Can't set httpBody on WKWebView POST request in iOS11.3

Question: following code
var webView: WKWebView!

override func loadView() {
    super.loadView()
    self.webView = WKWebView(frame: .zero)
    view = webView
}

override func viewDidLoad() {
    super.viewDidLoad()

    var request = URLRequest(url: URL(string: "https://hosts")!)
    request.httpMethod = "POST"
    let bodyData = "data1=postData"
    request.httpBody = bodyData.data(using: .utf8)!

    self.webView.load(request)
}

I was able to get the POST parameter on Web site loaded on iOS 11.2,
but could not get it on iOS 11.3
Why did not get it on iOS 11.3? Was the specification changed?
I want anyone to tell me the workaround. Please give me the answer.
Answer: WKWebView doesn't automatically set the Content-Type header to application/x-www-form-urlencoded for POST requests the way UIWebView does.
var webView: WKWebView!

override func loadView() {
    super.loadView()
    self.webView = WKWebView(frame: .zero)
    view = webView
}

override func viewDidLoad() {
    super.viewDidLoad()

    var request = URLRequest(url: URL(string: "https://hosts")!)
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let bodyData = "data1=postData"
    request.httpBody = bodyData.data(using: .utf8)!

    self.webView.load(request)
}

Answer: Haven't encountered this error on 11+, but had it surfaced on 10.3.3, was OK on 12+ though.
I've reverted to performing requests with bodies, manually using shared session, than inserting loaded data into WKWebView.
var firstRequest: URLRequest = URLRequest(url: requestUrl)
firstRequest.httpMethod = "POST"
firstRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
firstRequest.httpBody = "data1=\(requestData1)".data(using: .utf8)

URLSession.shared.dataTask(with: firstRequest) { [weak self] (data, response, error) in
    // check error, response and data to show useful error message
    if let data = data {
        self?.webView.load(body, mimeType: "text/html", characterEncodingName: "UTF-8", baseURL: baseUrl)
    }
}.resume()

Answer: If you switch to WKWebView you can use the following approach.  Basically you need to make use of WKURLSchemeHandler protocol:
1. Setup webview
let config = WKWebViewConfiguration()
config.setURLSchemeHandler(self, forURLScheme: "my-custom-scheme")
let wkWebView = WKWebView(frame: .zero, configuration: config)

2. Implement WKURLSchemeHandler protocol
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
  if let url = urlSchemeTask.request.url, url.scheme == "my-custom-scheme" {
    self.handleTermURLCallback(urlSchemeTask.request)
  }
}

By using this you'll find that your request httpBody in the callback is not null and you can continue the same way you used to with UIWebView.
It took a lot of effort to find this but it is working for us and we didn't need to change very much.  Hope it helps you guys.


Can an async function return undefined instead of a Promise

Question: I am working on an app using nodejs. I am making multiple HTTP requests with an async function and axios library. However I do not always want to return the fetched data from my http request, only if a certain condition is met.
Like so.
const getFooHTTP = async (id) => {
let response = await axios.get(url);

if (condition){
//I only want to return the response here
return response;
}

//Here i do not want to return the response
}

Then I am getting all the promises returned in an array with Promise.all()
const getAllData = async() => {
let dataArray = [];
for (let i = 0; i < n; i++){
const data = getFooHTTP(i);
dataArray.push(data)
}
const someData = await Promise.all(dataArray);
return someData ;
}

Then I get all the data
getAllData().then(data => {
//Here is the problem, here I get a bunch of undefined in my data array
console.log(data);
})

Here is my problem, when I get the returned data from getAllData, there is some undefined element because at the first function in the beginning (getFooHTTP) was returning nothing. My question is how can I return promises conditionally, so I don't get undefined promises returned even If the async function have no return statement.
Thank you
Comment: Possible duplicate of [Removing undefined values from Array](https://stackoverflow.com/questions/28607451/removing-undefined-values-from-array) and [Promise.all() - How to resolve() without returning undefined or value](https://stackoverflow.com/questions/35413572/promise-all-how-to-resolve-without-returning-undefined-or-value)
Answer: An async function will always return a Promise, no matter what. If you explicitly return a non-Promise even if there are no awaits before it, it will be automatically wrapped in a Promise before returning (eg return undefined will turn into something like return Promise.resolve(undefined)).

const prom = (async () => {
  return undefined;
})();

// Even though it returned undefined, it's still a Promise:
console.log(typeof prom.then);

If you don't want to return values that don't fulfill condition, filter the Promise.all before returning it:
const getFooHTTP = async (id) => {
  let response = await axios.get(url);
  if (condition){
    //I only want to return the response here
    return response;
  }
  //Here i do not want to return the response
  return undefined;
  // or, have no return statement at all
};

and
const getAllData = async() => {
  let dataArray = [];
  for (let i = 0; i < n; i++){
    const data = getFooHTTP(i);
    dataArray.push(data)
  }
  const someData = (await Promise.all(dataArray))
      .filter(val => val !== undefined);
  return someData ;
};

Though, this relies on all of the Promises that getFooHTTP resolves to returning non-undefined values.


Custom chart between pie and heat map

Question: We need to create a "heap map" using EChats in the form of a clock, where for each hour we have a certain number of occurrences (that would be the value) and the color of each block on the pie goes from white to black depending on the relative weightof the value.
Would be something like this:

Any suggestions or samples around?
Answer: This should not be that hard using the color attribute in the chart options.
Take for example the data from this example from the documentation.
We can assign colors to the chart sections using the following code:
const data = [
    {value: 335, name: '直接访问'},
    {value: 310, name: '邮件营销'},
    {value: 234, name: '联盟广告'},
    {value: 135, name: '视频广告'},
    {value: 1548, name: '搜索引擎'}
];

const max = data.reduce((acc, d) => acc < d.value ? d.value : acc, 0);
const colors = data.map(d => {
    const shade = 255 - Math.round(255 / (max / d.value));
    const hex = shade.toString(16)
    return '#' + hex + hex + hex
})

console.log(colors) // ["#c8c8c8", "#cccccc", "#d8d8d8", "#e9e9e9", "#000"]

// then you just assign the colors to the chart config
options.color = colors

Custom chart between pie and heat map


What identity does IIS use to instanciate COM objects from ASP pages?

Question: I was tasked to port and move an old ASP application from a Windows 2003 server (x86) to a Windows 2008R2 server running IIS 7.5
A number of things needed to be changed (mostly related to registry access) but I stumbled across one problem that I couldn't solve in a satisfying way.
The application makes use of an external COM object (in-process dll). It will create an instance of that object during the login phase and store it as a session variable.
This used to work quite nice and worked well in my test but when I deployed it on the first production server, I started to have random "500" errors when users tried to log in. The error was really not consistent so I used procmon to trace the source of the problem and got this: when a user tries to access the web site, the IIS worker process tries to open the Dll that hosts the COM object but fails with an access denied error.
Now, I don't understand this: the web application uses a service account for accessing the local resources. That service account has explicit rights on the directory where that COM library is located. Yet, the access to that file is still denied.
I "fixed" the issue by giving "everyone" explicit read and execute access on the dll and it (seems to) have solved the problem.
But I don't know why.
The strangest thing is that is I use a local administrator account to connect to the web page once (and just once), then the issue was fixed for as long as the application wasn't recycled.
I would appreciate if anyone could shed some light on that issue. I can live with the fix, but I really would like to understand.
Edit To clarify: the web site is NOT set to impersonate the connecting user. In fact, the only authentication scheme enabled is "Anonymous Authentication". The basic settings, however, are set to use the service account.
Edit The identity reported by procmon during the access denied is "IIS APPPOOL\(application name)"
Comment: The most relevant detail - still omitted - is the identity of the W3WP thread trying to access the DLL the first time. That's the identity that needs Read permission, regardless of everything else.
Comment: You are correct. I remember checking that and not being able to make sense of the result. I will check again and update the question. Thanks
Answer: I think you've answered your own question.
Your web app is configured to impersonate an authenticated user.
When a request is accepted, the thread handling the request is given the token of the user that authenticated, and then that identity is used for all operations by that thread until the request terminates.
The COM object only needs to be loaded once, and Admins can read basically any file, so the first  request as an Admin is able to a) read the file and b) load it into the process address space. This usually doesn't need to happen repeatedly: once the DLL is in memory, it's there.
If a regular user (or anonymous user) authenticates and is impersonated, they didn't have permission to open the file in the first place, and ProcMon should show you that, along with the identity which was being used. (By default: IUSR for anonymous requests).
The "service account" bit you've described sounds like a worker process identity. They're only used to start the app pool, read the configuration, and then for sitting around doing things that aren't directly related to a request*.
* unless you're using the App Pool account as the anonymous user account, and unless the thread impersonating the user isn't able to get off-box (i.e. needs to delegate), in which case the App Pool account will be used.


Fetch value from DB using Macros

Question: I need to do the below update through macros in MYSQL,
If tbname = "PARTY" Then
Dim ssql As String
ssql = SELECT MAX(PARTY_ID) FROM PARTY
DB.Execute ssql, 64
End If

I need to use above output i.e., Max(party_id) to update the party table.
That is,
UPDATE PARTY PARTY_ID = (output of SELECT MAX(PARTY_ID) FROM PARTY)
WHERE PARTY_ID='DUMMY'

Kindly advise how can we implement this using resultset concept
Answer: I also need answer for this..
Need to know how we can use result set concept to update a table based on the value of other ta

Fetch value from DB using Macros


GhostScript - get ink_cov from top 5pt?

Question: I'm trying to get the ink coverage from the top 5pt from an PDF.
Most of the times, this command will give me equal result across many different PDFs:
gs -o - -sDEVICE=ink_cov -dFirstPage=2 -dLastPage=2 -dAutoRotatePages=/None -g36340x5 "12345.pdf" | grep CMYK

That gives me a result like 0.02477.
But sometimes, I get completely different results, like 0.57318
I can admit that I'm not entirely sure that -g36340x5 means top 5pt. Is it maybe the bottom 5pt?
If I run the following command, I would think that the crop.pdf would show me what I want the ink coverage for, but it just shows me blank pdf.
gs -o crop.pdf -sDEVICE=pdfwrite -dFirstPage=2 -dLastPage=2 -dAutoRotatePages=/None -g36340x5 -f 12345.pdf

