Is it bad to redirect http to https?

Question: I just installed an SSL Certificate on my server.
It then set up a redirect for all traffic on my domain on Port 80 to redirect it to Port 443.
In other words, all my http://example.com traffic is now redirected to the appropriate https://example.com version of the page.
The redirect is done in my Apache Virtual Hosts file with something like this...
RewriteEngine on
ReWriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]

My question is, are there any drawbacks to using SSL?
Since this is not a 301 Redirect, will I lose link juice/ranking in search engines by switching to https?
I appreciate the help. I have always wanted to set up SSL on a server, just for the practice of doing it, and I finally decided to do it tonight. It seems to be working well so far, but I am not sure if it's a good idea to use this on every page. My site is not eCommerce and doesn't handle sensitive data; it's mainly for looks and the thrill of installing it for learning.

UPDATED ISSUE
Strangely Bing creates this screenshot from my site now that it is using HTTPS everywhere...

Comment: [WTF - I can't add answer (though seems I have enough rep).] My answer would (in part) be that __SOMETIMES IT IS BAD__. Consider passing a COOKIE or API Key in a GET over HTTP. If your site redirects HTTP requests to HTTPS requests, these calls would work, but the COOKIE or API Key would be transmitted in the clear - exposed. Some APIs turn HTTP off, a more robust approach - no HTTP at all so you can't even get it working unless you use HTTPS. Example: "All API requests must be made over HTTPS. Calls made over plain HTTP will fail" from https://stripe.com/docs/api?lang=php#authentication
Comment: @codingoutloud - the alternative is that the *whole thing* happens over HTTP with no HTTPS at all. How is that any better?
Comment: @BenCrowell, that's because a [captive portal](http://en.wikipedia.org/wiki/Captive_portal) looks an awful lot like an [`sslstrip`](http://www.thoughtcrime.org/software/sslstrip/)-style redirect attack (they're both man-in-the-middle request hijacks) so [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security)-aware browsers will block them both.
Comment: be aware that using https means everything you include should also be https or it might not load - eg load jquery using `src="://example.com/jquery.js"` - note the lack of `http` or `https` so the browser loads the appropriate one. I had a nightmare trying to get some embedded Amazon stuff to load properly as the API (loaded via https) produced http links - meaning they didn't work properly until I found the undocumented parameter to toggle https links
Comment: Jason; your update should be a new question, probably on [webmasters.se] as it's unrelated (technically) to your original question.  But it's probably that your style sheets are coming from an insecure domain.
Comment: I've seen sites that put up a site over http saying this site must be accessed over SSL and provide a linky with the https:// part
Comment: @codingoutloud if you don't have more than 10 reputation **in [sf]** you can't answer protected questions.
Comment: This is an added comment on an old thread, but there's some misinformation here.  If you follow the best practice of marking sensitive cookies (API keys, etc.) as `SECURE`, the browser *will not* send them to the server *unless* the request is made over SSL.  This makes the first comment misleading and incorrect.  If you have properly marked the cookie as `SECURE` when it is set (and, obviously, set it while in an SSL channel) then redirecting HTTP to HTTPS is perfectly safe.
Comment: Google started doing this last year. This seems to have led to the following problem on the wifi network at the college where I work. You pop up a browser and type google.com in the URL bar. It redirects you to a login page where you're supposed to provide your credentials for using the wifi network. But this then leads to an error, apparently because the redirect is detected as some kind of attempt to subvert the ssl connection. I don't claim to understand the full technical analysis of this situation, but it is a real-world problem that has occurred because of redirecting http to https.
Answer: The [R] flag on its own is a 302 redirection (Moved Temporarily). If you really want people using the HTTPS version of your site (hint: you do), then you should be using [R=301] for a permanent redirect:
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

A 301 keeps all your google-fu and hard-earned pageranks intact. Make sure mod_rewrite is enabled:
a2enmod rewrite

To answer your exact question:

Is it bad to redirect http to https?

Hell no. It's very good.
Comment: @AdamDavis The crypto algorithm may be lightweight, but the handshake overhead still exists. Also, HTTPS prevents HTTP proxies from caching your content. In _most_ cases, the overhead of HTTPS is minimal and worthwhile, but be careful about over-generalizing.
Comment: *"it uses a lot more server resources to run it on every page."* Modern CPUs have encryption acceleration features that make SSL nearly free.  Don't worry about overhead.
Comment: @jasondavis Only if you don't spend a few minutes to [optimize it](https://insouciant.org/tech/ssl-performance-case-study/).
Comment: It kills shared caching, which is useful for some site's usage patterns, and often protects little (is it important that people can know you visited the site, but not the details of what you did? That's the only situation where SSL is useful). The main advantage of SSL on every resource isn't that you need to "secure" e.g. people looking at "about us", but that you can't slip up and fail to use it in a case where you should.
Comment: Thanks for the information, my boss is telling me the reason he only runs https on certain pages of his site, is that it uses a lot more server resources to run it on every page.  Do you know anything about that or if that's true?
Comment: +1 for the `Hell no. It's very good.`  That was my immediate thought when I read the question title.
Comment: Upvote for the last line.. well said
Comment: If you *really* want people to use HTTPS, shouldn't you also set an HSTS header?
Comment: @atk - Actually, SSLStrip is defeated by an existing bookmark that goes to an HTTPS page in the first place.  It works by intercepting an HTTP connection first, and preventing it from ever going to HTTPS.  A connection that starts out as HTTPS can only be defeated by a corrupt CA.
Comment: @Brilliand, you are correct about that, but that wasn't my point ;-). The original question is if it is ok to redirect from http to https, which is exactly what sslstrip was designed to exploit.
Comment: Mark, doesn't the comments on the article that you linked to agree that you _do_ lose something in the redirect - just not _more_ than in a normal link (ie, if your page had a 'forward' link)?
Comment: @jasondavis The overhead of encryption is unlikely to make much of a difference, especially now that the SSL negotiation is usually cached for a time.  The advantage of encryption is that you're not letting the world see your data, passwords, etc.
Comment: From a security perspective, it's actually a bad practice.  There are tools like sslstrip that are specifically designed to take advantage of servers that create an http connection and redirect the victim to the malicious server, while the malicious server plays MitM with the victim and the real server.  In this case, it doesn't matter if the malicious redirect is http or https because if it's https, it's a valid, secure connection to the malicious server, who creates their own valid, secure connection to the real server.
Comment: @NickT - sure, but that's way outside the scope of the question. Anders covers that in his excellent answer below: http://serverfault.com/a/570353/7709
Comment: @JonHanna : SSL has a huge advantage: it prevents selective blocking by places like China. Plaintext is routinely sniffed and your connection is automatically cut off when sensitive keywords go over the wire. With HTTPS, China needs to manually block the whole site, which they would generally be reluctant to do (collateral damage to the vast majority of non-sensitive things on your site). I would say things like news sites may find this useful.
Comment: @user54609 one doesn't need to force SSL for that scenario, though.
Comment: @user54609 and the case you give is in the set of cases where I said SSL is useful.
Comment: I would say, as a person who have many *personal and tiny* websites getting autoblocked by the GFW (my friends and I are all in China but I host everything overseas (way cheaper, censorship cannot delete your stuff permanently)), that set of cases is close to "all websites".
Comment: @200_success HTTPS isn't the real problem there, it's not using proper Cache-Control headers. HTTPS is fully cacheable when the appropriate headers are present; if they're absent it's assumed that the page is not cacheable.
Comment: @MichaelHampton I think he is referring to Squid intercepting caches at the ISP which saves bandwidth by intercepting HTTP entities and forcing a shared cache on its customers. I don't think those are popular outside of Australia (latency) or Chinese schools (more rigid censorship) though.
Comment: @user54609 He didn't _mention_ an intercepting cache...
Comment: Why use `mod_rewrite` when you can use the simpler `Redirect permanent / https://domain.tld/` in the vhost for the domain's port 80 listener?
Comment: why not `RewriteCond %{HTTPS} off` instead of matching on port number?
Answer: Whilst I support the idea of SSL only sites, I would say one drawback is overheads depending on your site design. I mean for example if you are serving lots of individual images in img tags, this could cause your site to run a lot slower.  I would advise anyone using SSL only servers to make sure they work on the following.

Check the entire site for internal links and ensure they are all using HTTPS if you specific your own domain name in links, so you are not causing your own redirects.
Update your <meta property="og:url" to using the https version of your domain.
If you use <base href= again update to use HTTPS.
Install SPDY protocol if possible
Make sure to use CSS Image sprites where possible, to reduce numbers of request.
Update your sitemaps to indicate https status, so spiders over time learn this change.
Change Search Engine preferences like Google Webmaster Tools to prefer HTTPS
Where possible off-load any stactic media to HTTPS CDN servers.