But if I run this command, the crop.pdf shows me the part I would like to get ink coverage for:
gs -o crop.pdf -sDEVICE=pdfwrite -dFirstPage=2 -dLastPage=2 -dAutoRotatePages=/None -g36340x6120 -c "[/CropBox [0 607 3634 612] /PAGES pdfmark" -f 12345.pdf

But even with that, when trying go execute this command with ink_cov-device, I get very different results on similar pdf's:
gs -o - -sDEVICE=ink_cov -dFirstPage=2 -dLastPage=2 -dAutoRotatePages=/None -g36340x6120 -c "[/CropBox [0 607 3634 612] /PAGES pdfmark" -f 12345.pdf

All my pdf's are upside-down.
What am I doing wrong?
Best Regards
Niclas
Answer: -g sets the media size in pixels, it makes no attempt to relocate the content on the media. Since PostScript co-ordinates have 0.0 at bottom left, you are only looking at the bottom 5 pixels of the output.
Your third example uses pdfwrite to create a PDF file where the cropbox covers the area you are interested in. However, by default Ghostscript uses the MediaBox when rendering. If you want to use the CropBox then you need to add -dUseCropBox to your command line.  If you don't do that (as your last command does not) then it will still be checking the same content as the original PDF.
You either need to set a media size which matches the are you are interested in, and translate the page origin (which will be hard to do, as it will mean altering the PDF interpreter, how are you at programming in PostScript ?) or you need to create a new PDF with the CropBox, as you have done above, then process that PDF file with the inkcov device, but add -dUseCropBox (and discard the now redundant -g)
You'd probably find it easier to see what's going on if you render to screen instead of using inkcov, then you can change parameters and see what effect they have. Once you are convinced you are working with the area you want, then you can switch ot the inkcov device.

GhostScript - get ink_cov from top 5pt?


Docker Desktop kubernetes cluster reports Authentication required when pulling images

Question: Deploying a manifest in Docker Desktop (v4.21.1) Kubernetes cluster.
The image used in manifest looks like below,
my-local.artifactory.com/docker-images/my-app:v1.0.0

The secret with docker config is created and referred within the manifest in  imagePullSecrets. The imagePullPolicy is set to Always.
Error message
Failed to pull image "my-local.artifactory.com/docker-images/my-app:v1.0.0": rpc error: code = Unknown desc = Error response from daemon: Head "https://my-local.artifactory.com/v2/docker-images/my-app/manifests/v1.0.0": unknown: Authentication is required

The deployment failed since not able to pull image and indicates Authentication required. Odd thing is that the kubelet docker-desktop used the URL that looks like - https://my-local.artifactory.com/v2/myapp/manifests/v1.0.0
But not sure how this URL is constructed.

Question:
How Docker desktop kubelet know to create this url https://my-local.artifactory.com/v2/myapp/manifests/v1.0.0? Not sure how v2 is added to the URL.

When hit the URL directly in browser, do get below message.
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}

Comment: v2 the the api version. If has nothing to do with your image/tag
Comment: which Kubernetes you are using? is it on prem or cloud?YOu installed JFrog Artifactory with helm?
Comment: Can you do a `docker login my-local.artifactory.com` with the username/password used in the secret? How did you create your secret?
Comment: was using local Kubernetes V1.27.2, configured to WSL2
Comment: The issue was in the Yaml manfiest code which I used to deploy. The deployment is done using Operator and in Custom resource manifest the`imagePullSecrets` configuration was placed under incorrect property. Totally a manifest related issue.
Answer: The URL is specified by the Docker Registry HTTP API V2.
The image name my-local.artifactory.com/docker-images/my-app:v1.0.0 breaks down into three parts: the registry name my-local-artifactory.com, the image name docker-images/my-app, and the tag v1.0.0.  To pull the image, the kubelet (or anything else) first needs to fetch a piece called the image manifest, and that manifest has a list of the individual layers that need to be downloaded.
The registry API specifies the manifest URL as
GET /v2/<name>/manifests/<reference>

where GET is an HTTP verb, <name> is the image name, and <reference> is either the tag or a digest hash.  This matches the URL in the error message.
Answer: As Chris mentioned, v2 in the URL represents  the api version.
From your description we know that you are using an artifact registry for storing your images.
The  error  describes that it requires authentication to access this image/artifact
As per this article in County:

Authenticating and Pulling Images from Artifact Registry
Kubernetes uses Secrets to authenticate or store the credentials to
access a Docker registry for images.
Follow below steps  to create a Kubernetes Secret.
1.To fetch service account email from service account key:
cat serviceaccount.json | grep client_email  # Value used in docker-email key

2.Create a Kubernetes Secret:
kubectl create secret docker-registry artifact-registry \
--docker-server=https://us-docker.pkg.dev \
--docker-email=<service account email address> \
--docker-username=_json_key \
--docker-password="$(cat serviceaccount.json)"

3.Verify the creation of Kubernetes Secret:
kubectl get secrets | grep artifact-registry

Once you  have obtained the Service Account key, then you  can
authenticate to Artifact Registry using the command below:
cat serviceaccount.json | docker login -u _json_key --password-stdin https://us-docker.pkg.dev

Comment: This is correct, the `imagePullSecrets` of Docker configure was placed incorrectly in the Custom Resource manifest that I deployed. With `helm template` the yaml file generated clearly indicated it.


Model specification

Question: Actually I want to see the impact of Investors sentiment on Aggregate stock market return, so my major concern is to identify the impact of investors sentiment.
But besides investors sentiment I want to include 5 more Independent variable which might have impact also stock market return.
Its a single STOCK MARKET analysis (USA), here N=1
So can anybody suggests me what model I can use to test it other than Multiple Regression Analysis?
Comment: Hi, James, and welcome to Cross Validated! Is there a particularly reason you don't want to use regression? It's a fairly large family containing some very powerful tools....
Answer: Since you don't have so many variables, you can try brute force search to select the best variables that influence your outcome most. Refer this post for more details.

Model specification


Transform variables so residuals become normally distributed

Question: I'm doing a project which involves multiple regression, and I'm aware (as far as I understand) that the residuals should be normally distributed with a constant variance. From my study, the residuals look as follows

However, the second plot (the QQ-plot) indicates that the residuals are not normally distributed. I've tried to transform some of my continuous explanatory variables and also tried to fit variables with a spline function, both attempts without any success. I've read these posts which concern the subject
Post1, Post2, Post3, Post4, Post5 and finally, a post where the author seem to have the same problem as myself; Post6.
From these posts, I've reached these conclusions:

Rarely is it the case that you see a QQ plot that lines up along a straight line. Even if you have tried all kinds of transformations/fittings, a QQ-plot that doesn't fit with a straight line is not a substantial issue in practical terms. Thus, I should not be fixated on fixing the residuals.
There are other methods, such as Box-Tidwell, which can help me. But using this method can often result in models which are hard to interpret.

Question By looking at my plots above, do you see any obvious transformation that can be used? Or is there any other way to make sure that the residuals fulfill the assumption of normally distributed residuals? Or should I just leave it and try to explain why the residuals aren't normal?
Comment: If there is any, what's the distribution you assumed when running regression? Poisson/Gamma/Tweedie?  From the residual plots, the residual range for fitted value 190 above are narrower, this may be an indicator of too higher order of distribution power under a GLM model structure.
Comment: One of my friends agree with you, that I should use GLM and see if the residuals perhaps are Gamma-distributed (or any other distribution that are scewed). I will try to use this method and see what happens. Thank you!
Comment: Use of R here seems incidental. There is no good reason to make R the first word in the title.
Comment: Lack of symmetry here implies that you might be better off working on a different scale. Although this thread may be dead (OP asked just this one question and hasn't visited the site since January), I would want to know much more about the response or outcome variable and whether it is bounded, in practice if not in principle.  Also, all "multiple regression" implies is two or more predictors; without more of a story there, it's hard to advise.
Answer: My advice would be to stop trying to force the data to fit your model and choose a model that fits your data.
For example: Quantile regression or various robust regression methods could be used.
Answer: Although I am not 100%, what I would do in this scenario is split up the variables you included in your multiple regression, then graph a scatter plot of them individually. This will help you see what kind of data you are dealing with without the other variables clouding up your analysis. Determine if only one variable, or all of them need to be transformed, transform them individually, then regress the new variables on each other.
Comment: Thanks for the answer!
I did, one of the variables was fitted with a polynomial of second degree and the other with a log. Though, the result was the same. I will try to use GLM and also approach the datamaterial in another way to see if I get a better result.


Adding iptables route on openvpn connect

Question: I have my openvpn server up and running and I push certain routes to my clients via the ccd directive, I would like to know how I can update the iptables based on the ccd files when the client connects.
So lets say my ccd for client1 is :
ifconfig-push 10.8.0.45 255.255.255.0
push 'route 10.10.0.45'

and I want to add this to the iptables.
iptables -A FORWARD -s 10.8.0.45 -d 10.10.0.45 -j ACCEPT

and then
iptables -A FORWARD -s 10.8.0.0/24 -d 10.10.0.0/16 -j DROP

If someone can point me in the right direction would be much appreciated, im fairly newb with bash scripts
Answer: You can hook into an OpenVPN configuration many scripts, which receive many parameters from the server as environment variables: cf. Reference Manual.
You are mostly interested in the up, down scripts to insert the DROP rule at server startup and shutdown and the client-connect and client-disconnect script for per client rules. You need to modify your server config to contain:
# Allow user scripts
script-security 2
# up/down script
up /etc/openvpn/updown.sh
down /etc/openvpn/updown.sh
# Client connect/disconnect
client-connect /etc/openvpn/client.sh
client-disconnect /etc/openvpn/client.sh

Your /etc/openvpn/updown.sh script will create a OPENVPN and link it from the FORWARD chain:

#!/bin/bash
IPT=/usr/sbin/iptables
# 'script_type' contains the type of the script
if [ "$script_type" = "up" ]; then
  $IPT -N OPENVPN
  $IPT -A FORWARD -j OPENVPN
  $IPT -A OPENVPN -s 10.8.0.0/24 -d 10.10.0.0/16 -j DROP
else
  $IPT -F OPENVPN
  $IPT -D FORWARD -j OPENVPN
  $IPT -X OPENVPN
fi

You client script /etc/openvpn/client.sh will be more complicated: while the public and private IP addresses of the remote client are contained in the ifconfig_remote and ifconfig_pool_remote_ip, you will need to parse the ccd file to find out which routes did you send to the client:

#!/bin/bash
IPT=/usr/sbin/iptables
# We need to split the line into words as bash would, by
# interpreting the double quotes, hence the 'eval'.
function parse_ccd_line() {
  eval "local line=($1)"
  # If the first word is 'push' return the second one.
  if [ "${line[0]}" = "push" ]; then
    echo "${line[1]}"
  fi
}

# Your ccd_dir so we don't need to parse the OpenVPN
# server config file too.
ccd_dir=/etc/openvpn/ccd

if [ -f "$ccd_dir/$common_name" ]; then
  # We read the "$ccd_dir/$common_name" file line by line:
  while read line; do
    # We split the argument of every 'push' directive into 'cmd' and 'arg1'
    # If you need more arguments, the array 'push_opt' contains them.
    push_opt=($(parse_ccd_line "$line"))
    cmd=${push_opt[0]}
    arg1=${push_opt[1]}
    # We use just the 'route' commands
    if [ "$cmd" = "route" ]; then
      if [ "$script_type" = "client-connect" ]; then
        $IPT -I OPENVPN -s "$ifconfig_pool_remote_ip" -d "$arg1" -j ACCEPT
      else
        $IPT -D OPENVPN -s "$ifconfig_pool_remote_ip" -d "$arg1" -j ACCEPT
      fi
    fi
  done < "$ccd_dir/$common_name"
fi


generating a vector given other vectors in modulo 11

Question: how to show that vector $X4=\begin{bmatrix}0 \\ 2 \\ 1 \\ 1\end{bmatrix}$ can be generated with
$X1=\begin{bmatrix}9 & 1 & 0 & 0\end{bmatrix}$
$X2=\begin{bmatrix}8 & 0 & 1 & 0\end{bmatrix}$
$X3=\begin{bmatrix}7 & 0 & 0 & 1\end{bmatrix}$
in mod 11?
Answer: $X4=\begin{bmatrix}0 \\ 2 \\ 1 \\ 1\end{bmatrix}=2\begin{bmatrix}9 \\ 1 \\ 0 \\ 0\end{bmatrix}+1\begin{bmatrix}8 \\ 0 \\ 1 \\ 0\end{bmatrix}+1\begin{bmatrix}7 \\ 0 \\ 0 \\ 1\end{bmatrix}$ $(\text{mod }11)$


Hide iOS Keyboard Predictive Text Bar - UITextView / UITextField

Question: Seems that setting
autocorrectionType = UITextAutocorrectionTypeNo;
for a UITextView or UITextField no longer sufficient to hide the iOS keyboard's predictive bar.
Has Apple decided that this can only be hidden by the user in keyboard settings? Or this there still some way to do this programmatically? We need to do this for our app that includes spelling exercises.
Answer: This removes the predictive text bar for me:
@IBOutlet var tf: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    tf.autocorrectionType = .no
    tf.spellCheckingType = .no
}

Comment: So you need to subclass to achieve this?
Comment: no just create outlet off UITextField
Comment: @Peter - no, no need to subclass. That code is just an example of setting both properties to `.no` via code. If you've added your text field in Storyboard and want to do it there, set both **Correction** and **Spell Checking** to `No` in the Attributes Inspector pane.
Comment: Forgot to also set spellCheckingType = UITextSpellCheckingTypeNo. Working now. Thanks.


Linear regression with ARIMA errors and seasonal dummy covariates: how does differencing works?

Question: To model my daily time-series data, I want to use linear regression with ARIMA errors. I also want to introduce several seasonal dummy covariates (day of the week, month of the year). I read in Hyndman & Athanasopoulos (2018) the following

The auto.arima function will also handle regression terms via the xreg argument. The user must specify the predictor variables to include, but auto.arima will select the best ARIMA model for the errors. If differencing is required, then all variables are differenced during the estimation process, although the final model will be expressed in terms of the original variables.

I know the auto.arima function handles this automatically. But if variables are defined as dummy (zero-one), then how does the differencing happen?
Comment: Why should zeroes and ones cause any trouble when differencing? There is no problem in taking $d_t-d_{t-1}$ for a dummy variable, just like we would do it for some other time series, $x_t-x_{t-1}$.
Comment: I realized my comment is essentially an answer, even if a short one, so I am going to post it as such.
Comment: I thought so too, but a reviewer stated it should not be that simple. So I wanted to check with someone else. Thank you!
Answer: Why should zeroes and ones cause any trouble when differencing? There is no problem in taking $d_t−d_{t−1}$ for a dummy variable, just like we would do it for some other time series, $x_t−x_{t−1}$.


Twitter: "This page contains too many server redirects" error

Question: I'm trying to share some data using twitter in android app, so what ever the basic information like redirecting url, application given in the "Twitter app registration page", everything works fine but after giving the username and password in the LOGIN PAGE of twitter it doesn't redirects to the next page, instead getting "this page contains too many server redirects" error message.
My redirect url looks like this "https://www.example.com/".
Any suggestions?
public class constants {
public static final String CONSUMER_KEY = "key";
public static final String CONSUMER_SECRET= "secret";

public static final String REQUEST_URL = "http://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";

public static final String OAUTH_CALLBACK_URL = "x-latify-oauth-twitter";
private static final String CALLBACK_SCHEME = null;
public static final Object OAUTH_CALLBACK_SCHEME = CALLBACK_SCHEME + "://callback";

}
MainActivity
import java.util.Date;

import oauth.signpost.OAuth;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
 import android.os.Bundle;
import android.os.Handler;
 import android.preference.PreferenceManager;
   import android.provider.SyncStateContract.Constants;
 import android.app.Activity;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.util.Log;
 import android.view.Menu;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;
  import android.widget.Toast;

  public class MainActivity extends Activity {

private SharedPreferences prefs;
  private final Handler mTwitterHandler = new Handler();
  private TextView loginStatus;

    final Runnable mUpdateTwitterNotification = new Runnable() {
     public void run() {
        Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
      }
  };

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.prefs = PreferenceManager.getDefaultSharedPreferences(this);

    loginStatus = (TextView)findViewById(R.id.ls);
    Button tweet = (Button) findViewById(R.id.tweet);
    Button clearCredentials = (Button) findViewById(R.id.cc);

      tweet.setOnClickListener(new View.OnClickListener() {

     * to the twitter login page. Once the user authenticated, he'll authorize the     Android     application to send
    * tweets on the users behalf.
    */
        public void onClick(View v) {
         if (TwitterUtils.isAuthenticated(prefs)) {
         sendTweet();
         } else {
    Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
    i.putExtra("tweet_msg",getTweetMsg());
    startActivity(i);
         }
        }
    });

    clearCredentials.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
         clearCredentials();
         updateLoginStatus();
        }
    });
   }

  @Override
  protected void onResume() {
 super.onResume();
 updateLoginStatus();
  }

 public void updateLoginStatus() {
  loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
  }

 private String getTweetMsg() {
 return "Tweeting from Android App at " + new Date().toLocaleString();
  }

 public void sendTweet() {
 Thread t = new Thread() {
  public void run() {

  try {
  TwitterUtils.sendTweet(prefs,getTweetMsg());
  mTwitterHandler.post(mUpdateTwitterNotification);
  } catch (Exception ex) {
   ex.printStackTrace();
  }
  }

 };
 t.start();
 }

 private void clearCredentials() {
 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
 final Editor edit = prefs.edit();
 edit.remove(OAuth.OAUTH_TOKEN);
 edit.remove(OAuth.OAUTH_TOKEN_SECRET);
 edit.commit();
 }
 }

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
 import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
 import android.util.Log;

public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {

    final String TAG = getClass().getName();
    private Context context;
    private OAuthProvider provider;
    private OAuthConsumer consumer;

    /**
    *
    * We pass the OAuth consumer and provider.
    *
    * @param context
    * Required to be able to start the intent to launch the browser.
    * @param provider
    * The OAuthProvider object
    * @param consumer
    * The OAuthConsumer object
    */
    public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
    this.context = context;
    this.consumer = consumer;
    this.provider = provider;
    }

    /**
    *
    * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
    *
    */
    @Override
    protected Void doInBackground(Void... params) {

    try {
    Log.i(TAG, "Retrieving request token from Google servers");
    final String url = provider.retrieveRequestToken(consumer, constants.OAUTH_CALLBACK_URL);
    Log.i(TAG, "Popping a browser with the authorize URL : " + url);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
    context.startActivity(intent);
    } catch (Exception e) {
    Log.e(TAG, "Error during OAUth retrieve request token", e);
    }

    return null;
    }

    }

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;

 public class PrepareRequestTokenActivity extends Activity {
final String TAG = getClass().getName();

private OAuthConsumer consumer;
private OAuthProvider provider;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 try {
 this.consumer = new CommonsHttpOAuthConsumer(constants.CONSUMER_KEY,    constants.CONSUMER_SECRET);
 this.provider = new          CommonsHttpOAuthProvider(constants.REQUEST_URL,constants.ACCESS_URL,constants.AUTHORIZE_URL      );
 } catch (Exception e) {
 Log.e(TAG, "Error creating consumer / provider",e);
 }

    Log.i(TAG, "Starting task to retrieve request token.");
  new OAuthRequestTokenTask(this,consumer,provider).execute();
  }

  /**
  * Called when the OAuthRequestTokenTask finishes (user has authorized the request    token).
 * The callback URL will be intercepted here.
  */
 @Override
     public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
   final Uri uri = intent.getData();
    if (uri != null && uri.getScheme().equals(constants.OAUTH_CALLBACK_SCHEME)) {
   Log.i(TAG, "Callback received : " + uri);
    Log.i(TAG, "Retrieving Access Token");
    new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
     finish();
     }
      }

          public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {

       private Context  context;
      private OAuthProvider provider;
      private OAuthConsumer consumer;
       private SharedPreferences prefs;

     public RetrieveAccessTokenTask(Context context, OAuthConsumer                   consumer,OAuthProvider provider, SharedPreferences prefs) {
   this.context = context;
     this.consumer = consumer;
    this.provider = provider;
     this.prefs=prefs;
        }

      /**
       * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
     * for future API calls.
       */
      protected Void doInBackground(Uri...params) {
        final Uri uri = params[0];
      final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

             try {
       provider.retrieveAccessToken(consumer, oauth_verifier);

      final Editor edit = prefs.edit();
         edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
       edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
     edit.commit();

     String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
     String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

     consumer.setTokenWithSecret(token, secret);
     context.startActivity(new Intent(context,MainActivity.class));

  executeAfterAccessTokenRetrieval();

   Log.i(TAG, "OAuth - Access Token Retrieved");

    } catch (Exception e) {
    Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
     }

   return null;
      }

     private void executeAfterAccessTokenRetrieval() {
     String msg = getIntent().getExtras().getString("tweet_msg");
     try {
      TwitterUtils.sendTweet(prefs, msg);
        } catch (Exception e) {
     Log.e(TAG, "OAuth - Error sending to Twitter", e);
     }
     }
    }