If the above is addressed, then I doubt you will have many issues.
Comment: Using "//yourserver.com/some-uri" instead of "http://yourserver.com/some-uri" resolves issue (1) because the browser will pick the appropriate schema (http or https) depending on the schema the page was loaded with.
Comment: Google sees the URL someone is visiting via the `Referer` header. For example this site uses jQuery from Google's CDN and my browser sends a request to Google every time I reload the site. Thereby a `Referer` header is also send to Google which is set to the URL of this site. So Google can track the sites I visit during the time my IP address does not change (and if I use a Google service during this time, Google can also connect this information with my Google account).
Comment: @MauganRa Unless, of course, it's a link from http article page to https login page, for example.
Comment: For 1) I just did a search and replace in my MySQL database http to https...i'm using WordPress so it made it real easy to update hundreds of links
Comment: SPDY is a good suggestion; there even appears to be a module [adding SPDY support to Apache 2.x](https://code.google.com/p/mod-spdy/).
Comment: A question about the 8th point: One reason to use HTTPS only Servers is to protect the visitor's privacy. So I have to use a CDN which also respect it, right? For example, if I decide to use a HTTPS only server, I should not use [Google hosted libraries](https://developers.google.com/speed/libraries/devguide?hl=de). Do you think this reasoning is right?
Comment: @tampis I don't see it as a privacy issue - Google Hosted Libraries or other public CDNs improve speed and caching, and they aren't provided any data about the site you are visiting (if your site includes jQuery from, for example, Google's CDN, google don't see the URL). Further, the use of jQuery itself or other libraries is not a privacy risk as they aren't incriminating in any way, users do not choose them and have no awareness of them, and the resources tend to be extremely common and provide a large number of use cases, so cannot be tied to specific functionality either.
Comment: I installed the Apache module for SPDY, it caused complete chaos on my server though as you have to disable mod_php anbd instead use fcgid I think it's called...anyways trying to use that handler for PHP was a no go for my site as it broke all my virtualhosts files
Comment: @jasondavis For absolute links to your own site, you could also use the protocol-relative `://` prefix. (I.e. without the leading `http` or `https`.) Just in case you ever decide to change this back, or someone invents a new web protocol with a different scheme ;)
Answer: I you've set up https then you should use it everywhere on the site. You will avoid the risk of mixed content issues and if you have the required tools in place, why not make the entire site secure?
Regarding redirection from http to https the answer is not that simple.
Redirecting will make it a lot easier for your users, they just type in whateversite.com and gets redirected to https.
But. What if the user is sometimes on an unsecure network (or is close to Troy Hunt and his Pineapple)? Then the user will request http://whateversite.com out of old habit. That is http. That can be compromised. The redirect could point to https://whateversite.com.some.infrastructure.long.strange.url.hacker.org. To an ordinary user it would look quite legit. But the traffic can be intercepted.
So we have two competing requirements here: To be user friendly and be secure. Fortunately, there is a remedy called the HSTS header. With it you can enable the redirect. The browser will move over to the secure site, but thanks to the HSTS header also remember it. When the user types in whateversite.com sitting on that unsecure network, the browser will go to https right away, without jumping through the redirect over http. Unless you deal with very sensitive data, I think that's a fair tradeoff between security and usability for most sites. (When I recently set up an application handling medical records I went all https without a redirect). Unfortunately Internet Explorer has no support for HSTS (source), so if your target audience is mostly using IE and the data is sensitive you might want to disable redirects.
So if you're not targetting IE users, go ahead and use redirect, but enable the HSTS header as well.
Comment: @Velox - I don't think the implication of "people assume they are secure because the end point is HTTPS, ignoring the fact that all the information sent to the page in GETs or POSTs is in plain text" is quite accurate. While there are some gotchas, GET query params don't travel in the clear during transport over HTTPS. See for example: http://stackoverflow.com/questions/323200/is-an-https-query-string-secure POST payloads are also protected, while also not vulnerable to logging and referrer headers.
Comment: @Velox - If the whole site is redirecting to HTTPS, then it's unlikely that any GET parameters will get sent before HTTPS has kicked in (and everything will stay HTTPS after that point).  There's still the one initial request where cookies will be sent, which can be remedied with HSTS... and a small attack window for SSLStrip, which could possibly be defeated by JavaScript, but that's an arms race of its own.
Comment: More people need to pay attention to this as well. Another thing is that people assume they are secure because the end point is HTTPS, ignoring the fact that all the information sent to the page in GETs or POSTs is in plain text.
Comment: @codingoutloud That's my point. Over HTTPS they are encrypted, but in the initial request to the HTTP page they were not.
Comment: @Brilliand Fair point, but a weak point in security makes the entire thing weak. Always worth considering.
Comment: Thank you for bringing up the security implications, of which there are many to be aware.
Comment: Getting your [HSTS settings preloaded](https://hstspreload.appspot.com/) is a further step that can be taken to address the issue of the very first request from a client possibly happening over HTTP.
Answer: There's nothing wrong with this, and in fact it's best practice (for sites that should be served over a secure connection). In fact, what you're doing is pretty similar to the configuration I'm using:
<VirtualHost 10.2.3.40:80>
  ServerAdmin firstname.lastname@example.com
  ServerName secure.example.com
  RedirectMatch 301 (.*) https://secure.example.com$1
</VirtualHost>

# Insert 10.2.3.40:443 virtual host here :)

The 301 status code indicates a permanent redirect, instructing capable clients to use the secure URL for future connections (e.g. update the bookmark).
If you'll only be serving the site over TLS/SSL, I'd recommend a further directive to enable HTTP Strict Transport Security (HSTS) in your secure virtual host:
<IfModule mod_headers.c>
  Header set Strict-Transport-Security "max-age=1234; includeSubdomains"
</IfModule>

This header instructs capable clients (most of them these days, I believe) that they should only use HTTPS with the provided domain (secure.example.com, in this case) for the next 1234 seconds. The ; includeSubdomains portion is optional and indicates that the directive applies not just to the current domain, but any under it (e.g. alpha.secure.example.com). Note that the HSTS header is only accepted by browsers when served over an SSL/TLS connection!
To test your server configuration against current best practice, a good free resource is Qualys' SSL Server Test service; I'd be aiming to score at least an A- (you can't get more than that with Apache 2.2 due to the lack of support for elliptic curve cryptography).
Comment: I should add, sending the header `Strict-Transport-Security: max-age=0` will negate any previous directive; as always, this _must_ be sent over HTTPS to be accepted, but it's a handy way of cancelling things if you decide you also need to use HTTP on the domain.
Answer: Wow ! redirect HTTP to HTTPS is a very good thing and i cannot see any drawbacks for that.
Just make sure your clients have the right CA to avoid non user-friendly warnings about certificate in browser.
In addition, the way you have setup Apache to redirect to HTTPS seems ok.
Answer:

Is it bad to redirect http to https?

No, not at all. Actually, it is a good thing to do!
On redirects:
It could be more efficient, by completely eliminating the rewrites. Here's my config on a similar situation...
<VirtualHost *:80>
  ServerName domainname.com

  <IfModule mod_alias.c>
    Redirect permanent / https://domainname.com/
  </IfModule>
</VirtualHost>

Answer: HTTPS is not exactly foolproof.
Of course, normally forcing HTTPS is a good thing.
It prevents normal criminals from doing anything bad to your users.
But please remember to check you SSL Settings like the SSLCiphers setting.
Disable things like RC4 crypto, the SSLv2 and SSLv3 protocol.
Also, you should find out, whether the crypto-system libarys of your system support TLS1.2 (which is the thing you want to have ;) )
Turn on SSL, its a good thing.
Comment: Entropy doesn't get used up ([at least if you're defending against Earth-based attackers](http://security.stackexchange.com/questions/89/feeding-dev-random-entropy-pool/7074#7074) rather than [doing voodoo](http://security.stackexchange.com/questions/2604/evaluating-the-entropy-gathering-in-a-prng/2605#2605)). Either you start with insufficient entropy, and you can't do anything that requires randomness, or you start with sufficient entropy, and you keep having sufficient entropy no matter how much randomness you generate.
Comment: Sorry, *what*?  There are a number of operations on Linux that insist on hardware-derived strong entropy rather than PRNG-based probably-good-enough entropy, and those can indeed block if the pool depth is low.  It is most certainly possible to start with sufficient entropy on a Linux system, but by overuse to drain the pool, causing some operations to block.
Answer: Personally I am all for the use of SSL to secure connections on the web, however I feel a point that all the other answers here have missed is that not every device and piece of software capable of an HTTP connection will be able to use SSL, thus I would consider providing some way for users to avoid it if it is not supported for them. It is also possible that people in some Countries where encryption tech is illegal will then not be allowed to access your site. I would consider adding an unencrypted landing page with a link to force the insecure version of the site but unless a user specifically selects such to do as you said and just forward them to the HTTPS version.
Comment: A problem with solutions like having a plain HTTP landing page, even if properly separated, is that this page is left open to manipulation. Ie, there's no actual guarantee that the link for the HTTPS version of the site is delivered intact to visitors.
Answer: Here are some of the broad brushstroke issues:

MITM/SSLSTRIP: This is a huge caveat. If you're going to serve your site over HTTPS, then disable HTTP on the site. Otherwise, you leave your users open to various man-in-the-middle attacks including SSLSTRIP, which will intercept requests and quietly serve them over HTTP, inserting their own malware script into the stream. If the user doesn't notice, then they'll think their session is secure when it actually isn't.

The issue with this, though, is that if your site is a public site and you just unceremoniously disable HTTP, you might lose a lot of visitors. It probably won't even occur to them to try HTTPS if the site won't load with HTTP.

If your site requires a secure login, then the entire user session should be secured. Don't authenticate over HTTPS, then redirect the user back to HTTP. If you do, again, you're leaving your users vulnerable to MITM attacks.  The standard approach to authentication these days is to authenticate once, then pass an authentication token back and forth (in a cookie). But if you authenticate over HTTPS then redirect to HTTP then a man-in-the-middle can intercept that cookie and use the site as if they are your authenticated user, bypassing your security.
The "performance" issues with HTTPS are for all practical purposes limited to the handshake involved in creating a new connection. Do what you can to minimize the need for multiple HTTPS connections from a URL and you'll be miles ahead. And that's frankly true even if you're serving your content over HTTP. If you read up on SPDY, you'll realize that everything it does is oriented toward trying to serve all the content from a single URL over a single connection. Yes, using HTTPS affects caching. But how many web sites are just static, cacheable content these days, anyway? You're likely to get more bang for your buck using caching on your web server to minimize redundant database queries retrieving unchanged data over and over again, and preventing expensive code paths from executing more often than necessary.
Comment: The thing you can do to actually address *sslstrip* is to use HSTS (preferrably [get your HSTS settings preloaded](https://hstspreload.appspot.com/)). Whether you accept requests over plain HTTP or not doesn't actually matter in this regard, a MITM can answer over plain HTTP (possibly proxying to your HTTPS site) even if you only accept HTTPS requests.
Comment: @HåkanLindqvist I really earned a downvote from you? Did I give bad advice or good advice with regard to not authenticating over HTTPS then switching to HTTP for the rest of the session? Did I provide bad counsel with regard to HTTPS performance myths? Also, if the client initially attempts to connect using HTTPS, the MITM cannot intercept and respond without triggering an alert in the browser, because their cert won't match unless they have a stolen or successfully forged cert. On the other hand, if the site accepts an HTTP connection, interception is easier. Either way, HTTPS raises the bar.
Comment: ..and of course I agree wholeheartedly with using HSTS.
Comment: My problem with the answer is the first item in the list claiming to address sslstrip while it actually doesn't (speaking of myths). What I was trying to get at in my initial comment is that if you have an active MITM (which is what you need for sslstrip in the first place), the attacker can essentially be "the site" from the perspective of the client; it's the attacker that decides if they want to accept plain HTTP connections from the client, how your actual web server behaves in that regard doesn't affect what the attacker can or will do.
Comment: @HåkanLindqvist Except that if the visitor is intentionally trying to connect with HTTPS, the attacker can't satisfy that request without throwing flags in the browser, unless they have managed to steal a server certificate or somehow successfully forge one, which they would have to do in order to switch the connection to HTTP. HTTPS *still* raises the bar. Of course if the visitor makes the initial connection attempt over HTTP, all bets are completely off.
Comment: Sure, if the client is using HTTPS from the beginning then the question as well as the first item (about sslstrip) in your answer are not applicable. I'm not sure that I understand the relevance of this argument, though. If you want to fix sslstrip you use HSTS (preferrably preloaded), then the client will know to never issue HTTP requests even if asked to do so, ie the "all bets are off" problem is solved. Disabling HTTP on the server doesn't have the same effect.
Answer: It is very good to redirect to HTTPS, but I read it also depends on how you organize the redirecting.
Making a dedicated virtual host for redirecting the incoming HTTP requests to your HTTPS connection as suggested in this answer on  security.stackexchange.com - sounds very smart and will close some additional security threats. A configuration in Apache would look something like this:
# Virtual host for rerouting
<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

# Virtual host for secure hosting on https
<VirtualHost *:443>
    ServerName www.example.com
    SSLEngine on
    Header set Strict-Transport-Security "max-age=8640000;includeSubdomains"

    ...site settings...

</VirtualHost>

Answer: the only technical draw back to HTTPS over HTTP is that it is computationally more expensive to process HTTPS requests than plain HTTP
However given that most modern servers have high powered CPU's this impact is usually negligible unless you are at extremely high levels of traffic at which point you are more than likely using load balancers anyway
With the advent of protocols like SPDY which require SSL/TLS to work, this actually counteracts the aforementioned computational overhead by giving significant performance improvements with regards to multiple requests and getting assets to the client faster overall.
Comment: The issue with HTTPS performance is that establishing a new connection is more expensive because there are more round-trips involved and because asymmetrical encryption/decryption is a lot more expensive than symmetrical encryption/decryption. Once the connection handshake establishes a shared symmetrical encryption key, the ongoing overhead is virtually irrelevant (very small). If you read up on SPDY, you'll see that the goal of all the fancy stuff it does is essentially to serve all the content from a URL over a single connection, mitigating the connection handshake overhead.

Is it bad to redirect http to https?


Ask services "Which user am I?", as defined by session id?

Question: Scenario: An external service wakes up. This could be a remote Drupal site running a cron , a mobile application being started or something completely different.
The service has a session id from it's last interaction with a Drupal site running Services.
How does this service go about asking the Drupal site: "Based on this session ID, who am I?"?
For a regular user on the Drupal site, /user will tell you who you are. However, when accessing [endpoints]/user through Services, you get an index of all users, instead of a specific user object.
If possible, please include json as the content type for any code examples.
Comment: When you connect to an endpoint with session authentication you should be receiving a user object back, which matches the user that's logged in. I think that would be the most reliable way to check, short of writing your own 'whoami' resource (which actually would be very easy, let me know if you want me to dump some code in)
Comment: Hmm, are you saying _all_ resources in an endpoint will return the user? That doesn't seem to be the case for me, nor do I understand why that would be? If there is no "whoami" by defalt in services, then please dump the code :) If so, are you ok with me making it a patch against services?
Comment: Nah it won't come back for all resources, but standard practice is to authenticate, save the session id and any other user information you need for the rest of the session somewhere local to the calling app, then use that session id to make subsequent connections. That way you've got everything linked up and you don't need to establish a new session for every call (unless there's enough time between them that the session will expire, your app should be checking for that). I'll put some code together for a resource after I've made a coffee ;) Oh and yeah feel free to submit it as a patch
Comment: Ok, thanks. I sort of realised that between my comment and your second one. In my case, use of [IP Login](http://drupal.org/project/ip_login) means the login action is implicit, and the user object doesn't get returned.
Comment: Ah ok, not used that module before it looks interesting
Answer: This service resource simply return an object representing the currently authenticated user:
<code>/**
 * Implements hook_services_resources().
 */
function MYMODULE_services_resources() {
  $resources['MYMODULE'] = array(
    'actions' => array(
      'whoami' => array(
        'help' => 'Get an object referring to the currently authenticated user.',
        'callback' => '_MYMODULE_whoami_service_resource',
        'access callback' => 'services_access_menu'
      )
    )
  );

  return $resources;
}

/**
 * Resource callback
 */
function _MYMODULE_whoami_service_resource() {
  return $GLOBALS['user'];
}
</code>
Once enabled you should be able to access the resource at http://site.com/[endpoint]/MYMODULE/whoami.json.
Comment: Thanks! I unfortunately get `404 Not found: Could not find the controller.` when I try. I've ensured I copy paste the resource name in place of MYMODULE, and whoami from the action name, into the url. I'll try to debug it and see what I can figure out. Some quick hacking shows the access callback being called atleast.
Comment: Ah, I was GETing an action, which doesn't work. With POST it worked as expected, thanks again! :)
Comment: Oops yeah should have mentioned, sorry :)
Comment: Published as a sandbox project. Updated your answer to show both that it works and is published.


The probability that the problem is solved correctly by at least one of them

Question: Question: Four persons independently solve a certain problem correctly with probabilities 1/2, 3/4, 1/4 and 1/8.Then the probability that the problem is solved correctly by at least one
of them is ?
Solution:
say P(A)=1/2, P(B)=3/4, P(C)=1/4, P(D)=1/8
and P(A')=1 -1/2 = 1/2, P(B')= 1 - 3/4 = 1/4, P(C') = 1 - 1/4 = 3/1, P(D') = 1 - 1/8 = 7/8
Probability(at least one of them solves correctly) = 1-  Probability(None of them solves correctly)
Probability(None of them solves correctly) = P(A').P(B').P(C').P(B') = 1/2 * 1/4 * 3/4 * 7/8 = 21/256
P(at least one of them solves correctly) = 1 - 21/256 = 235/256. This is the complimentary method and it's the correct answer.
But when I try to do the direct method i.e
Required probability = (Number of ways at least one solved)/(Total number of ways all solved)
Number of ways at least one solved =  [P(A).P(B').P(C').P(D') ] + [P(A').P(B).P(C').P(D')] + [P(A').P(B').P(C).P(D')] + [ (P(A').P(B').P(C').P(D)]
= [1/2 * 1/4 * 3/4 * 7/8] + [1/2 * 3/4 * 3/4 * 7/8} + [1/2 * 1/4 * 1/4 * 7/8] + [1/2 * 1/4 * 3/4 * 1/8]
= 21/256 + 63/256 + 7/256 + 3/256
= 94/256
Total number of ways all solved = P(A) * P(B) * P(C) 8 P(D)
= 1/2 * 3/4 * 1/4 * 1/8 = 3/256
Required probability = (Number of ways at least one solved)/(Total number of ways all solved)
= $\frac{\frac{94}{256}}{\frac{3}{256}}$ = $\frac{94}{3}$
I know the probability shouldn't be greater than 1. Where am I doing wrong. Thanks.
Comment: In the second method you are calculating the probability that exactly one of them answers correctly. But you want the probability that at least one solves it correctly. So if you want to do it that way, you should add the probability that exactly 1 answers correctly + probability exactly two answer correctly, etc, and you should arrive to the same result. However, this is more tedious, so I would suggest using only the first method.
Comment: You should use [MathJax](https://math.stackexchange.com/help/notation) not only when you type fractions, but when you type **any** mathematical formula. $P(A)$ is a formula, so you type $\text{\$P(A)\$}$, and so on.
Answer:
Number of ways at least one solved = [P(A).P(B').P(C').P(D') ] + [P(A').P(B).P(C').P(D')] + [P(A').P(B').P(C).P(D')] + [ (P(A').P(B').P(C').P(D)]

If you add probabilities you can't get the number of ways. The probability is a real number in $[0,1]$, the number if ways is a non-negative integer.
What you found here is the probability that exactly one person solved the problem, not at least one.

Total number of ways all solved = P(A) * P(B) * P(C) * P(D)

This is the probability that everyone solved the problem. It happens rarely, this is nowhere near total something.
You first reasoning is correct. Just use that.
If you want to use the "direct" reasoning, you should add probabilities that exactly one person solved the problem (which you found), probabilities that exactly two persons solved the problem ($\binom42=6$ more summands), probabilities that exactly three persons solved the problem ($\binom43=4$ more summands), and finally the probability of everyone solving the problem (which you also found). Look at how tedious the "direct" calculation is:
$$\left(\frac12 \cdot\frac14 \cdot\frac34 \cdot\frac78+
\frac12 \cdot\frac34 \cdot\frac34 \cdot\frac78+
\frac12 \cdot\frac14 \cdot\frac14 \cdot\frac78+
\frac12 \cdot\frac14 \cdot\frac34 \cdot\frac18\right)+$$
$$+\left(\frac12 \cdot\frac14 \cdot\frac14 \cdot\frac18+
\frac12 \cdot\frac34 \cdot\frac34 \cdot\frac18+
\frac12 \cdot\frac34 \cdot\frac14 \cdot\frac78+
\frac12 \cdot\frac14 \cdot\frac34 \cdot\frac18+
\frac12 \cdot\frac14 \cdot\frac14 \cdot\frac78+
\frac12 \cdot\frac34 \cdot\frac34 \cdot\frac78\right)+$$
$$+\left(\frac12 \cdot\frac34 \cdot\frac14 \cdot\frac18+
\frac12 \cdot\frac14 \cdot\frac14 \cdot\frac18+
\frac12 \cdot\frac34 \cdot\frac34 \cdot\frac18+
\frac12 \cdot\frac34 \cdot\frac14 \cdot\frac78\right)+$$
$$+\frac12\cdot\frac34 \cdot\frac14 \cdot\frac18=$$
$$=\frac{235}{256}.$$


Conversão de date javascript para sqlserver

Question: Estou tentando salvar um campo do tipo data no banco SQLSERVER, porém ele não insere, está me retornando o seguinte erro:

Seqüência não foi reconhecida como DateTime válido.

DateTime dat = DateTime.ParseExact(txtVencimentoC.Text, "dd/MM/yyyy", null);
cadastrocontasreceber.Vencimento = dat;

Tentei dessa forma, e de outras várias, porém todas me retornam o erro.
Como estou fazendo a soma de datas pelo javascript, o campo fica deste formato "Sun Nov 19 2017 00:00:00 GMT-0200 (Horário brasileiro de verão)"
Como posso fazer para formatá-lo para DateTime no SqlServer, ou como posso configurar dentro do javascript passando para o txtVencimentoC já formatado? Pois todas as formas me retornam o mesmo erro. Agradeço.
Comment: Não sei se irá funcionar, mas tente converter esta data para timestamp e aí sim mandar para o sql. Veja aqui como gerar o timestamp: https://stackoverflow.com/questions/9873197/convert-date-to-timestamp-in-javascript
Answer: Utilizei este link como referência.
Ficou desta forma no código:

document.getElementById("<%= txtVencimentoC.ClientID %>").value = data.format("dd/MM/yyyy HH:mm:ss");


JSON stringify manipulation

Question: Take the code:
<code>JSON.stringify({ "x": 1.0 });
</code>
the output will be
<code>{"x":1}
</code>
I have tried everything using toFixed(), parseFloat(), +() and many others but cannot for the life of me get it to return:
<code>{"x":1.0}
</code>
I can get it to return:
<code>{"x":"1.0"}
</code>
but I just can't get
<code>{"x":1.0}
</code>
Is this possible? I am leaning towards no.
Comment: If you can't figure out a way, I would suggest adding post processing to the string if your object is predictable enough. Check for a decimal place after your var name and value and if it lacks one add ".0".
Answer: If you need the float to be displayed in a particular way, you need to leave it as a string.
However a better solution would be to just leave it as a Number and let the client/view format it.
Comment: I'm submitting the JSON data against a java servlet that requires the number to be a double. It fails otherwise.

JSON stringify manipulation


Minus query in SQL Oracle

Question: I was trying to do subtract between two of single float value from two tables:
The first one is:
select sum (cost) as "total cost" from (SELECT *
FROM PRODUCT
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)

It returns 240.
The second one is :
select sum (price) as "total price" from (SELECT *
FROM PRODUCT
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)

It returns 140.
So this is what I tried:
select sum (cost) as "total cost" from (SELECT *
FROM PRODUCT
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)
minus
select sum (price) as "total price" from (SELECT *
FROM PRODUCT
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)
;

But it returned 240... What's wrong ?
Comment: Sample data and desire results would help.
Answer: The MINUS operator does not do what you expect : it does not substract values, it operates on datasets (return all rows in the first SELECT statement that are not returned by the second SELECT statement).
Also, you don't need to use a subquery to compute the SUM, like : SELECT SUM(cost) from (SELECT...) ; I removed it.
I guess that you just want  :
SELECT
    SUM(cost) - SUM(price)
FROM
    product
    LEFT JOIN sell_bill ON sell_bill.product_id = product.id
WHERE product.cost > sell_bill.price

Answer: You can try below -
SELECT sum (cost)-sum (price) as difference
FROM PRODUCT
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE product.cost > sell_bill.PRICE

Minus query in SQL Oracle


How to save a file using file_save_upload in multistep AJAX form

Question: How can I save a file using file_save_upload in a AJAX multistep form? This works for a simple form, but I'm not sure where I'm going wrong in the multistep. Any help is very much appreciated!
File save works in simple form:
function xmlimport_form_submit($form, &$form_state){
$validators = array('file_validate_extensions' => array());
$file = file_save_upload('fid', $validators,'public://',FILE_EXISTS_RENAME);
 }

But doesn't seem to work in multistep. The error I get in my block says, "No file chosen" when I click Next Step on my form. AJAX form taken from Form API Example module.
function xmlimport_wizard($form, &$form_state) {

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['#tree'] = TRUE; // We want to deal with hierarchical form values.

  $step = empty($form_state['storage']['step']) ? 1 : $form_state['storage']['step'];
  $form_state['storage']['step'] = $step;

  switch ($step) {
    case 1:
      $form['step1'] = array(
        '#type' => 'fieldset',
        '#title' => t('Step 1: Log RFI from XML'),
      );
      $form['step1']['fid'] = array(
        '#type' => 'file',
        '#title' => t('Your XML file'),
        '#default_value' => empty($form_state['values']['step1']['fid']) ? '' : $form_state['values']['step1']['fid'],
        '#required' => TRUE,
      );
      break;

    case 2:
      $form['step2'] = array(
        '#type' => 'fieldset',
        '#title' => t('Step 2: Street address info'),
      );
      $form['step2']['project'] = array(
        '#type' => 'textfield',
        '#title' => t('Project Name'),
        '#default_value' => empty($form_state['values']['step2']['project']) ? '' : $form_state['values']['step2']['project'],
        '#required' => TRUE,
        '#size' => 23,
      );
      break;
  }
  if ($step == 2) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t("Submit your information"),
    );
  }
  if ($step < 2) {
    $form['next'] = array(
      '#type' => 'submit',
      '#value' => t('Next step'),
      '#ajax' => array(
        'wrapper' => 'wizard-form-wrapper',
        'callback' => 'xmlimport_wizard_callback',
      ),
    );
  }
  if ($step > 1) {
    $form['prev'] = array(
      '#type' => 'submit',
      '#value' => t("Previous step"),

      // Since all info will be discarded, don't validate on 'prev'.
      '#limit_validation_errors' => array(),
      // #submit is required to use #limit_validation_errors
      '#submit' => array('xmlimport_wizard_submit'),
      '#ajax' => array(
        'wrapper' => 'wizard-form-wrapper',
        'callback' => 'xmlimport_wizard_callback',
      ),
    );
  }
  return $form;
}

function xmlimport_wizard_callback($form, $form_state) {
    $validators = array('file_validate_extensions' => array());
    $file = file_save_upload('fid', $validators,'public://',FILE_EXISTS_RENAME);

  return $form;
}

/**
 * Submit function for xmlimport_wizard.
 *
 * In AJAX this is only submitted when the final submit button is clicked,
 * but in the non-javascript situation, it is submitted with every
 * button click.
 */
function xmlimport_wizard_submit($form, &$form_state) {

  // Save away the current information.
  $current_step = 'step' . $form_state['storage']['step'];
  if (!empty($form_state['values'][$current_step])) {
    $form_state['storage']['values'][$current_step] = $form_state['values'][$current_step];
  }

  // Increment or decrement the step as needed. Recover values if they exist.
  if ($form_state['triggering_element']['#value'] == t('Next step')) {
    $form_state['storage']['step']++;
    // If values have already been entered for this step, recover them from
    // $form_state['storage'] to pre-populate them.
    $step_name = 'step' . $form_state['storage']['step'];
    if (!empty($form_state['storage']['values'][$step_name])) {
      $form_state['values'][$step_name] = $form_state['storage']['values'][$step_name];
    }
  }
  if ($form_state['triggering_element']['#value'] == t('Previous step')) {
    $form_state['storage']['step']--;
    // Recover our values from $form_state['storage'] to pre-populate them.
    $step_name = 'step' . $form_state['storage']['step'];
    $form_state['values'][$step_name] = $form_state['storage']['values'][$step_name];
  }

  // If they're done, submit.
  if ($form_state['triggering_element']['#value'] == t('Submit your information')) {
    $value_message = t('Your information has been submitted:') . ' ';
    foreach ($form_state['storage']['values'] as $step => $values) {
      $value_message .= "$step: ";
      foreach ($values as $key => $value) {
        $value_message .= "$key=$value, ";
      }
    }
    drupal_set_message($value_message);
    $form_state['rebuild'] = FALSE;
    return;
  }

  // Otherwise, we still have work to do.
  $form_state['rebuild'] = TRUE;
}