twitterUtils.java
import oauth.signpost.OAuth;
import twitter4j.Twitter;
 import twitter4j.TwitterException;
 import twitter4j.TwitterFactory;
 import twitter4j.http.AccessToken;
 import android.content.SharedPreferences;
 import android.provider.SyncStateContract.Constants;

  public class TwitterUtils {
public static boolean isAuthenticated(SharedPreferences prefs) {

 String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
 String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

 AccessToken a = new AccessToken(token,secret);
 Twitter twitter = new TwitterFactory().getInstance();
 twitter.setOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
 twitter.setOAuthAccessToken(a);

 try {
 twitter.getAccountSettings();
 return true;
 } catch (TwitterException e) {
 return false;
 }
 }

 public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
 String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
 String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

 AccessToken a = new AccessToken(token,secret);
 Twitter twitter = new TwitterFactory().getInstance();
 twitter.setOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
  twitter.setOAuthAccessToken(a);
    twitter.updateStatus(msg);
 }
 }

Comment: Post some code so we can help you more.
Comment: added constants.java code@DipakKeshariya
Answer: Change Your Call Back URL and write below Call back URL instead of your URL.
public static final String CALLBACK_URL = "x-oauthflow-twitter://callback";

And see below link for more information.
Twitter Integration in Android
Comment: @DDA Try Above link example of Twitter Integration.
Comment: @DDA If you don't have any issue use above link code, it will definitely solve your problem.
Comment: yes i had downloaded n testing that, vry nice tutorial, l implement that in my project, if i get the output surely vl make ur answer correct:)@Dipak Keshariya
Comment: @DDA In above link code write your next activity code in onComplete() method of mTwitterLoginDialogListener and try.
Comment: i'm getting error in TwitterActivity.java of ur code, in this class private void postAsToast(FROM twitterPost, MESSAGE success)@Dipak Keshariya
Comment: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (new View.OnClickListener(){}, String, int)@Dipak Keshariya
Comment: Dipak everything went fine, but after giving username and password, m getting forceclose...@Dipak Keshariya
Comment: @DDA Post Error logcat in your question or post another question.
Comment: http://stackoverflow.com/questions/14378470/twitter-after-giving-username-and-password-the-app-gets-crash@Dipak Keshariya
Comment: @DDA Accept this answer and Are you using my whole code without changes?
Comment: i had posted the seperate question based on ur link, i followed ur link only,  l accept ur answer there, coz for many of the users it will be helpful...@Dipak Keshariya
Comment: this is the best tutorial for integrating twitter... pls find this friends, http://androidcodeexamples.blogspot.in/2011/12/how-to-integrate-twitter-in-android.html
Comment: i did its getting working, but after copy pasting it in my project, getting force close, u told previously to include some code in Oncompletemethod of some class na,,, wat shud i give in that class?@Dipak Keshariya


How to interpret PCA on time-series data?

Question: I am trying to understand the use of PCA in a recent journal article titled "Mapping brain activity at scale with cluster computing" Freeman et al., 2014 (free pdf available on the lab website).  They use PCA on time series data, and use the PCA weights to create a map of the brain.
The data is trial-average imaging data, stored as a matrix (called $\hat {\mathbf Y}$ in the paper) with $n$ voxels (or imaging locations in the brain) $\times \hat t$ time points (the length of a single stimulation to the brain).
They use the SVD resulting in $$\hat {\mathbf Y} = \mathbf{USV}^\top$$ ($\mathbf V^\top$ indicating transpose of matrix $\mathbf V$).
The authors state that

The principal components (the columns of $\mathbf V$) are vectors of length $\hat t$, and the scores (the columns of $\mathbf U$) are vectors of length $n$ (number of voxels), describing the projection of each voxel on the direction given by the corresponding component, forming projections on the volume, i.e. whole-brain maps.

So the PCs are vectors of length $\hat t$.  How can I interpret that the "first principal component explains the most variance" as is commonly expressed in tutorials of PCA? We started with a matrix of many highly correlated time-series -- how does a single PC time series explain variance in the original matrix?  I understand the whole "rotation of a Gaussian cloud of points to the most-varied axis" thing, but am unsure how this relates to time-series.  What do the authors mean by direction when they state: "the scores (the columns of $\mathbf U$) are vectors of length $n$ (number of voxels), describing the projection of each voxel on the direction given by the corresponding component"?  How can a principal component time course have a direction?
To see an example of the resulting times series from linear combinations of principle components 1 and 2 and the associated brain map, go to the following link and mouse over on the the dots in the XY plot.

My second question is related to the (state-space) trajectories they create using the principal component scores.
These are created by taking first 2 scores (in the case of the "optomotor" example I have outlined above) and project the individual trials (used to create the trial-averaged matrix described above) into the principal subspace by the equation: $$\mathbf J = \mathbf U^\top \mathbf Y.$$
As you can see by the linked movies, each trace in state space represents the activity of the brain as a whole.
Can someone provide the intuition for what each "frame" of the state space movie means, as compared to the figure that associates the XY plot of the scores of the first 2 PCs.  What does it means at a given "frame" for 1 trial of the experiment to be in 1 position in the XY state-space and another trial to be in another position?  How do the XY plot positions in the movies relate to the principle component traces in the linked figure mentioned in the first part of my question?
Comment: +1 I edited your question, take a look at how one can format tex equations here. Apart from that, I know the paper quite well, so will reply later.
Comment: This is not exactly what the OP wants, but might become handy in interpreting the principal components when taken from time-series data, as I do this all the time. I usually like to interpret PCA as a Karhunen-Loève expansion: expressing a given time series, $X_t$ (the different time-series that you apply PCA to), as a linear combination of uncorrelated time series (i.e., the principal components). The weights of each time series in this case are given by the eigenvectors obtained from the covariance matrix.
Comment: (See this for a more in-depth explaination of my point: http://www.astro.puc.cl/~nespino/files/Ch2_PCA_nespinoza.pdf)
Comment: I added to your question some screenshots that you were referring to.
Comment: Link from @statHacker didn't work for me. Here is one that I found working https://web.archive.org/web/20170517051143/http://www.dsea.unipi.it/Members/balestrinow/CP/file/TD_16_6_davies_pca.pdf
Comment: I also found this tutorial to be spot-on helpful for the first part of the question. http://www.dsea.unipi.it/Members/balestrinow/CP/file/TD_16_6_davies_pca.pdf The 2nd part is well explained by @conjectures . Thank you for your help. Great first experience with stats.stackexchange :) !!!!
Comment: That color palette is amazing, does anyone know what it's called and/or if there is an equivalent in R?  It's just so nice and vibrant.
Answer: Q1: What is the connection between PC time series and "maximum variance"?
The data that they are analyzing are $\hat t$ data points for each of the $n$ neurons, so one can think about that as $\hat t$ data points in the $n$-dimensional space $\mathbb R^n$. It is "a cloud of points", so performing PCA amounts to finding directions of maximal variance, as you are well aware. I prefer to call these directions (which are eigenvectors of the covariance matrix) "principal axes", and the projections of the data onto these directions "principal components".
When analyzing time series, the only addition to this picture is that the points are meaningfully ordered, or numbered (from $1$ to $\hat t$), as opposed to being simply an unordered collection of points. Which means that if we take firing rate of one single neuron (which is one coordinate in the $\mathbb R^n$), then its values can be plotted as a function of time. Similarly, if we take one PC (which is a projection from $\mathbb R^n$ on some line), then it also has $\hat t$ values and can be plotted as a function of time. So if original features are time series, then PCs are also time series.
I agree with @Nestor's interpretation above: each original feature can be then seen as a linear combination of PCs, and as PCs are uncorrelated between each other, one can think of them as basis functions that the original features are decomposed into. It's a little bit like Fourier analysis, but instead of taking fixed basis of sines and cosines, we are finding the "most appropriate" basis for this particular dataset, in a sense that first PC accounts for most variance, etc.
"Accounting for most variance" here means that if you only take one basis function (time series) and try to approximate all your features with it, then the first PC will do the best job. So the basic intuition here is that the first PC is a basis function time series that fits all the available time series the best, etc.

Why is this passage in Freeman et al. so confusing?
Freeman et al. analyze the data matrix $\hat{\mathbf Y}$ with variables (i.e. neurons) in rows (!), not in columns. Note that they subtract row means, which makes sense as variables are usually centred prior to PCA. Then they perform SVD: $$\hat {\mathbf Y} = \mathbf{USV}^\top.$$ Using the terminology I advocate above, columns of $\mathbf U$ are principal axes (directions in $\mathbb R^n$) and columns of $\mathbf{SV}$ are principal components (time series of length $\hat t$).
The sentence that you quoted from Freeman et al. is quite confusing indeed:

The principal components (the columns of $\mathbf V$) are vectors of length $\hat t$, and the scores (the columns of $\mathbf U$) are vectors of length $n$ (number of voxels), describing the projection of each voxel on the direction given by the corresponding component, forming projections on the volume, i.e. whole-brain maps.

First, columns of $\mathbf V$ are not PCs, but PCs scaled to unit norm. Second,  columns of $\mathbf U$ are NOT scores, because "scores" usually means PCs. Third, "direction given by the corresponding component" is a cryptic notion. I think that they flip the picture here and suggest to think about $n$ points in $\hat t$-dimensional space, so that now each neuron is a data point (and not a variable). Conceptually it sounds like a huge change, but mathematically it makes almost no difference, with the only change being that principal axes and [unit-norm] principal components change places. In this case, my PCs from above ($\hat t$-long time series) will become principal axes, i.e. directions, and $\mathbf U$ can be thought as normalized projections on these directions (normalized scores?).
I find this very confusing and so I suggest to ignore their choice of words, but only look at the formulas. From this point on I will keep using the terms as I like them, not how Freeman et al. use them.

Q2: What are the state space trajectories?
They take single-trial data and project it onto the first two principal axes, i.e. the first two columns of $\mathbf U$). If you did it with the original data $\hat{\mathbf Y}$, you would get two first principal components back. Again, projection on one principal axis is one principal component, i.e. a $\hat t$-long time series.
If you do it with some single-trial data $\mathbf Y$, you again get two $\hat t$-long time series. In the movie, each single line corresponds to such projection: x-coordinate evolves according to PC1 and y-coordinate according to PC2. This is what is called "state space": PC1 plotted against PC2. Time goes by as the dot moves around.
Each line in the movie is obtained with a different single trial $\mathbf Y$.
Comment: The short answer is **no**, it is generally not the mean time series, although in many cases it can be quite close. As an example, think of a collection of time series that are all straight lines with different slopes (positive and negative) all going through zero. Then the mean time series is around constant zero. But the first PC will be strong linear line. BTW, I think this is an *excellent* question and if you want more details and/or figures, please ask it (again) as a separate question. Just be sure not to duplicate any parts of this question about Freeman et al.; make them separate.
Comment: (or anyone else interested in a response) - with regards to Q2, what do you mean by "project [each trial] onto the first two [PCs]".  Mathematically it is very clear that U is a vector of length n voxels, and when matrix multiplied by the length n matrix Y we achieve dimensionality reduction to the 1st 2 PCs.  Can you provide intuition with regards to U being the matrix of scores (i.e. the distance of each voxel from the first 2 PCs).  Can I think of each timepoint of J as the 2-d average of the projection of each voxels position in the 2 dimensional plot of the 1st image above?
Comment: You are right, I had this badly explained. I edited my question, expanding several parts of it; please read again from the beginning (or see what I changed) to make sure you follow. Don't think about $U$ as "scores"!! $U$ are principal axes, directions in the neuron space. They take single trials and project on the two first principal axes. What they get (from one trial) is two time series. They could plot both as a function of time, but instead they plot them one against another: PC1 vs PC2. This is "state space". Each line corresponds to different single trial! So to your last question: NO!
Comment: Is "$\mathbf{SV}$" a typo above?:

"Using the terminology I advocate above, columns of U are principal axes (directions in Rn) and columns of SV are principal components (time series of length t^)."
Comment: OK, I am completely confused that you advise not to call U the scores – as this is a direct quote in the gray box above.

The first bit of confusion is that you write: "The data that they are analyzing are t^ data points for each of the n neurons, so one can think about that as t^ data points in the n-dimensional space $\mathbb R^n$. It is "a cloud of points"… ".  But I actually think the data should be in t^ dimensional space, and thus there would be n points.  That is why the resulting loadings vector, the PCs, are of length t^ - each time sample represents and axis in $\mathbb R^t$ space.
Comment: You also wrote: "Second, columns of U are NOT scores, because "scores" usually means PCs."   In my interpretation V, the PCs in the articles terminology, are equivalent to what are called loadings and translate to the rotations of each axis to align to the principal component being described – they are of length t^ because there are t^ axes that need to be rotated.  In other words they describe the hyperplane that is each PC (or possibly principal axis, I'm not sure of the language at this point).
Comment: The terminology of scores, which I am using is the distance of each voxel from each respective principal component (or axes if you like).  Therefore there are n voxels and thus n scores.  The scores are what are doing the projection of each trial into state space per the formula:
$$\mathbf J = \mathbf U^\top \mathbf Y.$$.
Comment: But besides all our confusion in terminology, if we just take the very first point or time sample of the state space movies, and only a single trace corresponding to a single trial, then that point is generated from the first time sample of a single trial, for all voxels – a vector of length n voxels.  That length n vector is (matrix) multiplied by the length n scores vector U resulting in a 2-d point.  But if scores represent the distance of each point from the first 2 principal axes, how can we intuitively understand this "projection" into 2-d space for this single n-d sample we start with?
Comment: I see that this becomes a confusion mess. I am really sorry for that; I will try to edit my answer to address it more explicitly. The point is that the same data $X$ can be seen as $n$ points in $t$-dimensional space, or as $t$ points in $n$-dimensional space. Simply transpose the matrix, and done. Crucially, SVD will not change, just $U$ and $V$ will change places. So one can have two "views" on the same PCA, and additionally use a couple of different terms to refer to $U$ and $V$, hence the mega-confusion. CONT.
Comment: CONT. I think that "my" view is easier to deal with. E.g. in your last question: yes, a single point in a single trace in the movie is generated from a vector of length $n$, which is in my view, simply a point in the $n$-dimensional space. Columns of $U$ define axes in this same space. So multiplying one point by $U^\top$ projects this point onto the corresponding axis. If two columns of $U$ are taken, then you get 2D projection, which is used for the movie. I find it very natural and intuitive to think about it like that.
Comment: The XY plot in the first image of the page is plotting the scores, which translate to the distance each of the n voxels are from the 1st 2 principal axis.  The XY plot of the movie doesnt plot this because the scores are used to compute J.   Therefore, using these scores in J does not project the individual trial time courses Y onto the same principle component axis as the first XY plot -  the scale is much different. This is because each point in the movies correspond to the sum over voxels for whole brain of the product of each voxel's raw image amplitude with that voxels corresponding CONT.
Comment: CONT. score.  But how is the fact the scores being the distance of each of the n voxels from the respective principal axis relate to why a point in the movie is closer or farther from the same principal component in the movie's XY space?
Comment: I guess my point about two "views" on PCA did not really come across. You are right: these two XY plots are completely different. The XY plot in the first image is a scatter plot of neurons; it shows $n$ neurons in the $t$-dimensional space (projected on a plane). The XY plot in the movie is a scatter plot of time points; it shows $t$ time points (connected with a line) in the $n$-dimensional space (projected on a plane). Doing PCA solves both problems simultaneously, in a sense of finding projection planes for neurons and for time points. CONT.
Comment: CONT. This is because in SVD of $X$ you get both $U$ and $V$. But I am afraid we are stuck. I can see two ways to try to get unstuck. First, discuss math and formulas, not interpretations. Second, discuss interpretations, but then we *first* need to agree on the terminology and on which of the two "views" we are using. I suggested my terminology and my "view" in my answer, but you don't seem to like it.
Comment: I asked this question as a comment to below, but perhaps @amoeba can help?  Is the first principal component weights vector just the mean time series collapsing across all voxels? If it were the mean, it would result in the smallest scores to fit to the individual data traces. –
Answer: With respect to the first question. Consider the whole time series through a particular voxel to be a single draw from a multivariate distribution. We can now think of this as a multivariate vector much like any other that we might apply PCA to. The first $p$ columns of $\bf V$ are then the eigen-timecourses which, when linearly combined provide the best approximation to the time course through a particular voxel for the duration $\hat t$ of a stimulus.
So $\bf \hat Y$ is an $n \times \hat t$ matrix and therefore $\bf U$ is $n \times n$ while $\bf V$ is $\hat t \times \hat t$.
With respect to the second question. The equation given is
$\bf J = \bf U^T Y$
We are given that $\bf J$ is a 2 or 3 $ \times t$ matrix. (This involves a small sleight of hand in dropping rows/columns.) Two or three is picked as the dimensionality as this is what can be plotted in figure 6 of the paper.
However  $t \ne \hat t$ so I expect the separate traces (lines in fig 6) have been obtained by chopping $\bf J$ into the different segments corresponding to presentations of the stimulus. Each of these blocks can then be plotted in 2 or 3 dimensional space by considering each column as a point in that space and then drawing a line between the points defined by adjacent columns giving the trajectories.
Following on from the above video 8 appears for each block to add each (column-)point sequentially, join it to the last point, and render this length $\hat t$ sequence as a video.
I've not dealt with the colouring methodology before, and it would take a while before I was confident to comment on that aspect. I found the comment on similarity to Fig 4c confusing as the colouring is obtained there by per-voxel regression. Whereas in Fig 6 each trace is a whole-image artefact. Unless I'm put straight I think it's the direction of the stimulus during that time segment as per the comment in the Figure.
Comment: The first figure above refers to an experiment with the same visual stimulus presented every time.  There is a different figure and movie for those data.  The second figure above refers to a different experiment in which the stimuli are visual stimuli with differing orientations, the traces in the 2nd figure above are colored to simply correspond to differing visual stimuli orientations.
Comment: Also, you are correct that the original vector $\mathbf Y$ is chopped up to lengths of $\hat {\mathbf T}$ $\n$
Comment: You have confused me by discussing $\mathbf V$ and $\mathbf S$ in the equation $$\mathbf J = \mathbf U^\top \mathbf Y.$$  Do you mean the first 2 or 3 columns of $\mathbf U$?
Comment: I've re-arranged things. Apologies, was a left over from before I sorted something else out.
Comment: Thanks for all your help.  Is the first principal component weights vector just the mean time series collapsing across all voxels?  If it were the mean, it would result in the smallest scores to fit to the individual data traces.


Absoloute value of convergent sequence times radius of convergence to n-power is bounded?

Question: I am currently learning about power series solutions for second order linear ODE's. I am reading a proof of the following statement:

Let $x_0$ be an ordinary point of the differential equation
  $y''+p(x)y'+q(x)y=0$, (11)
  and let $a_0$ and $a_1$ be arbitrary constants. Then there exists a unique function $y(x)$
  that is analytic at $x_0$, is a solution of equation (11) in a certain neighborhood of this
  point, and satisfies the initial conditions $y(x_0) = a_0$ and $y'(x_0) = a_1$. Furthermore, if
  the power series expansions of $P(x)$ and $Q(x)$ are valid on an interval $|x − x0|< R$,
  $R > 0$, then the power series expansion of this solution is also valid on the same
  interval
("Differential Equations With Applications And Historical Notes", by George F Simmons), page 246

In the proof, at one point he defines $r$, as some constant smaller than $R$. In the proof, for the sake of simplicity, $x_0$ is assumed to be zero, which means that we know $p(x),q(x)$ converge for $x<|R|$, and consequently, for $|x|<r$. We then let ${p_i},{q_i}$ be the sequences for the power series approximating $P(x)$,$Q(x)$. We know that on this interval, the power series exist, and therefore, converge. By the divergence test, the terms of the sequences must then approach $0$. Now, he says, there must exist some constant $M$ so:
$|p_n|*r^n<M, |q_n|*r^n<M $
"for all $n$". And this is where i get very confused. Because how do we know $|p_n|*r^n$ (or q) converges? It would happen if $|r|<1$, but that has not been given as a requirement. We can't use l'hopitals as $\frac{|p_n|}{\frac{1}{r^n}}$ either since we would have to take the derivative of $|p_n|$ which is a discrete thing. Now, it might be the case that with the "for all $n$", he simply means: "for each $n$, there exist that $M$ with that property", instead of "there exist a $M$ with that properties for that expression no matter what $n$ we plug in. But that second option i think - am not sure - might not be the case as he latter in the proof, for expressions with different values of $n$ uses the same $M$.
So my question is: does $|p_n|*r^n$ really converge (and is therefore bounded) ? And if so, why?
The full proof is in the book so i can't quite link to it
Answer: The series $\sum_{n=0}^\infty p_n x^n$ converges absolutely for $\lvert x\rvert<R$, in particular for $x=r$. Let $M=\sum_{n=0}^\infty \lvert p_n \rvert r^n$. Clearly, $\lvert p_n\rvert\cdot r^n\leq M$. The same can be done for the series with coefficients $q_n$.
Note that one can even chose the constant $M$ uniformly in $r$ on compact subsets of $[0,R)$.
Comment: Ah. Forgot about that. Thanks!


Ascending chain conditions on homogeneous ideals

Question: Here is one exercise from some notes on graded rings. I tried but I got no idea to solve it.
Please help me. Thanks.

Let $R$ be a graded ring. Prove that $R$ is Noetherian (Artinian) if and only if $R$ satisfies the ascending (descending) condition on homogeneous ideals.
Comment: What have you tried so far? The proof imitates the usual proof of the Hilbert Basis Theorem. This is already a direct hint to the solution ...
Comment: Can you post the solution? Sorry I am not good at algebra....
Answer: Proof that $R$ is Noetherian: Suppose $R$ satisfying ACC on homogeneous ideals. Then $R_0$ is Noetherian. Since $R_+$ is generated by homogeneous elements, by acc, we may find finitely many homogeneous elements, $x_1,\ldots,x_n$, such that $R_+=(x_1,\ldots,x_n)$. We claim that $R=R_0[x_1,\ldots,x_n]$. For any homogeneous $f\in R_+$, $f=x_1g_1+\cdots+x_ng_n$, where $g_i$ are homogeneous and with degree less than $f$. By induction $g_i\in R_0[x_1,\ldots,x_n]$, so $f\in R_0[x_1,\ldots,x_n]$. Thus $R=R_0[x_1,\ldots,x_n]$. Finally, by Hilbert's basis theorem, $R$ is Noetherian.
Proof that $R$ is Artinian: First of all, $R_0$ is Artinian. By dcc condition the ideal $R_+$ has indeed only finitely many terms, i.e., $R_+=R_1\oplus R_2\cdots \oplus R_n$. So $R_+$ is a nipotent ideal, $(R_+)^{n+1}=0$. The subring $R_0$ is Artinian, so it has finitely many maximal ideals, say $\mathfrak{m}_1,\ldots,\mathfrak{m}_k$. Then there exists an $l$ such that $\mathfrak{m}_1^l\cdots\mathfrak{m}_k^l=0$. It is clear that maximal ideals of $R$ are exactly $(\mathfrak{m}_i,R_+),i=1,\ldots,k$ and the ideals $\mathfrak{m}_i^lR$ pairwise are comaximal! So by Chinese Remainder Theorem, we only need to show $R/\mathfrak{m}_i^lR$ is Artinian for each $i$. Our dcc condition on homogeneous ideals still holds. Hence we may assume $R_0$ is a Artinian local ring with unique maximal $\mathfrak{m}_0$ and $R$ satisfies the dcc condition on homogeneous ideals. Let us consider the ring $R/\mathfrak{m}_0R$. It must be finite over $R_0/\mathfrak{m}_0$, otherwise, the image of $R_+$ is generated by the image of homogeneous of $R_+$ which is of infinite dimension over $R_0/\mathfrak{m}_0$ and hence we can find an infinite strictly descending chain of homogeneous ideals of $R$. This is a contradiction. Thus $R/\mathfrak{m}_0R$ is finite over $R_0/\mathfrak{m}_0$. Let us pick $f_1,\ldots,f_k$ be homogeneous elements of $R$ such that the image of $R_0+\sum R_0f_i$ is $R/\mathfrak{m}_0R$. Then we claim that $R=R_0+\sum R_0f_i$. Denote $S=R_0+\sum R_0f_i$. Then $R=S+\mathfrak{m}_0R$, thus $R/S=\mathfrak{m}_0R/S$. Now notice that $\mathfrak{m}_0$ is nilpotent! It follows immediately that $R/S=0$. Eventually, we have proved that $R$ is finite over $R_0$ and thus $R$ is Artinian.
Comment: is the result only true for positive graded ring?


Filter columns of a df using other df

Question: I have 2 dataframes (let's call A and B).
In A, I have a structure like this:

And in B, like this:

What I am trying to do is to filter the columns name of A that match with B. But I want to keep the first column.
Doing this I get what I want but I lose the Hugo_Symbol column:
Data_filter <- A[ ,which((names(A) %in% B$SAMPLE_ID)==TRUE)]

Any help is welcome! Thanks!
Comment: Try `df1[names(df1) %in% c(df2$SAMPLE_ID, "Hugo_Symbol")]`. Also please do not share images of data. Use `dput()` to provide reproducible examples
Comment: Try: `A[c(TRUE, names(A)[-1] %in% unique(B$SAMPLE_ID))]`
Comment: Thank you guys for your quick response! Sorry @Sotos I thought it was only one thing missing in my code and I found unnecessary, but you are right, I should put a reproducible example
Answer: Just, add the column name:
Data_filter <- A[ , names(A) %in% c(B$SAMPLE_ID, "Hugo_Symbol")]

Answer: Could also make and "exclude list" data frame, then use anti_join. This is could if you want to remove based on a number of conditions.
Test/pseudo-data:
ID1 <- c(5,10,6)
ID2 <- c(3,5,4)
Value <- rnorm(3)
DF1 <- data.frame(ID1, ID2, Value)

x <- c()
y <- c()
z <- c()

for (i in 1:10){
a <- rep(i, 10)
b <- c(1:10)
c <- rnorm(10)
x <- c(x, a)
y <- c(y, b)
z <- c(z, c)
}

DF2 <- data.frame(x, y, z)

Make a 'exclude' list
excl <- data.frame(
  x = c(DF1$ID1, DF1$ID2),
  y = c(DF1$ID2, DF1$ID1))

Then use anti join:
library(dplyr)
anti_join(DF2, excl, by = c("x", "y"))

Filter columns of a df using other df


How to prevent default Shortcut alt+b by Firefox and IE via JS?

Question: I need to implement a shortcut alt+b, calling a function. My problem is, that everytime i press this shortcut, a Firefox and an IE open a Menu-Bar "Edit". Is there any solution to prevent this default behavior? Or maybe it is possible to close this menu-bar after calling a function?
What i have tried but without success
     $(document).keydown(function(e) {

         if (e.keyCode == 18 || e.which==18)
         {
            e.preventDefault();
         }
      });

Answer: Try this, it will only run the console.log() if you hit Alt+B. Replace the console with anything you want.

$(window).keydown(function(event) {
  if(event.altKey && event.keyCode == 66) {
    event.preventDefault();
    console.log("Hey! alt+B event captured!");
  }
});

Comment: i tried this out, but no success. i tried to debug a .js file and i got this... https://i.stack.imgur.com/YwcxB.jpg                                                                  KeyCode is 18 (ALT)
Answer: This seems to work for me:
$(document).keydown(function(e) {

    // check for alt+b
    if (e.keyCode == 66 && e.altKey === true) {
        e.preventDefault();
    }
});

You need to check the press of b, not alt.
Comment: i tried this out, but no success. i tried to debug a .js file and i got this... https://i.stack.imgur.com/YwcxB.jpg                                                                  KeyCode is 18 (ALT)
Comment: Can you make a live example? For instance using JSFiddle.


willRotateToInterfaceOrientation gets called after device get rotated

Question: I have a some code in the willRotateToInterfaceOrientation: method. But it gets called after orientation gets changed.
And I want this method to be called before orientation gets changed.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
 //some code
}

anyone know why this happens...
Comment: The device only knows to rotate the orientation after the user's actually rotated the device, so there's no way to anticipate the orientation will change until the user actually rotates the device.
Comment: But in documentation support, they written willRotateToInterfaceOrientation() gets called before orientation changed...
Comment: Yes, before the interface orientation changes, not before the device orientation changes.
Answer: I had the same problem but found a way around. Just start listening to device orientation events:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector( detectOrientation )
                                             name: UIDeviceOrientationDidChangeNotification
                                           object: nil];