Comment: have you tried instead of using `'#type' => 'file'` for your file upload field to use the `'#type' => 'managed_file'`? it's easier to validate and it's ajax enabled by default. You can read more about it [here](http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file)
Comment: @MariusIlie thanks this exactly what I was looking for! Please add your comment as an answer so I can +1 it and close the loop for others. Thanks again, this was a stumper!
Comment: I added the comment as an answer. Cheers :)
Answer: have you tried instead of using '#type' => 'file' for your file upload field to use the '#type' => 'managed_file' ? it's easier to validate and it's ajax enabled by default. You can read more about it here
Answer: You can try this!!
$form['--Name--'] = array(
         '#type' => 'managed_file',

        '#name' => 'files[]',

        '#title' => t('Upload some multifile'),

        '#description' => t('Allow to upload jpg, jpeg and png, 5MB Max Size'),

        '#attributes' => array('multiple' => 'multiple'),

  );


Definition of a submanifold

Question:
Say what it means for a system of equations
$$f_1 = \cdots = f_m = 0,$$
where $f_i(x_1, \cdots x_n)$ are differentiable functions, to define a submanifold near a point $a = (a_1, \cdots a_n), f_i(a) = 0, i = 1, \cdots m$.

From my understanding, a submanifold is patches of various surfaces put together, but I don't see how I can get that definition from this.
Comment: Do you mean to have $f_1,\ldots,f_m$ *and* $x_1,\ldots,x_m$? That means $f : \mathbb{R}^m \to \mathbb{R}^m$. Usually, you expect $f : \mathbb{R}^{m+k} \to \mathbb{R}^m$, and $f^{-1}(0)$ is a $k$-dimensional submanifold.
Comment: @FlybyNight sorry, the $x$'s were supposed to go to $n$
Comment: Do you also want $n > m$?
Comment: @FlybyNight It doesn't say
Comment: In general, if $n < m$ then the solution to $f_1 = \ldots = f_m = 0$ will be empty. You're trying to solve $m$-equations in $n$-variables. More equations that variables is bad news. If $m=n$, the solution set will, generically, be a set of isolated points. In $n>m$ then, generically, the solution set will be a manifold of dimension $n-m$.
Answer: I'm not sure if this is what you mean, but let $\operatorname{f} : \mathbb{R}^{n} \to \mathbb{R}^m$, where $n > m$. The $m$-by-$n$ Jacobian matrix is given by:
$$\left[ \begin{array}{ccc} \partial\operatorname{f}_1/\partial x_1 & \cdots &  \partial\operatorname{f}_1/\partial x_n \\ \vdots & \ddots & \vdots \\  \partial\operatorname{f}_m/\partial x_1 & \cdots &  \partial\operatorname{f}_m/\partial x_n \end{array}\right]$$
A point $x \in \mathbb{R}^n$ is called a regular point if the Jacobian matrix has maximal rank, i.e. rank $m$, when evaluated at $x$. A point $y \in \mathbb{R}^m$ is called a regular value if all of the points $x \in \mathbb{R}^n$ for which $\operatorname{f}(x)=y$ are regular points. In such a case, the pre-image of a regular value is a smooth parametrisable manifold.
In your case, if all of the $x \in \mathbb{R}^n$ for which $\operatorname{f}(x)=0$ are regular points then the level-set $\operatorname{f}^{-1}(0)$ is a smooth parametrisable manifold. This is the Implicit Function Theorem.
In practise: Find all of the $x \in \mathbb{R}^n$ (critical points) for which the Jacobian has rank less than $m$. Then find all of the images $\operatorname{f}(x)$ (critical values). Just check that $0 \in \mathbb{R}^m$ is not a critical value.
Comment: I thought the Implicit Function Theorem was just a theorem saying that you can write a multi variable function as a series of functions?
Comment: Absolutely not. It's a theorem which tells you that the pre-image of a critical value can locally be parametrised as a graph of a (multi-variable) function.

Definition of a submanifold


AWS - Where should we store images, CSS and log files of the application?

Question: Looking for a clarification and guidance on the best practice.
Where should we store images, CSS and log files of the application? Application server or S3?
We will be storing user related images and thumbnails on S3. We will not be using CloudFront at this stage until there is a real need.
Another set of questions I have is related to EBS. Should the application server use EBS volume? What is the benefit of doing this? Would we pay extra for using EBS.
Thanks.
Answer: Yes EBS costs extra. The advantage to EBS is that is simple to access, it shows up as a drive on your server, versus S3 which you have to go through their API. Also, EBS content is permanent. Anything you store in your instance (not inside S3 and not inside an EBS volume) is not permanent, and can disappear if your machine is restarted.
S3 is a bad idea for log files, since you cannot append to an object in S3. User data that doesn't change too often (like only a couple times a day or less) makes sense in S3. Something that changes all the time might make more sense in a database (stored on EBS).
Comment: @davr. So you are recommending that application related images, CSS and log files should be stored on EC2 instance. Do we need an EBS volume for that instance, given that the image of the instance will be stored on S3?

I thought it was a good idea to store user images directly on S3?

Thanks for your help.
Comment: I think you just need to do some research / play around with it first, so you can see the advantages / disadvantages of EBS and S3.
Answer: You could use an Amazon EBS backend instance for all your needs.
Answer: EBS is a product oriented to increase disk access performance and availability.
The ephimeral storage is suboptimal for I/O operations.
Using EBS, you can still access your data if you can't access your instance.
Is perfect to store critical data or a database.
Store all css, js, css related images using CloudFront. To do this you have to store the files first in S3, then apply CloudFront to your bucket.  Make use of the special header (Expires, Cache-Control), so the users only download this element one time.
Also you can backup your logs to S3 for permanent storage using s3cmd or duplicity. Is a cheap option and you don't run out of disk space.


Classification algorithms that return confidence?

Question: Given a machine learning model built on top of scikit-learn, how can I classify new instances but then choose only those with the highest confidence? How do we define confidence in machine learning and how to generate it (if not generated automatically by scikit-learn)? What should I change in this approach if I had more that 2 potential classes?
This is what I have done so far:
<code># load libraries
from sklearn import neighbors
# initialize NearestNeighbor classifier
knn = neighbors.KNeighborsClassifier(n_neighbors=3)
# train model
knn.fit([[1],[2],[3],[4],[5],[6]], [0,0,0,1,1,1])
# predict ::: get class probabilities
print(knn.predict_proba(1.5))
print(knn.predict_proba(37))
print(knn.predict_proba(3.5))
</code>
Comment: In general if you want to get confidence values or probabilities, you should look at the statistical or bayes based machine learning algorithms.
Comment: Do you want confidence in the statistical sense, or just some measure of positiveness? If the latter is fine, then you don't need probabilistic models.
Answer: Three questions:

"How do we define confidence in machine learning and how to generate it (if not generated automatically by scikit-learn)?"
Here's a great summary on different types of confidence measures in machine learning. The specific metric used depends on which algorithm/model you generate.

"how can I classify new instances but then choose only those with the highest confidence?
and,

"What should I change in this approach if I had more that 2 potential classes?"

Here's a quick script that you can play around with that expands on what you started with so you can see how to handle an arbitrary number of classes and finding the likely classes for each predicted example. I like numpy and pandas (which you're likely using if you're using sklearn).
<code>from sklearn import neighbors
import pandas as pd
import numpy as np
number_of_classes = 3  # number of possible classes
number_of_features = 2 # number of features for each example
train_size = 20        # number of training examples
predict_size = 5       # number of examples to predict
# Generate a random 2-variable training set with random classes assigned
X = np.random.randint(100, size=(train_size, 2))
y = np.random.randint(number_of_classes, size=train_size)
# initialize NearestNeighbor classifier
knn = neighbors.KNeighborsClassifier(n_neighbors=3)
# train model
knn.fit(X, y)
# values to predict classes for
predict = np.random.randint(100, size=(predict_size, 2))
print "generated examples to predict:\n",predict,"\n"
# predict class probabilities for each class for each value and convert to DataFrame
probs = pd.DataFrame(knn.predict_proba(predict))
print "all probabilities:\n", probs, "\n"
for c in range(number_of_classes):
    likely=probs[probs[c] > 0.5]
    print "class" + str(c) + " probability > 0.5:\n", likely
    print "indexes of likely class" + str(c) + ":", likely.index.tolist(), "\n"
</code>
Answer: If you want confidence of classification result, you have two ways. First is using the classifier that will output probabilistic score, like logistic regression; the second approach is using calibration, like for svm or CART tree. you can find related modules in scikit-learn.


Como configurar cronjobs no cakephp?

Question: Como faço para usar o cronjobs no CakePHP, preciso chamar uma action de um controller no servidor linux, é o caminho do script?
Já tentei aqui e não deu certo!
Answer: O ideal é você fazer isto na sua camada de Model, acho que você deve repensar esta sua opção em chamar diretamente do Controller.
Para isso, você primeiro deve criar uma task shell, que será executada no agendador de tarefas do seu servidor. Vamos supor que você queira limpar uma tabela photos a cada meia-hora, então você cria uma task a partir de um arquivo app/Console/Command/PhotoShell.php mais ou menos assim:
class PhotoShell extends AppShell {
    public function limpar() {
        ClassRegistry::init('Photo')->limpar();
    }
}

E seu model Photo teria o método limpar() implementado assim:
public function limpar() {
    $this->query('TRUNCATE ' . $this->useTable);
}

Pronto, feito isto, basta incluir no seu cronjobs:
0,30 * * * * /app/Console/cake Photo limpar

Lembrando que o arquivo cake deve estar com as devidas permissões de execução.
Comment: Paulo, vou seguir suas dicas e efetuar as mudanças, valeu!!! ;)
Answer: Do próprio cakebook
  */5  *    *    *    *  cd /full/path/to/app && Console/cake myshell myparam
  # *    *    *    *    *  command to execute
  # │    │    │    │    │
  # │    │    │    │    │
  # │    │    │    │    \───── day of week (0 - 6) (0 to 6 are Sunday to Saturday,
    |    |    |    |           or use names)
  # │    │    │    \────────── month (1 - 12)
  # │    │    \─────────────── day of month (1 - 31)
  # │    \──────────────────── hour (0 - 23)
  # \───────────────────────── min (0 - 59)

http://book.cakephp.org/2.0/en/console-and-shells/cron-jobs.html
Comment: Eu já tinha visto este link mas não tinha entendido, da forma como o @PauloRodrigues explicou, ficou fácil.

Como configurar cronjobs no cakephp?


Help required for beginner!

Question: I am learning to play the piano and read music; I have only just started and so I apologise upfront if the question I am about to ask is a completely dumb one.
I was skimming through some sheet music for the Chopin Waltz in C# Minor Op. 64, No. 2 and I was wondering how one can tell that the C in the chord in the second bar is a C# and not just a C natural?

I would appreciate any help that you can give me please.
Thanks very much in advance.
Answer: The clue's in the title. The key of 4 sharps puts the key as in C♯ minor, so any C note in any octave will be sharp. As stated in the key signature itself, the C sharp notated there will represent all the c notes in all octaves, unless tempered with an accidental note before it. And, as Andy says, that's in the 1sst bar, as the bit before doesn't count as a full bar - only an anacrucis.

Help required for beginner!


Calculating the determinant by upper triangular reduction - can you check if it's correct?

Question: Exercise:

Calculate $$\begin{vmatrix}
a_0 & a_1 & a_2 & \dots & a_n \\
-x & x & 0 & \dots & 0 \\
0 & -x & x & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & x
\end{vmatrix}$$