Your handler (detectOrientation in the example above) will be called before the -willRotateToInterfaceOrientation:toInterfaceOrientationduration: method, thus also before the screen is rendered in the new orientation.
Just pay attention that every call to beginGeneratingDeviceOrientationNotifications must match a call to endGeneratingDeviceOrientationNotifications (as noted in the docs). So if you call the first at -viewDidLoad, don't forget to call the latter at dealloc.
Another thing to mind is that this method turns on the accelerometer hardware, so your application might consume more battery while it is still effective (that is, until you call endGeneratingDeviceOrientationNotifications).


Ionic directives VS Angular material directives with Ionic Framework

Question: I want to use ionic with material design. I am stuck between using ionic directives with custom CSS and angular-material
I have read that using ionic directives we get lot of efficient features like

App data is remembered with UI-router, even after navigating to other view and coming back to the page
Ionic list items are rendered only up to display height and reused when scrolling down or up

and a lot of performance improvements.
But, if I use ionic directives they don't have the material design.
If I use angular-material I will not have these performance improvements, and extra features needed for a mobile application.
Angular-material directives are like
<md-list>
  <md-item ng-repeat="item in items">
    Hello, {{item}}!
  </md-item>
</md-list>

Ionic directives are like
<ion-list>
  <ion-item ng-repeat="item in items">
    Hello, {{item}}!
  </ion-item>