My approach:
$$\begin{vmatrix}
a_0 & a_1 & a_2 & \dots & a_n \\
-x & x & 0 & \dots & 0 \\
0 & -x & x & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & x
\end{vmatrix} = x^n \begin{vmatrix}
a_0 & a_1 & a_2 & \dots & a_n \\
-1 & 1 & 0 & \dots & 0 \\
0 & -1 & 1 & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & 1
\end{vmatrix} = x^n \frac {1} {a_0} \begin{vmatrix}
a_0 & a_1 & a_2 & \dots & a_n \\
-a_0 & a_0 & 0 & \dots & 0 \\
0 & -1 & 1 & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & 1
\end{vmatrix} =  x^n \frac {1} {a_0} \begin{vmatrix}
a_0 & a_1 & a_2 & \dots & a_n \\
0 & a_0 + a_1 & a_2 & \dots & a_n \\
0 & -1 & 1 & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & 1
\end{vmatrix} = x^n \frac {1} {a_0} \frac {1} {a_0 + a_1} \begin{vmatrix}
a_0 & a_1 & a_2 & \dots & a_n \\
0 & a_0 + a_1 & a_2 & \dots & a_n \\
0 & - a_0 + a_1 & a_0 + a_1 & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & 1
\end{vmatrix} = x^n \frac {1} {a_0} \frac {1} {a_0 + a_1} \begin{vmatrix}
a_0 & a_1 & a_2 & \dots & a_n \\
0 & a_0 + a_1 & a_2 & \dots & a_n \\
0 & 0 & a_0 + a_1 + a_2& \dots & a_n \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & 1
\end{vmatrix} = \dots = x^n \frac {1} {(a_0)(a_0 + a_1) \dots (a_0 + a_1 + \dots a_{n-1})} \begin{vmatrix}
a_0 & * & * & * & \dots & * \\
0 & a_0 + a_1 & *&*& \dots & * \\
0 & 0 & a_0 + a_1 + a_2 & * & \dots & * \\
\dots & \dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & 0 & \dots & a_0 + a_1 + \dots a_n
\end{vmatrix} = (a_0 + \dots a_n) x^n$$
Comment: Have you checked your computations for $n=2$? I get that the determinant is $(a_0+a_1)x$ and [Wolfram](http://www.wolframalpha.com/input/?i=Determinant+%7B%7Ba_0,a_1%7D,%7B-x,x%7D%7D) agrees with me.
Comment: You're right, fixed it.
Answer: To verify this by other means, we denote the above determinant as $D_n$ and expand by cofactors along the last column. This yields $D_{n}=xD_{n-1}+x^n a_n$ with base case $D_0 =a_0$. (The $n$-by-$n$ submatrix in the corner yields $(-x)^n$, cancelling the $(-1)^n$ factor from the cofactor expansion.) It can then be readily checked that your result satisfies both this recurrence relation and the base case, so we conclude by mathematical induction that it is correct for all $n$.


If $M$ is a $R$ Module which has a finite generating system and $T$ is a submodule of $M$, is there a submodule $F$ such that $M=F\oplus T$?

Question: We know that in vector spaces such a complementary substructure exists. But in this proof we took advantage of the fact that every vector space has a basis, ie. the subvectorspace has a basis and this basis then can be extended to a full basis of the whole vector space and then the basis vectors which are only in the extension create a basis for the desired complement.
In an $R$-module $M$, where $R$ is a principal ideal domain, we cannot use this argument with a basis, is it still possible to find a submodule $F$ such that every element of $M$ can be expressed as $x=f+t$ with $f\in F$ and $t\in T$ and that every such description is unique? If it is not true for the general case, how can it be true if $T$ is the torsion submodule of $M$?
Comment: The terminology for this is "semisimple" https://en.wikipedia.org/wiki/Semisimple_module
Comment: @freakish There exists a finite System $(a_i)_n$ of Elements ins $M$ such that $\sum_i Ra_i=M$. The torision submodule $T$ of a module $M$ is the set $\{a\in M:\exists\alpha\in R-\{0\}:\alpha a=0\}$. It is indeed a submodule if you know that $R$ is  a principal ideal domain
Comment: @freakish how can you prove that $T$ is a direct summand?
Answer: It works for the torsion module primarily because a finitely generated module $M$ over a P.I.D. $R$, which is a noetherian ring, has a finite presentation, i.e. there exists an exact sequence
$$F_1\longrightarrow F_0\longrightarrow M\longrightarrow 0,$$
where $F_0$ and $F_1$ are finitely generated free modules. The map $F_1\longrightarrow F_0$ is represented by a matrix, and in suitable bases for $F_0$ and $F_1$, this matrix has a Smith normal form:
$$\begin{pmatrix}
d_1&0&0&\dots&0&\dots&0\\
0&d_2&0&\dots&0&\dots&0\ \\
0&0&d_3&\dots&0 &\dots&0\\
\vdots&&&\ddots&&&\vdots \\
0&0&0&&d_r&\dots&0\\
0&0&0&\dots&0&\dots&0 \\
\vdots&&&&&\ddots&\vdots\\
0&0&0&\dots&0&\dots&0
\end{pmatrix}$$
where $\;d_i\mid d_{i+1}$ for each $1\le i<r$. There results that the  module $M$ is isomorphic to
$$\underbrace{R/d_1R\times R/d_2R\times\dots\times R/d_rR}_{\text{torsion submodule}}\times R^{\text{rk}(F_0)-r}.$$
Comment: Why can you say that the left part of $\underbrace{R/d_1R\times R/d_2R\times\dots\times R/d_rR}_{\text{torsion submodule}}\times R^{\text{rk}(F_0)-r}.$ corresponds to the torision submodule?
Comment: The other factor is free, and the quotient is isomorphic to $M$.
Comment: With the Quotient you mean $R/d_1R\times R/d_2R\times\dots\times R/d_rR\times R^{\text{rk}(F_0)-r}.$?. I understand that this set is isomorphic to $M$. I also see that if M is free,the torision submodule is $0$. But I don't understand how this implies the existence of a $F$ such that $M=F\oplus T$. I think I also could prove that $R/d_1R\times R/d_2R\times\dots\times R/d_rR$'s torision submodule is it itself. To be more precise why if $\psi:M\rightarrow A\oplus B$ isomorph such that $B$ is torioson module of $A\oplus B$, why $\phi^{-1}(B)=T$ and $\phi^{-1}(A)=T$ as desired?
Comment: What you denote $F$  (the free part) is $R^{\text{rk}F_0-r}= and $T$ (the torsion part) is the contents of the underbrace. As to your last question, it is easy to check that a homomorphism maps torsion elements to torsion elements (including $0$ in $T$), and to deduce from this fact that an isomorphim maps the torsion submodule of its domain onto the torsion submodule of its codomain.
Answer: I presume that $R$ is always a PID here.

is it still possible to find a submodule $F$ such that every element of $M$ can be expressed as $x=f+t$ with $f\in F$ and $t\in T$ and that every such description is unique?

No. Consider $R=M=\mathbb{Z}$ and $T=2\mathbb{Z}$ and note that $\mathbb{Z}$ is not decomposable as a group, let alone as a module (well, over $\mathbb{Z}$ it is the same thing).
In fact rings with this property (i.e. every submodule is a direct summand) are precisely semisimple rings and these are all well known by the Artin-Wedderburn theorem. As a consequence an integral domain is semisimple if and only if it is a field. And so we are back at vector spaces.

If it is not true for the general case, how can it be true if $T$ is the torsion submodule of $M$?

It is true. Since $M$ is finitely generated then so is $M/T$. Also $M/T$ is torsion free, which I leave as an exercise. Finally finitely generated torsion free modules over PID are free, in particular projective. Therefore
$$0\to T\to M\to M/T\to 0$$
splits which shows that $T$ is a direct summand of $M$.


Can the captain change players' positions without permission from a coach or manager?

Question: In football, can the captain move players from one position into another, during the game, without the coach or manager telling them to?
Does the coach or manager need to give the captain permission for this to be done?
Comment: And as a tactical / coaching issue, it would be far too broad for Stack Exchange.
Comment: I've added the rules tag, since this question also seems to implicitly ask whether there is a rule preventing this (rather than it being simply a tactical/coaching issue).
Answer: Other than the goalkeeper, there are no positions defined in the Laws of the Game, so nobody needs "permission" from anybody play anywhere on the pitch. The captain, or anyone else on the team for that matter, can tell anyone to move into any position at all. Whether they'll be listened to our not is a different question of course, and that's down to the relationship between the manager, the captain and everybody else.
Answer: As stated by @PhilipKendall, there's no rule delimiting the functions of coaches and players. And to add to that: there's no rule that forces you to even have a coach present, nor for the coach to just coach.
In lower tiers, clubs with financial or management problems that can't find a coach, would play following the directions of the captain and/or the physical trainer. Take the example of Jumilla CF (Google-translated article), a modest Spanish "bronze division" team that's now in the top 3 of their group after surviving almost half the last season without a coach.
On the other side of the spectrum, a coach may choose to be a player himself too. When Zidane arrived to Real Madrid as a coach, there was some mild speculation about him actually playing some matches if he couldn't decide a lineup in time.
So much for rules about whether the captain can tell other players what to do :-)
Comment: What was spculated about Zidane actually came true with Giggs when he was in charge of MU's first team.
Comment: @Nij In Spain, football coaches are required to have a specific license in order to coach, which takes years and money to get (the higher the tier, the longer and pricier it gets). To be a physical trainer, however, the requirements are more relaxed: you can function as one after completing a 2-year course in a public school (basically free), so they are usually cheaper than a coach. Also, we're talking about local clubs,  where some amateurs will work for free just to support their team. It's easier to find an amateur sports masseur than an amateur licensed coach.
Comment: What teams are these that can afford a PT but not a coach?!


Convert Image to Base64String

Question: I need some help in convert image to base64string. I had used solution from similar question in stackoverflow but an error occured.
Solution used:
convert image into base64 in wp8
The problem lies on the Image's Source I used to set as a writeablebitmap but the outcome was a null exception.
This is my image source :
image123.Source = new BitmapImage(new Uri("/correct1.jpg", UriKind.Relative));

Error occured in this line :
WriteableBitmap wbitmp = new WriteableBitmap((BitmapImage)image123.Source);

The Error:
An exception of type 'System.NullReferenceException' occurred in System.Windows.ni.dll but was not handled in user code

My existing code as reference :
        image123.Source = new BitmapImage(new Uri("/correct1.jpg", UriKind.Relative));

        byte[] bytearray = null;

        using (MemoryStream ms = new MemoryStream())
        {
            if (image123.Source != null)
            {
                WriteableBitmap wbitmp = new WriteableBitmap((BitmapImage)image123.Source);
                wbitmp.SaveJpeg(ms, 46, 38, 0, 100);
                bytearray = ms.ToArray();
            }
        }
        str = Convert.ToBase64String(bytearray);

        binarytxt.Text = str;

I'm really desperate for help as this is my major project. Thanks in advance!
Comment: I copy pasted your code and it works fine, are you sure `correct1.jpg` is loaded into the Image correctly
Comment: @sa_ddam213 yes i commented out my codes expect for the image source, the image was loaded on to the control. I'm still getting the same error after several changes to the Uri string. By the way, I'm using windows phone 8 application template, just to clarify.
Answer: The codes are working correctly, just that it needs an EventHandler. I had used a Button_Click Listener to run the codes and it worked perfectly!

Convert Image to Base64String


How to check Django permissions in Vue JS template

Question: I would like to v-show a label based on a Django permission, like so:

    'Upload'

However, Vue JS complains because Property or method "False" is not defined on the instance but referenced during render..
Is there a way to access the permission inside v-show?
Comment: you can try to use tag lower `v-show="(!is_existing) && {{perms.auth.has_permission|lower}}">`
Comment: You'll need to package up the Django permissions object into an API call via the Rest Framework (e.g. make a ListView which uses Auth.Permissions as kit's queryset), then you can call the permissions via the API and load them into a Javascript variable.

Alternatively you could have an API method which checks if a permission string exists for a user.
Comment: @Darkstarone Okay. Thank you. I will do it this way.
Comment: That works, feel free to create an answer!
Comment: glad to help you
Comment: @Darkstarone how you access perms in vue js ? can you tell me how to use django permissions in vue js ?
Comment: @AjinkyaBhosale Django permissions work the same regardless of framework, if you have access to the template you can just use `{{perms.auth.*}}` like I did above, If you're seperated from Django (e.g. serving a seperate frontend from an API) you'll have to pass the permissions along via the API.
Comment: @Darkstarone I want to separate front end and backend. I have created API using Django Rest Framework and I am creating front end using vuejs.
Previously In django templates ,  I show menu's in base.html like follows
`{% if perms.cms.view_village %}
                     Village Master
                 {% endif %} `

How can I do same in front end ( vuejs ) ?
Answer: in js the boolean true is in lowercase but in the python start from capitalize, so you can try to use tag lower
v-show="(!is_existing) && {{perms.auth.has_permission|lower}}">


bitnami django, solution to restarting service?

Question: Hey I use installed bitnami django 1.3.0,
but whenever I add changes to urls.py or views.py in my system due to some error. The error won't disappear after refresh.
I have to restart my bitnami Service, "stop" and then "start" it, which is time consuming, I feel like I'm coding C# apps in visual studio.  Sometimes even that doesn't work, I have to sometimes restart my computer and then I suddenly realize "oh wow, the error is solved now!"
Any solution to this? Why does everything require a runserver / restart?
Answer: You can use Apache for deploy your application in production but use the Django server for development. You will need to configure your application for being served by apache later (modifying the settings.py and the apache configuration file) but during the development you won't need to restart the server for every change.
Comment: and how would I reconfigure bitnami or apache setup to use the "django server for development"? Is there a guide somewhere ?
Comment: You don't need change anything. Just start the django server with `python manage.py runserver` and work on your project. Once your application is ready for production you need to configure apache to serve your application. It will depend of your specific configuration and url mapping. This part more Apache related than django itself. (Don't hesitate to let me know if you find any issue with that, here or directly in bitnami forums)
Answer: Everything requires a restart because of the way that the python process operates. It does not reload the file when it's changed (outside of runserver..which is an anomaly, and just there for convenience)
Python execution isn't like PHP execution in that way, and your code isn't dynamically loaded on every page refresh, it's loaded on every server restart.
Hope that helps.
Comment: Isn't that a serious disadvantage for python, then there is no way python can overtake php then until someone solves this. This makes for incredibly slow development and stopping and starting a service takes forever.
Comment: There are loads of tradeoffs that get made when you pick a platform, and when laguages, platforms, and frameworks get designed and developed. You pick the ones that work well for you. This is one of the things that, while slightly annoying coming from a PHP background into Python, turns out to be totally reasonable for me. I do 100% of my development locally with runserver (which DOES refresh) and then you deploy your code out somewhere else, which DOES take a noticeable amount of time. It's not so bad though, because the language and framework are awesome.
Comment: Again I don't understand what do you mean it does refresh locally. My server is local and I have to stop and restart service every time now.


AutoIT UIAutomation extension for C#

Question: Started automating a windows application using Visual Studio with AutoIT.But facing problems with some controls and I came to know about the AutoIt UIAutomation. This is working fine in AutoIt Scite editor but how can we use this in Visual Studio 2015?Thanks in advance.
Answer: Edit: Per the comments of this thread, there is not a way to include other '.au3' files in C#. They'll need to be translated to C# :(

I misunderstood the question... this answers how to reference AutoItX in C#
Per this topic on the AutoIt Forums ...

Add a reference to AutoItX3.Assembly.dll to your project
Add a using AutoIt; statement in the files you want to use AutoIt functions

The AutoItX3.Assembly.dll is located in C:\Program Files (x86)\AutoIt3\AutoItX in a 'normal' installation

AutoIT UIAutomation extension for C#


Everything is correct but codeigniter showing Message: Undefined variable: data

Question: Please read the code below
Insertmodel.php
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Insertmodel extends CI_Model {

    public function insertdata($data)
    {
        $this->db->insert('page',$data);
    }
    public function getpagedata()
    {
        //$this->db->select('pname,purl,pub');
        //$this->db->from('page');
        //$this->load->database();

        $getquery = $this->db->get('page');
        return $getquery->result();
    }
}

Pagedatainsert.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pagedatainsert extends CI_Controller {

    public function insertdata()
    {
        $this->load->helper('date');
        $this->load->model('insertmodel','tblselect');
        $data = array(
            'pname'=>$this->input->post('page-name'),
            'purl'=>$this->input->post('page-url'),
            'pcon'=>$this->input->post('page-content'),
            'pub'=>date('Y-m-d H:i:s')
        );
        $this->tblselect->insertdata($data);
    }
    public function gpdatacon()
    {
        $this->load->model('insertmodel');
        $data['query'] = $this->insertmodel->getpagedata();
        $this->load->view('backend/pages/pages',$data);
    }
}

pages.php (which is under directory backend/pages)
<?php foreach($data as $row){?>

        <?= $row->pname; ?>
        <?= $row->purl; ?>
        <?= $row->pub; ?>

<?php } ?>

Here an error is occurred which says
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: pages/pages.php
Line Number: 73
Backtrace:
File: D:\Ampps\www\customcms\application\views\backend\pages\pages.php
Line: 73
Function: _error_handler
File: D:\Ampps\www\customcms\application\controllers\Backmanage.php
Line: 26
Function: view
File: D:\Ampps\www\customcms\index.php
Line: 316
Function: require_once

My database name is customcms, table name is page.
Made lots of searching on google already but not found so much. Besides, I found a question like this on stackoverflow but that was not so much helpful in my case. I am working for entire day on this problem but it is not getting resolved.
Comment: I also tried foreach($query as $row) instead of foreach($data as $row) in view but not working still.
Comment: Error is about `Backmanage.php` controller file. You didn't show that one nor show us URL that you are trying to access along with routes.php file code.
Comment: $route['default_controller'] = 'backmanage';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
Comment: I have also tried to pass simple values directly from the controller. I changed $data['query'] to $data = "hello" and tried to echo it on the view but it shows nothing. After tried echo var_dump($data); shown NULL. Its not sending data from controller to the view.
Comment: Show us `Backmanage.php` controller.
Answer: Change it:
$this->load->view('backend/pages/pages',$data);

to
$this->load->view('backend/pages/pages',array('data' => $data));