</ion-list>

Looks like Ionic is funding angular-material project development, then why is angular-material not compatible to use with ionic?
How can I use angular-material components without losing the performance improvements and features of ionic?
OR
is there a better idea for using material design with ionic?
Comment: I have posted in ionic forums, with no luck. Some of the google app's are using material design on both android and ios. But I'm currently interested in android. iOS is more costly and every year :( . It just discourages starter's like me to join ios. I think ios should use limited charge for developer account.
Comment: It will propably take some time, until ngMaterial and ionic will work with each other. Ionic always has to support iOS as well. I'm not sure where Ionix is heading design-wise. When the project started they wanted the apps to look identical on all platforms. They scraped that goal some time ago and now head for more platform continuity, which is shown by the job posting as well. You might want to ask the developers directly (the Ionic forum is a good place to ask) concerning the roadmap to material design.
Comment: I'm sure they will announce the post v1 roadmap in the near future.
Answer: I found a material design CSS framework known as Materializecss. It looks promising. It's just plain CSS and javascript framework.
http://materializecss.com/
Advantages over other frameworks

Pure CSS classes, will not conflict with ionic directives. No performance loss.
Of all the frameworks I have seen, this is the only one closely following material design rules
Almost ready it has about 50+ contributors it's current Version 0.95.3 in less than 6 months
Easy to use. Well documented with feature wise navigation.
It has almost all the material design features needed for an app.

This page http://materializecss.com/getting-started.html will show you how to include it in your projects.
I hope this helps for any of you searching for a good material design framework.
UPDATE: 2015-07-09
I Found another lightweight powerful beautiful CSS framework for material design
Material Design Light
http://www.getmdl.io/
It is lightweight, has smooth and quick animations, looking pretty good. It was made by one of the Google developers. It is officially promoted by google  https://developers.google.com/web/. It is getting quite popular, try it. Comparision with Angular Material
UPDATE: 2015-10-23
Ionic2 has InBuilt Support for Material Design in Android
It's Official, You can watch Ionic2 demo in AngularConnect, It has Material Design as default for Android. We don't need to worry about choosing a Material Design framework.
Comment: The big problem with this is that it needs jQuery
Comment: We just need the css. Popup's, modals and other features exists in ionic. So, jquery is mostly not needed unless we are trying to use materialize javascript features that are not in ionic.
Comment: Do u have any feedback using Material Design Light http://www.getmdl.io/
I cam here having the same problem and question about ionic + material design.
So would be much appreciate any feedback about the library
Comment: I have not personally used `Material Design Light`, It looks promising. Here is the comparison of `Material Design Light` and `bootstrap` http://tutorialzine.com/2015/07/comparing-bootstrap-with-mdl/, If you have used bootstrap it will help. Google promoting this in its web developer page. So, It must be good enough.
Answer: There is a fairly new project called Ionic Material.
I've tried it out and it works pretty well, but be advised that it is still in "Pre-Release Preview" mode.
According to the github repo it should enter Alpha in April 2015.
It can be installed with bower
bower install ionic-material
That's pretty much all you need to do, but be warned, there are bugs and the documentation is basically non-existent.
Good luck!
Comment: I have seen ionic-material library before, but the problem is
1. This is no where near completion. No documentation available.
2. This is not in active development, and doesn't have good support. only one guy worked on it for 7 days as seen today. So it is hard use it in production app without guarantee.
3. Angular-material, ionic both have good funding and support and very good developers are working on it, at good pace. so I can trust them.
Answer: Ionic Material and Ionic Material Design Lite are two budding new libraries that aim to be an extension of ionic framework. Though a little immature, works well with ionic components and supports the material theming well.
This probably could give more of an insight.


Nesting a text inside a tag in slim

Question: How do I nest the 'Featured' text inside the a tag, given the span, the text, and the other span are siblings?
li
  a href="#" class="selected"
    span class="icon-before"
    Featured
    span class="icon-after"

Answer: li
  a href="#" class="selected"
    span class="icon-before"
    | Featured
    span class="icon-after"

Gives:

Featured

Answer: ul
  li
    | first text
    span.color-red.bold-g
     | (text transform)

Give :

first text(text transform)

Nesting a text inside a tag in slim


Case-sensitive database search with Active Record

Question: Does Active Record provide a way to generate SQL that forces a text search to be case-sensitive?
Ruby-on-Rails generators instructed to create a string-type column produce a simple VARCHAR(255) field, in a mysql database. It turns out that queries on such columns are case insensitive by default.
Thus, an Active Record search such as:
Secret.where(token: 'abcde')

will match records with tokens abcde, ABcdE, etc.
Without changing the underlying database column (e.g. specifying a utf8_bin collation) searches can be made case sensitive by explicitly tweaking the where clause:
Secret.where('binary token = ?', 'abcde')

However, this is database-specific, and I am wondering if Active Record has an idiom to accomplish the same for any database. Just as an example, something resembling the where.not construct:
Secret.where.binary(token: 'abcde')

Wouldn't this be a common enough need?
Comment: `Secret.where('binary token LIKE ? ', '%abcde%')` how about this?
Comment: Duplicate of: https://stackoverflow.com/questions/2220423/case-insensitive-search-in-rails-model ?
Comment: @Gabbar, this is similar to my own version, in that you are actually writing database-specific SQL. My question is about whether an Active Record abstraction exists.
Comment: I'm not getting you exactly , but so far as i understand Active Record also contact to database in return of sql query to ORM object.
Comment: Active Record searches are NOT case-insensitive by default. Moreover, AR is not about "case sensitivity", it is about SQL constructing and mapping result to the objects. I guess, either you DB settings or `token` column type is the reason why SQL query, generated by `Secret.where(token: 'abcde')`, makes case-insensitive search.
Comment: @PavelMikhailyuk, you are right, the question needs editing. But first, at least when the RoR-generated mysql column is a `varchar(255)`, part of an `InnoDB`, `utf8mb4` table, a search like `Secret.where(token: 'abcde')` is indeed case-insensitive. Agree? It is at least conceivable that AR might provide a way to construct (db-specific) SQL that forces the query to be case-sensitive. Am I still missing something?
Comment: @Austio, my question is related, but I think quite distinct from the one you refer to.
Comment: @PavelMikhailyuk, please see my extensive edits. Thanks!
Comment: `binary` is MySQL-specific, other DBs use different syntax for type casting. And "other DBs" use case-sensitive `collation` by default. So, probably, Rails team does not consider it as "common enough need". Moreover, I haven't find even `COLLATE` usage in ActiveRecord sources(except for schema definition), despite `COLLATE` is much more _common_ across DB, than `binary`.
Comment: @PavelMikhailyuk, I gather from your comments that the brief answer to my question is NO. If so, would you go ahead and post a response? I'd like to see this question resolved.
Answer:
In short: there is NO ActiveRecord idiom for case-sensitive
  search.

For case-insensitive search you can try to use
  this.
  It still works, but source code was changed a bit. So, use it on your
  own risk.

In general, case sensitivity is subset of the Collation idiom.
And different DBMS use very different default collations for string(text) data types, including default case sensitivity.
Detailed description for MySQL.
There is a sql operator COLLATE which is very common across DBMS(but seems still is not in SQL Standard).
But ActiveRecord sources show it only in schema creation code.
Neither ActiveRecord, nor Arel gems do not use COLLATE in where search(sad).
Note: Please, don't miss the database tag(mysql etc) in a Question.
There are many Questions and Answers on SO without the tags(or with sql one), which are completely irrelevant for the most of DBMSs except author's one.
Comment: I had initially avoided the `mysql` tag on purpose because the essence of my question was NOT db-specific. I was seeking a functionality that could have been provided by AR, such that one would not have to worry about the specific database syntax. Anyhow, tag added now.
Comment: I left the note not for you only: I've really spent "a tons" of time on SO, understanding what DBMS Q/A was related to. Hint: DBMS(especially postgresql :) ) tag also triggers some good SO members to answer even they don't know Rails.


Find triples of solutions for the equation $a+2b^2+3c^3+\frac{1}{a}+\frac{2}{b^2}+\frac{3}{c^3}=12$

Question: How can I find the triples of solutions ($a,b,c$) for the equation $a+2b^2+3c^3+\frac{1}{a}+\frac{2}{b^2}+\frac{3}{c^3}=12$.
Answer: I'm going to assume $a,b,c > 0$.
$a + \frac{1}{a} \ge 2$ by say the AM-GM inequality, with equality iff $a =1$.
Similarly $2b^2 + \frac{2}{b^2} \ge 4$ and $3c^3 + \frac{3}{c^3} \ge 6$ with equality when they are equal to $1$.
Combining these gives $a+2b^2+3c^3+\frac{1}{a}+\frac{2}{b^2}+\frac{3}{c^3}\ge12$ with equality iff $a=b=c=1$


Prove A' ∪ B′ = (A ∩ B)'

Question: Prove $A' ∪ B′ = (A ∩ B)'$
Let, $M=A' ∪ B′  $ and $ N=(A ∩ B)'$
Let $x$ be an arbitrary element of M then
$x\in M\Rightarrow x\in A'∪B'\Rightarrow x\in A'$ or $x\in B'\Rightarrow x\not\in A$ or $x\not\in B\Rightarrow x\not\in(A∪B)\Rightarrow x\in(A∪B)'$????
I think I'm doing something wrong, can you help me?
Comment: $x∉A$ or $x∉B$ ⇒ $x∉(A \cap B)$
Comment: NO; $x \in A'$ means $x$ belongs to the *complement* of $A$. Bu the complement of $A$ is **defined** as the set of all elements that do **not** belong to $A$. Thus : $x \in A' \Leftrightarrow x \notin A$.
Comment: @MauroALLEGRANZA Thanks!
Comment: @MauroALLEGRANZA so $x\in A'\not\Rightarrow x\not\in A$? and $x\in A\not\Rightarrow x\not\in A'$?
Comment: ok, definitely better
Answer: Narrowly on your argument. It is fine as far as $x\notin A$ or $x\notin B$. But that does not imply that it is in neither, it implies that it is not in both. So yes, you did to do something wrong - almost at the end of your argument.
Comment: You need to use $\subset$ not $\in$!
Comment: if $A,B\in R$ and $A\not=B$
$x\in A' \Rightarrow x\in B\setminus\left \{A\cap B  \right \} $ and
$x\in B' \Rightarrow x\in A\setminus\left \{B\cap A  \right \}$
is it correct?
Comment: @vmahth1 What is $R$? The set $B\setminus (A\cap B)$ is a subset of $B$. So why should the fact that $x$ is **not in** $A$ imply that it **is in** $B$?
Comment: $x\in A' \Rightarrow B\setminus\left \{A\cap B  \right \}\in x $ ,
$x\in A'\not\Rightarrow x\in B\setminus\left \{A\cap B  \right \}$?
Comment: $A$ and $B$ are unrelated sets. Suppose we are looking at subsets of $X=\{1,2,3,4,5\}$ and $A=\{3,4,5\}$, whilst $B=\{1,3\}$. Then $A'=\{1,2\}$, $A\cap B=\{3\}$, so $B\setminus(A\cap B)=\{1\}$. Then $1$ belongs to both $A'$ and $B\setminus(A\cap B)$, but $2$ belongs to $A'$ and **does not** belong to $B\setminus(A\cap B)$.
Comment: so $B\setminus(A\cap B)\in A'$ and $A' \not\in B\setminus(A\cap B)$
Comment: ok Thanks @almagest for help
Comment: But enough of this! You need to learn the definitions of complement, setminus etc carefully and work out some examples **carefully** on your own. Try Venn diagrams. They can be most helpful!
Comment: My problem was that he was currently I am using literature and was given a simple example and suddenly given more difficult tasks and it was difficult to do it on the way

Prove A' ∪ B′ = (A ∩ B)'


Unable to launch application after changing something in the manifest

Question: i tried to add a share intent to the manifest but i did something wrong, now when i delete what i added it keeps coming back after i launch the application. So i cant launch the application as i could before, if needed i can add more code or logs. im at a loss
My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.drieo.soundwave.test.cms"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="18"
    android:targetSdkVersion="23" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<activity
    android:name="nl.drieo.soundwave.test.cms.ShareActivity"
    android:label="@string/title_activity_share" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />

        <category android:name="android.intent.category.DEFAULT" />

        <data android:mimeType="image/*" />
    </intent-filter>
</activity>

<application
    android:allowBackup="true"
    android:fullBackupContent="true"
    android:icon="@mipmap/ic_launcher"
    android:label="Multi-CMS"
    android:screenOrientation="portrait"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.NoActionBar" >
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainActivity"
        android:label="Drie-O  CMS"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainAdministration"
        android:label="Administration"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComponents"
        android:label="Components"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainUsers"
        android:label="Users"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_Content"
        android:label="Content"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_Label"
        android:label="Label"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_Content_edit"
        android:label="EditContent"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"
        android:windowSoftInputMode="stateHidden|adjustResize" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_news"
        android:label="MainComp_news"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_News_Edit"
        android:label="MainComp_news_edit"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"
        android:windowSoftInputMode="stateHidden|adjustResize" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_Label_edit"
        android:label="MainComp_news_edit"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"
        android:windowSoftInputMode="stateHidden|adjustResize" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_AgendaItem"
        android:label="MainComp_news_edit"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.MainComp_AgendaItem_edit"
        android:label="MainComp_news_edit"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"
        android:windowSoftInputMode="stateHidden|adjustResize" />
    <activity
        android:name="nl.drieo.soundwave.test.cms.new_content_item"
        android:label="MainComp_news_edit"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
</application>

Errors i got when launched:
Information:Gradle tasks [:app:assembleDebug]
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2320Library UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72320Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72311Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2320Library UP-TO-DATE
:app:prepareComAndroidSupportPercent2320Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72320Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42320Library UP-TO-DATE
:app:prepareComAndroidSupportSupportVectorDrawable2320Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest
:app:processDebugResources
C:\Users\r.devries\AndroidStudioProjects\CMS2\app\build\intermediates\manifests\full\debug\AndroidManifest.xml
Error:(18, 24) No resource found that matches the given name (at 'label' with value '@string/title_activity_share').
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\r.devries\AppData\Local\Android\sdk\build-tools\23.0.2\aapt.exe'' finished with non-zero exit value 1
Information:BUILD FAILED
Information:Total time: 1.166 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console

Comment: The "doesn't want to be deleted" part is what I am talking about. **Make sure that you are editing your actual manifest**, not some other tab that Android Studio happened to open.
Comment: @Sanoop i never changed that, so why would it be a problem now?
Comment: Make sure that you are editing your real manifest. Sometimes, when you get an error in the manifest, Android Studio opens up a tab on the *generated* manifest, the one that blends in information from your dependencies and `build.gradle` settings. Editing that does you no good. See [this issue](https://code.google.com/p/android/issues/detail?id=93290) for more.
Comment: @CommonsWare i am sorry i got the wrong manifest, this is what it looks like the top activity is what i added and tried to delete and doesnt want to be deleted. i edited the question
Comment: You defined an Activity outside of the application tag. I'm not sure, but it may cause errors
Comment: Could you share String.xml resource file?
Comment: @0xDEADC0DE That is the problem i cant get rid of it, it wont allow me to delete it.
Comment: @Robbert, Then I think CommonsWare is on the right track
Comment: @CommonsWare I am sorry, that is my awnser, didnt know this was a thing! thank you sir!
Comment: @CommonsWare respond this awnser as an actual awnser and il accept it as an awnser :)
Answer: When you get a build error tied to your manifest, and you double-click on the error in the build output, Android Studio (through 2.0.0) will pop open a tab on a manifest.
Unfortunately, it is the wrong manifest.
This is a long-standing bug in Android Studio, where clicking the error opens up a generated manifest, one that blends information from your module's manifest, libraries, build.gradle, etc. Editing this is possible, if you do not mind your changes vanishing as soon as you do your next build.
Make sure that you edit your real module manifest file. The tab will show something like debug/AndroidManifest.xml when you are editing the generated one.
Comment: Everything corrects, but it happens to every xml resource file too, not only the manifest ;).
Probably this would be corrected in Android Studio 2.2
Answer: No resource found that matches the given name (at 'label' with value '@string/title_activity_share').
Please check you have title_activity_share item in your strings.xml.


How to return an Integral in Haskell?

Question: I'm trying to figure out Haskell, but I'm a bit stuck with 'Integral'.
From what I gather, Int and Integer are both Integral.
However if I try to compile a function like this:
lastNums :: Integral a => a -> a
lastNums a = read ( tail ( show a ) ) :: Integer

I get
Could not deduce (a ~ Integer)
from the context (Integral a)

How do I return an Integral?
Also lets say I have to stick to that function signature.
Answer: Let's read this function type signature in English.
lastNums :: Integral a => a -> a

This means that "Let the caller choose any integral type.  The lastNums function can take a value of that type and produce another value of the same type."
However, your definition always returns Integer.  According to the type signature, it's supposed to leave that decision up to the caller.
Easiest way to fix this:
lastNums :: Integer -> Integer
lastNums = read . tail . show

There's no shame in defining a monomorphic function.  Don't feel it has to be polymorphic just because it can be polymorphic.  Often the polymorphic version is more complicated.
Here's another way:
lastNums :: (Integral a, Num a) => a -> a
lastNums = fromInteger . read . tail . show . toInteger

And another way:
lastNums :: (Integral a, Read a, Show a) => a -> a
lastNums = read . tail . show

Comment: Another way of reading the signature in English, same as this answer but with a slightly different emphasis: for any `Integral` type `a` **that the caller chooses**, this function accepts and returns **that exact same type**. This "caller choice" dynamic can be very useful for understanding this sort of situation.  The problem with OP's function then is that the caller may have chosen some other `Integral` type that's not `Integer`.
Comment: @dfeuer: `fromInteger` is part of `Num`, last time I checked.
Comment: @LuisCasillas: That's a good way of phrasing it.  I've integrated that into the answer.
Comment: Yes, but `Integral` is a subclass of `Real` (itself a subclass of `Num` and `Ord`), as well as `Enum`.
Answer: While Int and Integer both implement Integral, Haskell doesn't quite work like that.  Instead, if your function returns a value of type Integral a => a, then it must be able to return any value that implements the Integral typeclass.  This is different from how most OOP languages use interfaces, in which you can return a specific instance of an interface by casting it to the interface type.
In this case, if you wanted a function lastNums to take an Integral value, convert it to a string, drop the first digits, then convert back to an Integral value, you would have to implement it as
lastNums :: (Integral a, Show a, Read a) => a -> a
lastNums a = read ( tail ( show a ) )

Answer: You need to be able to Read and Show also. And get rid of the Integer annotation. An Integer is a concrete type while Integral is a typeclass.
lastNums :: (Integral a, Show a, Integral b, Read b) => a -> b
lastNums = read . tail . show

*Main> lastNums (32 :: Int) :: Integer
2

Answer: The Integral class offers integer division, and it's a subclass of Ord, so it has comparison too. Thus we can skip the string and just do math. Warning: I haven't tested this yet.
lastNums x | x < 0 = -x
           | otherwise = dropBiggest x

dropBiggest x = db x 0 1

db x acc !val
  | x < 10 = acc
  | otherwise = case x `quotRem` 10 of
                  (q, r) -> db q (acc + r * val) (val * 10)

Side notes: the bang pattern serves to make db unconditionally strict in val. We could add one to acc as well, but GHC will almost certainly figure that out on its own. Last I checked, GHC's native code generator (the default back-end) is not so great at optimizing division by known divisors. The LLVM back-end is much better at that.

How to return an Integral in Haskell?