or change it:
<?php foreach($data as $row){?>

to
<?php foreach($query as $row){?>

Explanation: The second parameter of view() function is an array like
view('viewname', array('data' => $data))

and on view you can access it by using $data. If you pass $data then you have to use by its index i.e. $query
Answer: change $data to $query cause you store all data in $data['query'] so you get all data in $qyery variable
<?php foreach($data as $row){?>
.............
<?php } ?>

to
<?php foreach($query as $row){?>
............
<?php } ?>

if not work then print_r use and check that value exit
 public function gpdatacon()
    {
        $this->load->model('insertmodel');
        $data['query'] = $this->insertmodel->getpagedata();
        print_r( $data['query']);
        die()
        $this->load->view('backend/pages/pages',$data);
    }

for more information
https://www.codeigniter.com/user_guide/general/views.html
Comment: thanks for the answer but I already tried putting $query in foreach as per my earlier comment above
Answer: I tried it myself that was the issue with the URL I was calling. I made two pages similar in looks. and accidentally calling the wrong URL that was obvious not working.


Permutações de um número inteiro desconsiderando os zeros à esquerda

Question: Tenho o seguinte problema:
Dada uma entrada n tenho que calcular o número de permutações possíveis com os dígitos que o compõem. Por exemplo, se n = 123 tenho 6 números que podem ser formados: 123, 132, 231, 213, 312, 321. Porém se a entrada for 100 a resposta seria 1, já que as permutações possíveis são: 001, 010 e 001 mas 001, 010 não são representações válidas para o problema.
Aplicando a fórmula matemática para permutação com repetição, cheguei no seguinte código:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Similaridade {

  public int solucao(int n) {
    List<Integer> digitos = separarDigitos(n);
    Map<Integer, Integer> ocorrencias;
    Integer resultado;
    Integer[] valores;

    ocorrencias = this.contarOcorrencias(digitos);
    valores = ocorrencias.values().toArray(new Integer[ocorrencias.size()]);
    resultado = this.calcularPermutacao(digitos.size(), valores);

    return resultado;
  }

  public Integer calcularPermutacao(Integer total, Integer... repeticoes) {
    Long denominador = 1L;
    Long numerador;
    Long resultado;

    for (Integer repeticao : repeticoes) {
      if (repeticao > 1) {
        denominador = denominador * this.fatorial(repeticao);
      }
    }

    numerador = this.fatorial(total);
    resultado = numerador / denominador;

    return resultado.intValue();
  }

  private List<Integer> separarDigitos(int numero) {
    List<Integer> resultado = new ArrayList<>();

    while (numero != 0) {
      int digito = numero % 10;
      numero = numero / 10;
      resultado.add(digito);
    }

    return resultado;
  }

  private Map<Integer, Integer> contarOcorrencias(List<Integer> numeros) {
    Map<Integer, Integer> ocorrencias = new HashMap<>();

    numeros.forEach((numero) -> {
      if (ocorrencias.containsKey(numero)) {
        ocorrencias.put(numero, ocorrencias.get(numero) + 1);
      } else {
        ocorrencias.put(numero, 1);
      }
    });

    return ocorrencias;
  }

  private Long fatorial(Integer numero) {
    Long resultado = 1L;

    for (int fator = 2; fator <= numero; fator++) {
      resultado = resultado * fator;
    }

    return resultado;
  }
}

Porém agora preciso calcular e aplicar os resultados com zeros.
Como posso fazer isso? Lembrando que a performance é importante e que, sendo assim, apenas realizar as trocas para ter todas as possibilidades não é interessante. A resolução fica mais completa aplicando o desconto na fórmula ou após o cálculo da mesma.

Exemplos:

Entrada: 1213. Saída: 12.
Entrada: 123. Saída: 6.
Entrada: 100. Saída: 1.
Entrada: 120. Saída: 4.
Entrada: 1200. Saída: 6.
Entrada: 0. Saída: 1.
Comment: Existe tempo limite para execução do programa ? Se sim quanto ? Existem restrições para o `n` ? Se sim quais?
Comment: @Isac limite não existe, mas fazendo uma a uma cada possibilidade eu já tenho pronto. O interessante seria resolver descobrindo apenas as combinações iniciando com `0` matematicamente para descontar do resultado do código atual.
Comment: Ou seja a sua ideia é por meio de alguma dedução matemática conseguir chegar à quantidade de números únicos descontabilizando números com zeros à esquerda, sem ter que iterar sobre cada um ?
Comment: @Isac sim, exatamente
Answer:
As fórmulas abaixo foram retiradas daqui.

Dado um número qualquer, e considerando:

ai é a quantidade de vezes que o dígito i ocorre neste número (portanto, 0 <= i <= 9)

Ex: no número 644, o valor de a4 é igual a 2 (existem 2 dígitos 4 no número) e a6 é igual a 1 (todos os outros ai - para i diferente de 4 e 6 - são iguais a zero)

n é a quantidade de dígitos do número, ou seja, é a soma de todos os ai:
a0 + a1 + ... + a9 = n

O total de permutações possíveis (incluindo as que tem zeros no início) é:
n! / (a₀! * a₁! * a₂! * ... * a₉!)

Se o número não tem nenhum zero (ou seja, a0 é igual a zero), então o valor acima já é a resposta.
Mas se há algum zero no número, então podemos colocar um deles no início, restando a0 - 1 zeros no restante do número (ou seja, basta rearranjar os dígitos restantes para saber a quantidade). Sendo assim, a quantidade de permutações que possuem um zero no início seria:
(n - 1)! / ((a₀ - 1)! * a₁! * a₂! * ... * a₉!)

Portanto, caso haja zeros, basta fazer a primeira fórmula acima menos a segunda, que teremos o resultado. Se não tiver nenhum zero, a primeira fórmula já é a resposta. Em Java ficaria assim:
public int solucao(int n) {
    int[] quantidades = new int[10];
    int nDigits = 0;
    while (n > 0) {
        nDigits++;
        quantidades[n % 10]++;
        n /= 10;
    }

    // multiplica os fatoriais de a1 até a9
    int d = 1;
    for (int i = 1; i < quantidades.length; i++) {
        d *= fatorial(quantidades[i]);
    }

    // total de permutações
    int totalPerms = fatorial(nDigits) / (d * fatorial(quantidades[0]));
    if (quantidades[0] == 0) { // não tem zeros
        return totalPerms;
    }
    // descontar as permutações que começam com zero
    return totalPerms - (fatorial(nDigits - 1) / (d * fatorial(quantidades[0] - 1)));
}

Como estou computando a quantidade dos dígitos de zero a 9, guardei esses valores em um array de int mesmo, com 10 posições (o elemento da posição zero é a quantidade de zeros, na posição 1 é a quantidade de 1, etc). Além de ficar mais simples, também evita o uso dos wrappers.
O método fatorial é o mesmo que você já tem (apesar de que seria possível melhorar isso com memoização, fica a sugestão). E também poderia mudar todos os int's para long's, caso vá trabalhar com números muito grandes, nos quais o fatorial estoura os limites de um int.

Outra alternativa é considerar, além das definições acima:

bn(n, k): fórmula do Binômio de Newton, ou seja, bn(n, k) é igual a n! / k! (n - k)! (sendo que n! é o fatorial de n)

Temos que o total de permutações possíveis, desconsiderando os zeros no início, é:
bn(n - 1, a₀) * bn(n - a₀, a₁) * bn(n - a₀ - a₁, a₂) * ... * bn(a₉, a₉)

A ideia é similar: se colocar um zero no início, todos os outros dígitos (independente de ser zero ou não) podem ser colocados depois. A fórmula acima faz este "desconto", e também pode ser generalizada para:
bn(n - 1, a₀) * ( (n - a₀)! / (a₁! * a₂! * ... * a₉!) )

Em Java ficaria:
public int solucao(int n) {
    int[] quantidades = new int[10];
    int nDigits = 0;
    while (n > 0) {
        nDigits++;
        quantidades[n % 10]++;
        n /= 10;
    }
    int d = 1;
    for (int i = 1; i < quantidades.length; i++) {
        d *= this.fatorial(quantidades[i]);
    }
    return bn(nDigits - 1, quantidades[0]) * (this.fatorial(nDigits - quantidades[0]) / d);
}

private int bn(int n, int k) {
    return this.fatorial(n) / (this.fatorial(k) * this.fatorial(n - k));
}

Answer: Consegui chegar a um resultado calculado a proporção em que o número zero aparece e descontando do cálculo de permutações. O resultado final foi o seguinte:
import java.util.HashMap;
import java.util.Map;

public class Similaridade {

  public int solucao(int n) {
    Map<Integer, Integer> ocorrencias = new HashMap<>();
    Integer total = this.separarDigitos(n, ocorrencias);
    Integer resultado;
    Integer[] valores;

    valores = ocorrencias.values().toArray(new Integer[ocorrencias.size()]);
    resultado = this.calcularPermutacao(total, valores);

    // Desconsidera os zeros no início
    if (ocorrencias.containsKey(0)) {
      Double quantidadeDeZeros = Double.valueOf(ocorrencias.get(0));
      Double quantidadeDeDigitos = Double.valueOf(total);
      Double provisorio = Double.valueOf(resultado);

      provisorio = provisorio - (provisorio / (quantidadeDeDigitos / quantidadeDeZeros));
      resultado = provisorio.intValue();
    }

    return resultado;
  }

  public Integer calcularPermutacao(Integer total, Integer... combinacoes) {
    Long denominador = 1L;
    Long numerador;
    Long resultado;

    for (Integer combinacao : combinacoes) {
      if (combinacao > 1) {
        denominador = denominador * this.fatorial(combinacao);
      }
    }

    numerador = this.fatorial(total);
    resultado = numerador / denominador;

    return resultado.intValue();
  }

  private Integer separarDigitos(int numero, Map<Integer, Integer> ocorrencias) {
    Integer total = 0;

    while (numero != 0) {
      int digito = numero % 10;

      numero = numero / 10;

      if (ocorrencias.containsKey(digito)) {
        ocorrencias.put(digito, ocorrencias.get(digito) + 1);
      } else {
        ocorrencias.put(digito, 1);
      }

      total++;
    }

    return total;
  }

  private Long fatorial(Integer numero) {
    Long resultado = 1L;

    for (int fator = 2; fator <= numero; fator++) {
      resultado = resultado * fator;
    }

    return resultado;
  }
}


Problema ao tratar foreach em um array com PHP

Question: Estou tentando percorrer as transaction da seguinte array mas sem sucesso:
Array
(
    [date] => 2021-08-07T20:48:14.000-03:00
    [transactions] => Array
        (
            [transaction] => Array
                (
                    [date] => 2021-08-07T19:14:44.000-03:00
                    [reference] => TPW-253961
                    [code] => 3ECE880C-AEFF-4A3E-44E5
                    [type] => 1
                    [status] => 4
                    [paymentMethod] => Array
                        (
                            [type] => 11
                        )

                    [grossAmount] => 3.00
                    [discountAmount] => 0.00
                    [feeAmount] => 0.06
                    [netAmount] => 2.94
                    [extraAmount] => 0.00
                    [lastEventDate] => 2021-08-07T19:15:59.000-03:00
                )
            [transaction] => Array
                (
                    [date] => 2021-08-07T19:15:44.000-03:00
                    [reference] => TPW-253961
                    [code] => 3ECE880C-AEFF-4A3E-99EA
                    [type] => 1
                    [status] => 4
                    [paymentMethod] => Array
                        (
                            [type] => 11
                        )

                    [grossAmount] => 3.00
                    [discountAmount] => 0.00
                    [feeAmount] => 0.06
                    [netAmount] => 2.94
                    [extraAmount] => 0.00
                    [lastEventDate] => 2021-08-07T19:15:59.000-03:00
                )

        )

    [resultsInThisPage] => 1
    [currentPage] => 1
    [totalPages] => 1
)

A array é recebida originalmente de um XML, por isso estou convertendo da seguinte maneira para o PHP:
$xml = simplexml_load_string($response, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,true);

E com o seguinte foreach estou tentando exibir os status e code de cada transaction:
foreach ($array["transactions"]["transaction"] as $resultado){
    echo $resultado["status"].' - '.$resultado["code"].'
';
}

O resultado do echo é algo completamente diferente do esperado, além de que não estar retornando o status e code de cada transaction, há 12 linhas de resultado (uma para cada item na array transaction:
Answer: Consegui resolver alterando o parâmetro false para true na conversão da array.
$array = json_decode($json,true);

Em vez de usar foreach, passei a utilizar o for da seguinte maneira:
for ($i = 0; $i < $array["resultsInThisPage"] OR $array["resultsInThisPage"] == 0 AND $i == 0; $i++){
    if ($array["resultsInThisPage"] < 2){
        $status = $array["transactions"]["transaction"]["status"];
        $code = $array["transactions"]["transaction"]["code"];
    } else {
        $status = $array["transactions"]["transaction"][$i]["status"];
        $code = $array["transactions"]["transaction"][$i]["code"];
    }
    echo $status.' - '.$code.'
';
}

Desta forma consegui obter os valores de $status e $code na array.