Android Development- Intents

Question: I have recently started Android development on API version 16 (4.1). According to the tutorials that are available on developer.android.com I started to develop the app which taught me the use of Intents. The problem is that as soon as my app is loading on the Emulator it shows the error that the app had to shut down. I am giving my xml code. Can someone please tell me where I am going wrong? Thanks.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<EditText
    android:id="@+id/et1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="Edit text"
    android:layout_weight="1"
    tools:ignore="HardcodedText" />

<Button
    android:id="@+id/b1"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:text="Press"
    android:onClick="sendMessage"
    tools:ignore="HardcodedText" />

</LinearLayout>

The logcat is given below.
09-26 19:35:03.880: E/Trace(615): error opening trace file: No such file or directory     (2)
09-26 19:35:04.430: D/AndroidRuntime(615): Shutting down VM
09-26 19:35:04.430: W/dalvikvm(615): threadid=1: thread exiting with uncaught exception  (group=0x40a13300)
09-26 19:35:04.471: E/AndroidRuntime(615): FATAL EXCEPTION: main
09-26 19:35:04.471: E/AndroidRuntime(615): java.lang.RuntimeException: Unable to     instantiate activity ComponentInfo{com.learn.training1/com.learn.training1.Training1}:     java.lang.NullPointerException
 09-26 19:35:04.471: E/AndroidRuntime(615):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.os.Looper.loop(Looper.java:137)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 19:35:04.471: E/AndroidRuntime(615):  at java.lang.reflect.Method.invokeNative(Native Method)
09-26 19:35:04.471: E/AndroidRuntime(615):  at java.lang.reflect.Method.invoke(Method.java:511)
09-26 19:35:04.471: E/AndroidRuntime(615):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 19:35:04.471: E/AndroidRuntime(615):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 19:35:04.471: E/AndroidRuntime(615):  at dalvik.system.NativeStart.main(Native Method)
09-26 19:35:04.471: E/AndroidRuntime(615): Caused by: java.lang.NullPointerException
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.app.Activity.findViewById(Activity.java:1825)
09-26 19:35:04.471: E/AndroidRuntime(615):  at com.learn.training1.Training1.<init>(Training1.java:15)
09-26 19:35:04.471: E/AndroidRuntime(615):  at java.lang.Class.newInstanceImpl(Native Method)
09-26 19:35:04.471: E/AndroidRuntime(615):  at java.lang.Class.newInstance(Class.java:1319)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
09-26 19:35:04.471: E/AndroidRuntime(615):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
09-26 19:35:04.471: E/AndroidRuntime(615):  ... 11 more
09-26 19:35:32.352: I/Process(615): Sending signal. PID: 615 SIG: 9
09-26 19:39:22.460: E/Trace(664): error opening trace file: No such file or directory (2)
09-26 19:39:22.820: D/AndroidRuntime(664): Shutting down VM
09-26 19:39:22.820: W/dalvikvm(664): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-26 19:39:22.846: E/AndroidRuntime(664): FATAL EXCEPTION: main
09-26 19:39:22.846: E/AndroidRuntime(664): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.learn.training1/com.learn.training1.Training1}: java.lang.NullPointerException
 09-26 19:39:22.846: E/AndroidRuntime(664):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.os.Looper.loop(Looper.java:137)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 19:39:22.846: E/AndroidRuntime(664):  at java.lang.reflect.Method.invokeNative(Native Method)
09-26 19:39:22.846: E/AndroidRuntime(664):  at java.lang.reflect.Method.invoke(Method.java:511)
09-26 19:39:22.846: E/AndroidRuntime(664):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 19:39:22.846: E/AndroidRuntime(664):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 19:39:22.846: E/AndroidRuntime(664):  at dalvik.system.NativeStart.main(Native Method)
09-26 19:39:22.846: E/AndroidRuntime(664): Caused by: java.lang.NullPointerException
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.app.Activity.findViewById(Activity.java:1825)
09-26 19:39:22.846: E/AndroidRuntime(664):  at com.learn.training1.Training1.<init>(Training1.java:15)
09-26 19:39:22.846: E/AndroidRuntime(664):  at java.lang.Class.newInstanceImpl(Native Method)
09-26 19:39:22.846: E/AndroidRuntime(664):  at java.lang.Class.newInstance(Class.java:1319)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
09-26 19:39:22.846: E/AndroidRuntime(664):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
09-26 19:39:22.846: E/AndroidRuntime(664):  ... 11 more
09-26 19:40:29.130: E/Trace(712): error opening trace file: No such file or directory (2)
09-26 19:40:29.431: D/dalvikvm(712): newInstance failed: Lcom/learn/training1/Training1; not accessible to Landroid/app/Instrumentation;
09-26 19:40:29.431: D/AndroidRuntime(712): Shutting down VM
09-26 19:40:29.431: W/dalvikvm(712): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-26 19:40:29.461: E/AndroidRuntime(712): FATAL EXCEPTION: main
09-26 19:40:29.461: E/AndroidRuntime(712): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.learn.training1/com.learn.training1.Training1}: java.lang.IllegalAccessException: access to class not allowed
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.os.Looper.loop(Looper.java:137)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 19:40:29.461: E/AndroidRuntime(712):  at java.lang.reflect.Method.invokeNative(Native Method)
09-26 19:40:29.461: E/AndroidRuntime(712):  at java.lang.reflect.Method.invoke(Method.java:511)
09-26 19:40:29.461: E/AndroidRuntime(712):  at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 19:40:29.461: E/AndroidRuntime(712):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 19:40:29.461: E/AndroidRuntime(712):  at dalvik.system.NativeStart.main(Native Method)
09-26 19:40:29.461: E/AndroidRuntime(712): Caused by: java.lang.IllegalAccessException: access to class not allowed
09-26 19:40:29.461: E/AndroidRuntime(712):  at java.lang.Class.newInstanceImpl(Native Method)
09-26 19:40:29.461: E/AndroidRuntime(712):  at java.lang.Class.newInstance(Class.java:1319)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
09-26 19:40:29.461: E/AndroidRuntime(712):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
09-26 19:40:29.461: E/AndroidRuntime(712):  ... 11 more
09-26 19:43:52.020: E/Trace(760): error opening trace file: No such file or directory (2)
09-26 19:43:52.110: D/dalvikvm(760): newInstance failed: Lcom/learn/training1/Training1; not accessible to Landroid/app/Instrumentation;
09-26 19:43:52.110: D/AndroidRuntime(760): Shutting down VM
09-26 19:43:52.110: W/dalvikvm(760): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-26 19:43:52.190: E/AndroidRuntime(760): FATAL EXCEPTION: main
09-26 19:43:52.190: E/AndroidRuntime(760): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.learn.training1/com.learn.training1.Training1}: java.lang.IllegalAccessException: access to class not allowed
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.os.Looper.loop(Looper.java:137)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 19:43:52.190: E/AndroidRuntime(760):  at java.lang.reflect.Method.invokeNative(Native Method)
 09-26 19:43:52.190: E/AndroidRuntime(760):     at java.lang.reflect.Method.invoke(Method.java:511)
09-26 19:43:52.190: E/AndroidRuntime(760):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 19:43:52.190: E/AndroidRuntime(760):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 19:43:52.190: E/AndroidRuntime(760):  at dalvik.system.NativeStart.main(Native Method)
09-26 19:43:52.190: E/AndroidRuntime(760): Caused by: java.lang.IllegalAccessException: access to class not allowed
09-26 19:43:52.190: E/AndroidRuntime(760):  at java.lang.Class.newInstanceImpl(Native Method)
09-26 19:43:52.190: E/AndroidRuntime(760):  at java.lang.Class.newInstance(Class.java:1319)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
09-26 19:43:52.190: E/AndroidRuntime(760):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
09-26 19:43:52.190: E/AndroidRuntime(760):  ... 11 more
09-26 19:47:20.550: I/Process(810): Sending signal. PID: 810 SIG: 9

Comment: always put your logcat (exceptions) when asking questions related to crash
Comment: Sorry. I'm really inexperienced when it comes to android. What part of the logcat do I submit? Everything?
Comment: the Error part... i mean the messages in red color. otherwise put it all :)
Comment: put the code for `Training1` too. The problem seems in the code
Comment: Yep. `Training1` code is needed, the error can be found here: `at com.learn.training1.Training1.(Training1.java:15)`
Answer: Looks like your activity isn't properly declared (maybe you didn't make it public?). You should have a file called Training1.java and in this file you should have something like
public class Training1 extends Activity {
    ...your activity code here...
}

See https://groups.google.com/forum/?fromgroups=#!topic/android-developers/0Gw5WHc1J6g
EDIT: Add note
Note: Also, you shouldn't have any constructors. The Android framework takes care of that for you.
Comment: @Leandros Actually, it looks like OP posted his entire logcat which has multiple attempts. My answer refers to the most recent one at 19:43:52. There were other errors (including the NPE you refer to) in other attempts at 19:35:04, 19:39:22 and 19:40:29. OP probably tried a few different things before posting his question.
Comment: Theres simply a `NullPointerException` at `com.learn.training1.Training1.(Training1.java:15)`
Comment: Oh, I see. Don't noticed it before.

Android Development- Intents


Match multiple columns in two data frames and print unequal

Question: So I have two large (in some part different) data frames, first is named sifrant and consist of:
   IDP   PREDMET   ID    NAME
1 120_1  ustanove  _18 Barbara
2 120_1  ustanove _301  Mojca
3 200_1  zakonod  _954  Klara

And other data frame is dalled baza
predmet sifpredm izvajalec1 sifizv1 izvajalec2 sifizv2 izvajalec3 sifizv3 izvajalec4 sifizv4 izvajalec5 sifizv5
ustanove    120_1   Barbara      _18     Mojca     _301     Klara     _954         -2      -2         -2      -2
ustanove    120_1   Barbara      _18     Mojca     _301         -2      -2         -2      -2         -2      -2

Boath data frames should have equal values in next colums: IDP==sifpredm and ID==sifizv1, siizv2, sifizv3, and so on.
Now I would like to match this columns
 IDP with sifpredm and
 ID with sifizv1 and sifizv2 and sifizv3 and so on.
Based on match, I would like to print IDP, ID and NAME that do not have match in sifrant (i.e., is missing in sifrant and is present in baza)
Comparing two data frames I can see that in data frame sifrant lecturer  Klara is missing IDP 120_1. So my output should print which sifpredm, sifizv and izvajalec are in baza but not in sifrant. In my case sifrant is missing class with ID number 120_1, lecturer ID number _954, lecturer name Klara
So far I have tried
    merge(sifrant, baza, by.x = "IDP",by.y="sifpredm" , all = T)

and
 require(sqldf)
    sifrantNotInbaza <- sqldf('SELECT * FROM baza EXCEPT SELECT * FROM sifrant')

and
library(diffobj)
install.packages("diffobj")
diffPrint(sifrant, baza)
diffObj(sifrant, baza)

I've also looked here
Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2
Here is also dput of both data frames:
structure(list(IDP = c("120_1", "120_1"), PREDMET = c("ustanove",
" ustanove"), ID = c("_18", "_301"), NAME = c("Barbara", "Mojca "
)), .Names = c("IDP", "PREDMET", "ID", "NAME"), class = "data.frame", row.names = c(NA,
-2L))

structure(list(predmet = c("ustanove", "ustanove"), sifpredm = c("120_1",
"120_1"), izvajalec1 = c("Barbara ", "Barbara "), sifizv1 = c("_18",
"_18"), izvajalec2 = c("Mojca ", "Mojca "), sifizv2 = c("_301",
"_301"), izvajalec3 = c("Klara ", "-2"), sifizv3 = c("_954",
"-2"), izvajalec4 = c(-2L, -2L), sifizv4 = c(-2L, -2L), izvajalec5 = c(-2L,
-2L), sifizv5 = c(-2L, -2L)), .Names = c("predmet", "sifpredm",
"izvajalec1", "sifizv1", "izvajalec2", "sifizv2", "izvajalec3",
"sifizv3", "izvajalec4", "sifizv4", "izvajalec5", "sifizv5"), class = "data.frame", row.names = c(NA,
-2L))

Answer: I think you need to correct your dput for sifrant. I copied in the table you've got in your description instead.
Then I would do something like:
library(tidyverse)
baza2 <- baza %>%
           gather(contains("sifizv"),
                key = "sifizv",
                value = "ID"
                ) %>%
           select(1:2,ID) %>%
           unique()
output <- anti_join(baza2, sifrant, by = c("sifpredm" = "IDP", "ID"))

This tells you the ID of the missing person. You can then look up their name by using match or:
left_join(output, sifrant) %>% select(sifpredm, predmet, ID, NAME)

Comment: Yes I've missed one row in dput. thx. But your output gives `IDP PREDMET   ID  NAME
1 200_1      zakonod  _954 Klara` but my outpus should be ID of class that is not in sifrant so it should be IDP PREDMET   ID  NAME
1 120_1      ustanove  _954 Klara`
Comment: No, the result is the same, I stil get `200_1` .... So in my example Klara with IDP  120_1 is in `baza` but not in `sifrant`, so my output should look like this:`120_1  ustanove _954  Klara` because this lecture is not in `sifrat` but is in `baza`.
Comment: Edited again. Hopefully it should reflect what you need now.
Comment: Malenkost stari! lp
Comment: Haha :). Legenda :).


How to remove separation between UITableView cells

Question: I want to remove the built in separation between cells in UITableView.
I tried using :
[self.myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];

But that only removes the separator line.
I need the view to appear as if it's not a table view at all. (like the tableview is one big view who doesn't contain many separated cells)
Is that possible ?
Edit:
See the separation between the cells? I wan't it to disappear and the table view to be as if it's one big cell.

Edit 2:
The problem doesn't appear when I don't use an image view as the cell background, but just use a simple background color.
I tried using a different image, and as you can see the problem is much less obvious.
I would still appreciate a solution for the red image though, since I do have a lot of images that still can't be put as background currently. (Not sure why one image would cause the problem and other won't ,I guess something with the pic setting)
Comment: @AntwanVanHoudt - table views are ther for laying out data. What. The end result looks like is irrelevant.
Comment: It looks like the red image has shading, and the top of each cell shows the top of the image, which creates the line effects. If you want the gradient in that image without the appearance of separation, lay the table view on top of the image, and set the table view cell colors as UIColor clearColor. This should stop it from repeating in every cell.
Comment: If it shouldn't look like an UITableView then why are you using one?
Comment: If you use `UITableViewStylePlain` and no section titles/footers, you should not see any separators at all.
Answer: You can do something like
self.tableView.separatorColor = [UIColor whiteColor];
or
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
I suppose in your case it would be
self.myTableView.separatorColor = [UIColor whiteColor];
In the future you might want to search Stack Overflow as there are many similar questions.
Comment: Haven't you read my question ? cause I tried already exactly what you suggested and it didn't do all the job.
Comment: Well it's confusing _what_ you want because you say "I need the view to appear as if it's not a table view at all. (like the tableview is one big view who doesn't contain many separated cells)" which leads me (and other posters) to wonder _why_ you're using a TableView at all. If you want the table view structure without the scrolling effect just do `self.tableView.scrollEnabled = NO;` Maybe you can clarify your question if you aren't getting satisfactory replies.
Answer: Your separation is due to the background gradient in the red example and it is  not coming from the tableView. in your second image there is no gradient so you don't see separation.
remove the gradient from the background image and it will be fine.
Answer: try to do this:
self.tableView.backgroundColor=[UIColor clearColor];
self.tableview.separatorColor=[UIColor clearColor];
self.view.backgroundColor=[UIColor yourcolor];

i don't remember if it's then color with image or backgroundwithimage or background with view.. don't remember, however logic way is this.
hope it's usefull
Answer: If you just want to get rid of the separator between UITableView cells. Two things you need.

[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
Make sure your imageView ( in your tableview cell) has same height as tableview cell. This means your image view is fully covering the table view cell. Goto inspector view and verify the height , if you see the height is 43 just set it to 44 ( 44 is default tableview cell height for retina display).
Answer: Go StroyBaord -> Select Table -> Attribute inspector -> Separator None
No Separator Will Appear
Answer: You seem to have answered your own question. If you want a solid colored background, make an image with just a solid color. I suspect it's not best practice, but it will get the job done.
Comment: Hi Moshe, I do use custom cells, but I guess the problem is not with the cells, it's with how the TableView present them.
Comment: I will try your suggestion about the sections and let you know the results. thanks
Comment: Sorry man, but your suggestion didn't work. Maybe you didn't understood me well, see my question now - I edited it.
Answer: I've done this many times in my own applications. I understand that you wish to make your tableview look as if its not a tableview but as if its on a blank piece of paper.
Just a note for you, the reason you can see the separation with some images and not so much with others is due to its image texture. When you place copies of the image side by side, they dont have a continuous pattern thus forming obvious visual separations.
Solution:
Assuming you have the tableview setup in a xib file, display the background of the table itself to to clear -> then set the background of the view itself to whatever image you like. You will then have a tableview with the background view being transparent with only the main view behind it showing its image or color. Displaying your image on this canvas will mean a clear one image background.


How to display raw messages in Ansible?

Question: I have the following playbook:
---
- name: Find sudo mit PPID 1
  hosts: solaris
  become: true

  tasks:
    - shell: "pgrep -P1 -x sudo | xargs -n1 ptree"
      register: result
    - debug: var=result.stdout_lines

The command ansible-playbook quotes the standard output of the command in JSON syntax:
ok: [gggggggg] => {
    "result.stdout_lines": [
        "26982 sudo su -",
        "  26983 -sh",
        "    6628  zlogin NNNNNNNN",
        "      6629  -sh"
    ]
}

This is pretty unreadable for me.
Is it possible to write stdout without JSON quoting as it is done by ad-hoc commands?
gggggggg | SUCCESS | rc=0 >>
17589 sudo su -
  17590 -sh
    17613 zlogin NNNNNNNN
      17614 -sh
        17646 bash

Comment: @TimFletcher No I can't. It is even less readable.
Comment: No, but you could instead write the output to a file.
Comment: @larsks Can I use file descriptor 2 as the file?
Comment: You can use `results.stdout`
Answer: Try using the to_nice_json filter:
tasks:
- shell: "pgrep -P1 -x sudo | xargs -n1 ptree"
  register: result
- debug: var="{{ result.stdout_lines | to_nice_json }}"

How to display raw messages in Ansible?


Multiple filters in ng-repeat where one requires exact matching

Question: I have written this filters in ng-repeat and this works correctly.

Now I need a function that filters with same criterion. I have written this
$scope.getData = function () {
    return $filter('filter')($scope.data, { Name: $scope.search, Country: $scope.country, MembershipType: $scope.membership, Gender: $scope.gender })
}

Others works fine, but this function does not return the exact match of the gender.
What should I do in the function?
Comment: Try this `return $filter('filter')($scope.data, { Name: $scope.search, Country: $scope.country, MembershipType: $scope.membership, Gender: $scope.gender},true )`
Comment: hadijz, is this return the only exact match of gender?
Comment: doesnot work this time too
Answer: You can use a second parameter for using exact match. Just as in your html you can use the filter twice:
$scope.getData = function () {

    var filter = $filter('filter');

    // First filter the non-exact
    var filtered = filter($scope.data, {
        Name: $scope.search,
        Country: $scope.country,
        MembershipType: $scope.membership
    });

    // then the exact filters
    var genderFiltered = filter(filtered, {
        Gender: $scope.gender
    }, true);

    return genderFiltered;
}

Comment: OMG. Me also trying to post this same here :( . +1
Answer: Am also tried the same as @devqon answer. but can't post here for the duplicate answer, So I just changing my code like below .

Your ng-rpeate having two filters to two time filter the data. So, you should write your code like filter of filter way.

$scope.getData = function () {
        return $filter('filter')(($filter('filter')($scope.data, { Name: $scope.search,
            Country: $scope.country, MembershipType: $scope.membership }), {
            Gender: $scope.gender
            }, true);
}


Conversion from 'double' to 'System::TVarRec' is ambiguous

Question: I'm trying to compile some code in Embarcadero C++Builder using the BCC32C compiler, but I get an error:

[bcc32c Error]: conversion from 'double' to 'System::TVarRec' is ambiguous
Comment: It's very difficult to explain why code you do not include isn't working properly. See [mcve].
Answer: Ok, this was solved simply by casting
<code> VarRec v_double = (long double) 1.0;
 TVarRec v_longdbl = 1.0l;`
</code>
Comment: That is because [`TVarRec` doesn't have a constructor that accepts a `double` as input](http://docwiki.embarcadero.com/Libraries/en/System.TVarRec.Create), but it does have one for `const long double &`. But why are you using `TVarRec` at all? You are not supposed to be using `TVarRec` directly, unless you are manually manipulating the contents of a Delphi `array of const` function parameter. What are you trying to accomplish exactly?


Positive definite matrices - symmetric - diagonal elements

Question:
a) Show that the tridiagonal matrix $$A=\begin{pmatrix} 2 & 1 & \dots & 0 \\ 1 & 2 & 1 & \vdots \\ \vdots & \vdots & \ddots & \vdots \\ 0 & \ldots & 1 & 2\end{pmatrix}$$ is positive definite.  b) Show that a symmetric, positive definite matrix $A\in \mathbb{R}^{n\times n}, \ A=\{a_{k\ell}\}_{k,\ell=1}^n$ has only positive diagonal elements and that it holds that $\displaystyle{\max_{k=1,\ldots, n}| a_{kk}| = \max_{k,\ell=1,\ldots,n}| a_{k\ell}|}$.

I have done the following :
a) Let $x\in \mathbb{R}^n\setminus \{\vec{0}\}$.
\begin{align*}x^TAx&=\sum_{i,k=1}^na_{ik}x_ix_k \\ & [\text{ if } i=k : a_{ii}=2 \ , \  \text{ if } k=i-1 : a_{i(i-1)}=1 \ , \  \text{ if } k=i+1 : a_{i(i+1)}=1 ]\\ & =\sum_{i=1}^nx_i x_{i-1}+2\sum_{i=1}^n x_i^2+\sum_{i=1}^n x_ix_{i+1} \\ & =x_1 x_{0}+\sum_{i=2}^nx_i x_{i-1}+2\sum_{i=1}^n x_i^2+\sum_{i=1}^{n-1} x_ix_{i+1} +x_nx_{n+1} \\ & =\sum_{i=2}^nx_i x_{i-1}+2\sum_{i=1}^n x_i^2+\sum_{i=1}^{n-1} x_ix_{i+1} \\ & = \sum_{i=1}^{n-1}x_i x_{i+1}+2\sum_{i=1}^n x_i^2+\sum_{i=1}^{n-1} x_ix_{i+1} \\ & = 2\sum_{i=1}^{n-1}x_i x_{i+1}+2\sum_{i=1}^n x_i^2 \\ & = \left (\sum_{i=1}^{n-1} x_i^2+x_n^2\right )+2\sum_{i=1}^{n-1}x_i x_{i+1}+\left (x_1^2+\sum_{i=2}^n x_i^2\right ) \\ & = \sum_{i=1}^{n-1} x_i^2+2\sum_{i=1}^{n-1}x_i x_{i+1}+\sum_{i=2}^n x_i^2+x_1^2+x_n^2 \\ & = \sum_{i=1}^{n-1} x_i^2+2\sum_{i=1}^{n-1}x_i x_{i+1}+\sum_{i=1}^{n-1} x_{i+1}^2+x_1^2+x_n^2 \\ & = \sum_{i=1}^{n-1} \left (x_i^2+2x_i x_{i+1}+ x_{i+1}^2\right )+x_1^2+x_n^2 \\ & = \sum_{i=1}^{n-1} \left (x_i+ x_{i+1}\right )^2+x_1^2+x_n^2 \\ & >0 \end{align*}
Since it is a sum of positive (squares) terms. It is equal to zero only if all terms are equal to zero and we get this only when $\vec{x}=\vec{0}$.
Is that correct and complete?
$$$$
At b) I need some help.
We have that $A$ is symmetric, that means that $\displaystyle{a_{k\ell}=a_{\ell k}}$, or not?
We also have that $A$ is positive definite, that means that $\displaystyle{x^TAx>0 \Rightarrow \sum_{k, \ell=1}^na_{k \ell }x_kx_\ell >0}$ for $x\neq 0$, right?
How do we get that $a_{kk}>0$ ?
Do we maybe take the half sum and then the other sum is the same due to symmetric property?
$$$$
EDIT :
For b) I have done the following :
We consider that the contrary is true, i.e $\displaystyle{\max_{k,\ell=1,\ldots,n}|a_{k\ell}|=|a_{ij}|}$ with $i<j$.
Since $A$ is positive definite we have that $x^T A x >0 \quad \forall x\neq 0$.
We consider the vector $x_{ij}$ where the $i$-th entry is equal to $1$ and the $j$-th entry is equal to $-1$ and all other entries are equal to $0$, where $i,j\in \{1, \ldots , n\}$ arbitrary.
For this vector we get : \begin{align*}&x_{ij}^T A x_{ij} >0 \\ & \Rightarrow  \begin{pmatrix}0  & \ldots & 0 & 1 & 0 & \ldots & -1 & \ldots & 0\end{pmatrix}\begin{pmatrix}a_{11} & \ldots & a_{1n} \\ \ldots & \ldots & \ldots \\ a_{i1} & \ldots & a_{in} \\ \ldots & \ldots & \ldots \\ a_{j1} & \ldots & a_{jn} \\ \ldots & \ldots & \ldots  \\ a_{n1} & \ldots & a_{nn}\end{pmatrix}\begin{pmatrix}0  \\ \vdots \\ 0 \\ 1 \\ 0 \\ \vdots \\ -1 \\ \vdots \\ 0\end{pmatrix}>0 \\ & \Rightarrow  \begin{pmatrix}a_{i1}-a_{j1}  & \ldots  & a_{ii}-a_{ji} & \ldots & a_{ij}-a_{jj} & \ldots & a_{in}-a_{jn}\end{pmatrix}\begin{pmatrix}0  \\ \vdots \\ 0 \\ 1 \\ 0 \\ \vdots \\ -1 \\ \vdots \\ 0\end{pmatrix}>0 \\ & \Rightarrow (a_{ii}-a_{ji})-(a_{ij}-a_{jj})>0\\ & \Rightarrow a_{ii}-a_{ji}-a_{ij}+a_{jj}>0\end{align*}
Since $A$ is symmetric we get that $a_{ji}=a_{ij}$, and so we get \begin{equation*}a_{ii}-a_{ji}-a_{ij}+a_{jj}>0 \Rightarrow a_{ii}-a_{ij}-a_{ij}+a_{jj}>0\Rightarrow a_{ii}+a_{jj}>a_{ij}+a_{ij}\end{equation*} and in that way we get a contradiction.
Is that correct and complete?
Comment: For b), consider $x=[1\ 0\ \cdots\ 0]$, what do you find? As for a) it seems right, though I read it diagonally
Comment: For this $x$ do we get $a_{11}>0$ ? @GFrazao
Comment: Yes, and if you continue with $x = [0\ 1\ 0\ \cdots\ 0]$ and so on?
Comment: For the first question you can simply use Gershgorin circle Theorem. I guess you can use it also for the second question.
Comment: Note that $a_{kk}$ are elements of the matrix $A$, they have no relation with $x$. We chose these specific $x$'s because they tell us specific information for each $a_{kk}$, given that $x^T A x >0$ holds for any $x \neq 0$.
Comment: One possible way is to use the Gershgorin circle theorem, as mentioned by VanBaffo: https://en.wikipedia.org/wiki/Gershgorin_circle_theorem. This might be a bit of an overkill, let me think if there is a simpler way to show it.
Comment: Gerschgorin Discs tell you the matrix is PSD *but doesn't tell you it is PD*.  You need to do something like apply Taussky's refinement of G-discs, use Perron-Frobenius Theory, or directly calculate the eigenvalues of the Tri-diagonal matrix.... i.e. part (1) is basically a duplicate of https://math.stackexchange.com/questions/3903369/prove-that-this-block-matrix-is-positive-definite/  .  Part 2 comes from writing $A=B^TB$ and seeing the $(a_{i,k})^2=(\mathbf b_i^T\mathbf b_k)^2 \leq \big \Vert \mathbf b_i\big\Vert_2\cdot \Vert \mathbf b_k\big\Vert_2=a_{i,i}\cdot a_{k,k}$ by Cauchy-Schwarz
Comment: that should read $(a_{i,k})^2=(\mathbf b_i^T\mathbf b_k)^2 \leq \big \Vert \mathbf b_i\big\Vert_2^2\cdot \Vert \mathbf b_k\big\Vert_2^2=a_{i,i}\cdot a_{k,k}$ which of course is bounded above by $\max\big(a_{i,i}, a_{k,k}\big)^2$
Comment: Then we will get that $a_{kk}>0$ for all $k$, right? Can we just take this specific $x$ ? Do we not have to show that the diagonal elements are positive for all vectors $x$ ? @GFrazao
Comment: Ah ok! I got it! And what about the second question with the maximum? How do wegt that equality? @GFrazao
Comment: Can you check please the edit part of the above question? Is that correct and complete? @user8675309
Comment: Can you check please the edit part of the above question? Is that correct and complete? @VanBaffo
Answer:
Show that a (symmetric) positive definite matrix $A\in \mathbb{R}^{n\times n}$, has positive diagonal elements.

Positive definite: $x^T A x >0 \quad \forall x\neq 0$.
Consider the vector $x_k$ with $k^{\text{th}}$ entry $1$ and remaining entries $0$.
$x_k^T A x_k = a_{kk} >0 \quad { }_\blacksquare$

Show that the matrix element with maximum absolute value lies on the diagonal.

Consider the vector $x = [x_1\ x_2\ 0 \cdots 0]$.
$\begin{align}
&x^T A x = a_{11}x_1^2 + 2a_{12}x_1 x_2 + a_{22}x_2^2 >0 \\
&\Rightarrow a_{11}a_{22} > a_{12}^2 \\
&\Rightarrow \frac{a_{11}}{|a_{12}|} \frac{a_{22}}{|a_{12}|} > 1
\end{align}$
Which implies that either $a_{11}$ or $a_{22}$ must be greater than $|a_{12}|$. You can easily generalize to show that $|a_{kl}|$ is upper-bounded by either $a_{kk}$ or $a_{ll}$ for all $k,l$, which completes the proof.

Of course, as mentioned earlier, the Gershgorin circle theorem is a useful tool  to have in your linear algebra tool box.
Comment: Can you check please the edit part of the above question? Is that correct and complete?
Comment: @MaryStar your edit is in the right path, but not complete. You showed $a_{ii}+a_{jj}>2a_{ij}$, which is correct but is not equivalent to $a_{ii}+a_{jj}>|2a_{ij}|$. Imagine that $a_{ii}=a_{jj}=1$ and $a_{ij}=-2$, the equation you derive holds even though $|a_{ij}|>\text{max}(|a_{ii}|,|a_{jj}|)$.
Comment: @MaryStar Repeat the reasoning with the vector with $i$-th and $j$-th entries equal to $1$ and remaining equal to $0$. You should arrive at $a_{ii}+a_{jj}>-2a_{ij}$, combine it with the previous equation to get the absolute value.
Comment: So what is missing in my edit part to get the absolute value?
Comment: Ah ok! Thank you very much!!! :-)
Comment: Do you maybe have also an idea about my other question : https://math.stackexchange.com/questions/4578124/matrix-exchanging-elements ?


NoSQL é tão problemático quanto parece?

Question: Andei lendo sobre NoSQL nos últimos tempos, pois a primeira impressão que tive sobre a tecnologia foi boa. Fiz testes com MongoDB especificamente e achei muito prático e bem mais fácil do que bancos de dados relacionais. Também tive a impressão de que esse tipo de banco de dados é mais compatível com a orientação à objetos e por isso fiquei bastante interessado no assunto.
Acontece que lendo comecei a ver muitas opiniões negativas a respeito dessa tecnologia. Ouvi falar sobre o teorema CAP que implicaria que um banco de dados NoSQL ou não terá disponibilidade ou não terá consistência. Isso é uma coisa muito preocupamente, porque até hoje não encontrei casos em que é possível abrir mão de uma dessas coisas.
Na realidade, construir um sistema que pode vir a não ter os dados disponíveis ou não ter garantia de que os dados exibidos estão corretos me parece uma coisa extremamente problemática. Vi até um programador falando já que esse tipo de tecnologia provavelmente não vai ser muito usada, sendo que os bancos relacionais continuam sendo mais indicados.
Se por um lado tem tudo isso, por outro lado senti muito mais facilidade e naturalidade ao usar o NoSQL. Dessa forma, gostaria de saber: o NoSQL é tão problemático assim como parece? Não há nenhuma forma de contornar esses problemas? Ou o NoSQL realmente só tem alguns poucos usos nos quais os dados podem nem sempre ser corretos ou nem sempre disponíveis?
Comment: Lembre que o NoSQL não se aplica a qualquer caso e me parece que ele realmente abre mão de certos aspectos para favorecer outros justamente para contemplar aplicações como as Redes Socias, a SQL Magazine publicou um bom artigo recentemente sobre isto.
Answer: Primeiro eu te pergunto: você fez operações complexas como NoSQL? Você mediu adequadamente a performance em todas as situações?
Ferramenta certa

Existe uma expressão popular que todo mundo conhece: "Se a única ferramenta que você conhece é um martelo, todos os problemas parecem pregos".
Não, esta expressão não cabe aqui, mas ela é adotada por muitos. Deveria ser conhecida outra que cabe nesta situação: "Quando você tem um canivete suíço, vai querer brincar com todas as ferramentas".
NoSQL é uma tecnologia interessante e tem sua serventia. Certamente é uma das ferramentas do canivete suíço que temos disponíveis. Mas ele não é uma faca, uma chave de fenda ou um saca-rolhas.
NoSQL é aquela ferramenta obscura que quase ninguém sabe para que serve (mesmo a maioria que usa). Mas mesmo assim as pessoas tentam usar, afinal se está lá, eu devo ser obrigado a usar, certo? Se tem outras pessoas usando deve ser bom.
Confusão de conceitos
NoSQL é um nome que engloba várias tecnologias bem diferentes com uma característica em comum. Saber escolher a tecnologia mais adequada é importante também.
Só para citar as principais variantes:

pares de chave e valor;
colunares;
baseado em documento;
grafos.

Mesmo essas possuem subtipos. Tamanha são as variações que dificilmente vai encontrar duas tecnologias com as mesmas características.
Outros já deram algumas dicas que o assunto é mais complexo e você verá explicações erradas por todo lado.
Durabilidade
Você fala em falta de disponibilidade. Eu vou imaginar que você está falando em falta de durabilidade, porque disponibilidade é uma das coisas que o NoSQL facilita.
Durabilidade é a propriedade da informação se manter permanente após sua execução. Em geral isso é obtido através da gravação em memória de massa (disco por exemplo).
Disponibilidade é a propriedade onde o banco de dados está respondendo às queries sempre que for requisitado. Não quer dizer que não haverá resposta, mas pode não acontecer agora.
De fato algumas implementações não facilitam a durabilidade, ou pelo menos não tem isso como prioridade. Mas é possível ter todos os dados duráveis de uma forma ou de outra.
Consistência eventual
Tecnologias NoSQL costumam ser ótimas para obter escalabilidade.
Já a consistência é problemática mesmo. NoSQL basicamente aceita a tese da consistência eventual. Ou seja, em algum momento o banco de dados estará consistente. Inclusive em algum momento não definido estará durável, ou disponível.
Nem todos os problemas exigem que a consistência seja absoluta.
Então NoSQL troca uma capacidade por outra.
Facilidade de uso
Esse não é o melhor motivo para escolher uma ferramenta, principalmente quando essa facilidade não é absoluta. Você precisa de anestesia geral para simplesmente quebrar o osso do nariz mas pode se manter consciente quando abre o cérebro. É contra intuitivo, mas é assim que funciona.
Onde usar?
Se você é o Facebook, como vai tratar bilhões de transações por dia em um banco de dados?
Com NoSQL! Se você é o Facebook você precisa de uma tecnologia assim. E se você é o Facebook, não precisará de consistência absoluta na maior parte dos casos. E nos casos que precisa, vai criar uma aplicação que lidará com isso. Essa aplicação será complexa, mas é a única forma de fazer.
No Facebook também não precisa de características relacionais do banco de dados. Parte disso é pela característica própria da aplicação. Mas também ajudada pela forma como ela é desenvolvida. Quando eles pensam em adicionar algum recurso do software que se aproxime da característica relacional, ou se muda a forma de desenvolver o software, recusa-se a funcionalidade.
Já vi muitos "especialistas" em banco de dados reclamar da falta de um recurso no Facebook ou no Gmail. Segundo eles, seria um recurso trivial de implementar. Seria... em um banco de dados relacional.
Ninguém vai morrer ou ter prejuízo se demorar um pouco para receber um notificação de um amigo, se o número de likes não for 100% preciso no exato momento que está olhando. Os mais maldosos (ou realistas?) dirão que mesmo erros grotescos permanentes nesse site também não farão diferença alguma na vida de alguém :)
Então se você não é o Facebook (claro que é apenas um exemplo), não se preocupe tanto com NoSQL. Quem disser que NoSQL não é nicho provavelmente estará se comportando como fanboy. Dá até para discordar do tamanho do nicho, mas não é uma solução para tudo.
Por default você deve usar um banco de dados relacional. A maioria dos problemas reais onde banco de dados são usados se encaixa neste paradigma ou muito bem ou pelo menos de forma minimamente adequada. A maioria dos problemas possuem dados tabulares relacionados.
Uma cirurgia que cura uma doença rara no cérebro chama muita atenção, mas a maioria das pessoas precisam apenas tirar o apêndice. O que está na mídia não é o que todo mundo precisa é só o que chama atenção.
Assunto do momento
Você ouve falar muito porque a mídia é assim, sempre tem o assunto da moda. Os profissionais mais qualificados costumam escrever muito na internet. Tecnologias de ponta (que quase sempre só são usadas em casos muitos específicos) ficam em evidência mais que as tecnologias maduras. Quando surgir outro assunto mais relevante, todo mundo falará dele e o NoSQL só vai ser falado quando for relevante. Tem até outros motivos para o assunto ter tanta repercussão, mas não cabe aqui.
Agora a moda é microsserviço que é uma extensão do NoSQL. Nessa metodologia NoSQL faz muito sentido, mas um relacional simples como o SQLite também faz (tem outros exemplos), em alguns casos. Microsserviço guarda semelhança com NoSQL nas dificuldades. Para conseguir uma característica complica todo o resto.
Vida longa aos relacionais
Diversas tentativas de novos paradigmas de banco de dados tentaram desbancar a hegemonia do relacional e não conseguiram. Mas quase todos sobreviveram em nichos, alguns tiveram bastante destaque. O problema é quando você tenta usar para algo além do que ele foi feito.
O maior abuso é o modelo de documento. As pessoas acham que podem trocar tabelas por documentos. Esse modelo foi feito quando realmente tem documentos e não dados relacionados. A maioria dos problemas não são documentos, as pessoas tentam mudar o problema pra se encaixar nessa forma.
Bancos de dados relacionais são bem conceituados, atendem os requisitos do que é feito, talvez, em 99,9% das "aplicações do mundo real", e tem uma quantidade imensa de profissionais que dominam seu uso. Alguém deve pensar nele antes de qualquer outra alternativa. Primeiro pense na faca, ou quem sabe na chave de fenda. Se elas não resolvem o problema de forma adequada, aí você pensará em outra ferramenta.
Não estou dizendo que você não deve estudar novos paradigmas de banco de dados. Se não estudar não saberá quando usá-los. Assim como ocorre com linguagens, saber maneiras diferentes de resolver um problema não só ajuda saber quando usar uma ferramenta diferente, mas também saber como resolver o problema de um jeito diferente com a mesma ferramenta.
O problema é que a maioria aprende errado.
E de fato quase todos os bancos de dados relacionais relevantes estão criando formas diferentes de resolver certos problemas que são mais adequados a um NoSQL. Mais um motivo para não abandonar os relacionais. 10 anos depois alguns relacionais são capazes de lidar bem com todos os problemas, só não são muito pequenos. Outros são pequenos mas lidam só mais ou menos com esse tipo de problema.
Depois de ver muita gente trabalhando com isso vejo que usam do jeito errado. Fazem tudo simples demais e só funciona porque não precisava daquilo. Quando precisam fica tudo complicado demais ou então não funciona direito. Como em geral não era necessário esses problemas aparecem pouco.
Note que uma tecnologia não exclui a outra. O próprio Stack Exchange usa ambas. E ele tem as vantagens de cada. Mas no começo só usava SQL. E quando mudou, ninguém notou a diferença. Então é apenas um detalhe de implementação. A mudança foi relativamente simples.
Só não ache que o sistema financeiro de uma empresa vai ter o mesmo benefício. Pode até ter malefício. Já vi fazerem isso, mas o problema que dá não compensa.
Ainda temos uma imensidão de problemas que exigem relações complexas. Por que evitar um banco de dados relacional? Tenho visto desastres onde o relacional é o adequado mas a pessoa optou por NoSQL (ou NoRel que é o que essa tecnologia realmente é).
Na verdade o nome correto desse tipo de tecnologia devia ser NoConsistency porque é isso que realmente não tem. Cada vez mais elas estão usando relações e até SQL.
Em alguns casos para conseguir consistência abre-se mão da disponibilidade.
Como a maioria das vezes quer a consistência e a disponibilidade deve-se evitar o particionamento. Tudo isso faz parte do CAP theorem. Você acha que não, mas funciona.
Este site é um dos 30 sites mais acessados do mundo e tem consistência, e disponibilidade, não tem particionamento. E atende bem sem sobressaltos. Você acha que precisa mais que isso?
O Stack Overflow (em inglês, o grandão) pode rodar em um servidor se quiser.
O tráfego do SO no Brasil é semelhante a um dos maiores e mais conhecidos sites brasileiros que tem um padrão de acesso muito parecido. Uma página descritiva que todo leem muito, e muito eventualmente alguém comenta algo ou mais eventualmente faz alguma operação de escrita, e esse site precisa de milhares de servidores, justamente porque adotou ferramentas erradas. E precisa de bem mais gente em TI para lidar com tudo, principalmente de desenvolvimento. Muitas dessas modas são vendidas como facilitadores, é insano.
Conclusão
A melhor forma de aprender tudo isso é fazer um estudo sério, aprofundado e consistente sobre os assuntos. No processo pode até descobrir que não sabia muita coisa sobre banco de dados relacional (eu vi muito fã de NoSQL - pessoas que são referência - que não sabia usar relacional direito e tomou a decisão por causa disso). Caso não possa conduzir esses estudos adequadamente terá que confiar em pessoas aleatórias dizendo o que é bom para você. :P
Se você precisa de consistência absoluta, sim, ele é problemático, apesar de não ser inviável. O problema é que aí estará usando a ferramenta errada, terá muito trabalho para conseguir o que é "fácil" com outra ferramenta.
A grande pergunta que deve ser feita: por que "diabos" alguém escolhe usar NoSQL quando ele precisa de consistência absoluta? O mesmo vale pra disponibilidade que dá para conseguir um ou outro, ou ambos se abrir mão do particionamento, que é o motivo do NoSQL ter sido criado.
Coloquei no GitHub para referência futura.
Answer: O Teorema CAP (Consistency/Availability/Partition tolerance) se refere a integridade destes três items em um sistema distribuído, e não se refere particularmente a sistemas SQL ou NoSQL. O que importa no teorema é a questão do sistema distribuído e a impossibilidade de garantir estes 3 itens simultaneamente em tais sistemas.
Dito isto, sistemas distribuídos SQL tem suas características, assim como os NoSQL, cada um vai pender por priorizar uma das 3 características do teorema. Então a meu ver vale ponderar qual destas é prioridade (na aplicação) para a escolha do tipo de sistema, pois garantia dos 3 itens é o que o teorema diz que não haverá, seja SQL ou NoSQL.

Consistency models in nonrelational DBS
CAP Theorem, Eventual Consistency, NoSQL
Answer: Primeiro de tudo basta entender uma coisa, em qualquer situação, em qualquer ocasião, em qualquer ponto da história da humanidade, sempre houve e haverá pessoas contra e a favor de mudanças.
Muitas tecnologias que diziam não ter futuro, por muitas vezes não tiveram futuro. Outras que diziam não ter futuro, acabaram se tornando o grande carro chefe de muitas empresas, tudo porque houve nesses momentos PARADIGMAS que foram desafiados. Nos casos de sucessos, foram vencidos e estabelecidos novos em seus lugares.
O NoSQL é uma tecnologia, um conceito, um novo paradigma ainda não tão bem visto, como muitos gostariam que fosse. Porém, isso não o torna menos eficaz que um velho paradigma como os Bancos de Dados Relacionais.
Muitos dos que comentam negativamente a respeito do NoSQL o fazem por estarem em uma zona de conforto dentro da tecnologia e muitas vezes não a estuda tããão a fundo para descobrir todo o  potencial por trás dela.
A questão de funcionalidade só pode ser respondida por um aprofundamento bem detalhado de sua necessidade, de uma pesquisa relacionada a alternativas para concepções e pelo velho fato da tentativa e acerto.
Ninguém vai acertar na primeira tentativa sempre, sempre terão erros no meio do caminho, mas que serão como bases para novos aprendizados e evitar cometer os erros passados.
Passado ao primeiro momento de explicar o medo ou a incerteza que muitos tem a tentar coisas novas, vamos responder as perguntas:

o NoSQL é tão problemático assim como parece?

"Os problemas da vida são do tamanho que a gente dá a eles."
Mallu Magalhães
Se você logo de cara criar esse bloqueio de que o NoSQL é TÃO problemático assim, para você, mesmo depois de algum tempo de estudo, ele será sim, tão problemático. Mas se tiver vontade de estudá-lo a fundo, podem ser probleminhas ou ciscos no seu caminho.
Sobre NoSQL na minha opnião, não é que ele seja complicado, é que ele faz parte de uma mentalidade que não tinhamos antes a respeito de tecnologias de gerenciamento e armazenamento de nossos dados.

Não há nenhuma forma de contornar esses problemas?

Tem, sempre tem, estudo, estudo, estudo, estudo e quando sobrar um pouco de tempo, mais estudo. Lembro sempre de duas frases que me desafiam a encontrar a forma para esses problemas que parem não ter forma de contornar.
"Prefiro o impossível, lá a concorrência é menor" - Steve Jobs
e também.
_"Não sabendo que era impossível, ele foi lá e fez" - Jean Cocteau
Essas duas frases remetem a necessidade da primeira pergunta respondida e do fato das tentativas e erros para descobrir os caminhos alternativos.

Ou o NoSQL realmente só tem alguns poucos usos nos quais os dados podem nem sempre ser corretos ou nem sempre disponíveis?

Pergunte ao Facebook ou outros casos de sucesso como StudyBlue também.
Eles usam porque suas soluções precisaram de algo a mais que em algum ponto dos seus projetos, viram que o esquema relacional não se tornara mais viável.
Assim sendo, volto a afirmar o ponto de que só pode decidir algo em relação a NoSQL e Relacional depois de um estudo aprofundado no projeto que deseja impor-lhes...
Se o tudo for apenas em intuito de aprender algo novo... Vale mais a pena ainda que aprenda sim e que use em seus projetos particulares, porque não existe cliente melhor pra testar novas tecnologias do que você mesmo... Tenho certeza que esse cliente vai lhe deixar testar isso. ;)
Abraços e desculpa o "ARTIGO" que escrevi kkk.
edit: links para estudo
Introdução no SS
Oracle NoSQL Overview and Practice
No-SQL Database
Mongo-DB achei bem interessante, bem direto ao ponto
Mongo Documentation
NoSQL Data Modeling
NoSQL relationship
Livro indispensável: NoSQL Essencial
Answer: Já existem cases de sistemas enormes e bem complexos construídos em cima de bases NOSQL. Creio que tais cases impedem qualquer um de dizer coisas como "NoSQL realmente só tem alguns poucos usos nos quais os dados podem nem sempre ser corretos ou nem sempre disponíveis". Certamente há formas de contornar. Só pra citar um exemplo, com Mongo DB, você pode "reinventar a roda" para tentar ter 2PC (Two Phase Commit - http://cookbook.mongodb.org/patterns/perform-two-phase-commits/), enfim dá pra forçar a barra e ter soluções para outros tipos de limitações. A questão é: será que realmente vale a pena? Se você precisa tanto disso, não era melhor usar logo um RDBMS?
Answer: A questão não é ser problemático, mas sim que a finalidade dele é outra e não substitui o relacional.
Sou dba, conheço os 2 principais rdbms do mercado e um nosql de um grande fornecedor o qual já trabalhei para ele.
Não defendo nenhum deles, nem fabricante, nem tecnologia.(nem vou fazer propaganda de graça)
Como rapaz já escreveu ali em cima, são para propósitos diferentes e noSQl nunca substituirá relacional. Apesar da modinha noSQL em que muitas empresas querem usar sem conhecer a fundo sua finalidade, ele pode ser bem usado para ganhar escalabilidade, tempo de resposta em grandes massas, desde que você possa abrir mão de algumas coisas importantes como consistência, etc.
Pois então, ele é problemático? Não! Para alguns fins é rápido e bom!
Quer garantias dos seus dados e que seu SGBD seja rápido, um bom dba do maior fabricante sabe que existem hardware, software apartados, options que podem transformar ele em um canhão, inclusive em grandes massas de dados no modelo relacional. Só que não é barato.
A decisão de construir um sistema passa por muitas questões, uma das mais importantes é a conta que vai dar alguns milhões de dólares... Tirando tudo isso cada produto tem seu lugar, no relacional este lugar é bem maior.
E eles continuarão como estão por um bom tempo...
Comment: Robie bem-vindo ao Stackoverflow em Português! Tente não ser tão agressivo nas suas respostas, afinal aqui ninguém é melhor que ninguém. Estamos aqui todos para ajudar a comunidade de programadores que falam português. Podemos todos ajudar sem insultar e sem agressividade. Continue participando.

NoSQL é tão problemático quanto parece?


How do I customize the credentials check in the Grails Spring Security Core plugin?

Question: I'm currently creating a new application that requires users to login. I want to use the Spring Security Core plugin for this, but the only problem is that the credentials of the users are stored in a centralized system, and not locally in the database. This system can only be accessed by an API, and will tell me whether the credentials are correct or not.
Is there any way to override the credentials check of the Spring Security Code plugin, so I can check the credentials myself? Or in case this is not possible, is there any other workaround?
Answer: It belongs on what your system looks like.
You can write your own Authentication Provider.
Here is answer.
You can create your own User class with datasource set on your centralized system database.
Or you can use Spring Security CAS Plugin


Filter under condition based on value checkbox of current user profile

Question: I use Views 3.x and Views PHP module.
The task. Make Views filtering criteria that would make two different actions, depending on status of checkbox (TRUE or FALSE) of current user's profile.
Description. Logic diagram:
IF checkbox current user == TRUE
THEN display taxonomy terms, tid == New
ELSE display taxonomy terms, tid == array('New', 'Archive', 'Old', ...) // 50+ taxonomy terms

Please help me.
Comment: Can you display all those 50+ taxonomy terms in a View? If so, you can create a template file for that View and easily convert your logic diagram to code there.
Comment: Example code please, if you can.
Comment: I can, but you have to provide some more information in your question. What are those taxonomy terms? Can you already display them in a View?
Comment: This 50+ terms — it's only example. In real project I have only 3 terms (New, Arhive, Old).
Comment: Question is "Can you already display them in a View"? Answer: yes.
Comment: Maybe there's a Views sub-module that would replace stantard operator "AND" ("OR") in the filtering criteria for this: "IF", "THEN", "ELSE"?
Answer: As you can already display the taxonomy terms from the ELSE part of your logic diagram in a View, it is quite easy to achieve what you want with a template file for your View. Find the suitable template here and adapt the code underneath, where I assume that you use views-view-field--YOUR_VIEW-YOUR_BOULEAN_FIELD.tpl.php:
global $user;
if ($user->field_YOUR_BOULEAN_FIELD['und'][0]['value'] == 1) {
  $output = taxonomy_term_load($tid)->name;
}

The variable $tid for taxonomy_term_load() should be the tid of your taxonomy term New.
Comment: Thx. Is it possible to do it in Views PHP field?
Comment: Yes, I think it would be possible to rewrite the output of the Views field with a PHP snippet, but that isn't possible with Views alone. You'll need the Views PHP module for that. But personally I wouldn't install a new module to rewrite only 1 field.


Monotone convergence theorem for sets?

Question: Let $M = \bigcup\limits_{n=1}^\infty M_n$, $M_n$ be a measurable sets on $\mathbb R$ and $f$ be a measurable function on $\mathbb R$. Then I want to know how the equality
$$
\lim\limits_{N\to \infty}\int_{M\setminus \bigcup\limits_{n=1}^NM_n} |f(x)| \,dx = 0
$$
holds. It seems something like monotone convergence theorem, but I know the monotone convergence theorem is for the monotone "functions".
How can I justify this?
Comment: $\int|f|<\infty$ is required. See my comment answering LeGrandDODOM.
Answer: The map $\nu:A\mapsto \int_A |f|$ is a measure.
Note that $A_N:=M\setminus \bigcup_{n=1}^NM_n$ is a decreasing sequence that converges to $\emptyset$.
Assuming $\int |f|<\infty$, we have $\lim_N\nu(A_N)=\nu(\emptyset)=0$.
Answer: Hint: use characteristic functions to write each integral as an integral on $M$.
Comment: Can you solve it without the assumption $\int |f|<\infty$ ? It seems to me the sequence of functions at hand is decreasing, so some domination is needed...
Comment: @LeGrandDODOM, without the assumption is obviously false. Take $f=1$, $M_n=[-n,n]$.

Monotone convergence theorem for sets?


What does it mean to write a song in a certain key?

Question: I have been searching for a while to try to correctly understand this.
What exactly does it mean if for example a song is written in C Major? Does it mean the song's notes cannot contain any sharps or flats? Does it mean the song can only have chords from ABCDEFG but use the major chords of those scales which could mean sharps and flats?
Any explanation on it would be really helpful.
Thanks
Comment: If I'm reading music, it helps to know what key a song is in so I can play without glancing at the key signature on the left almost constantly. (I'm a very slow reader. I rarely read music. I only learned to read it because I played trombone in an orchestra when I was a teenager). To _write_ music in a certain key, I can't answer, the key I write a song in is purely accidental (no pun intended!).
Answer: To understand the answer to this question you need and understanding of these concepts:

Key center
Tonality
Chord progressions in functional harmony
Cadence

A song is regarded as being in the key of C major if the pitch C is its key center, if the notes in the song chiefly fall in the C-major scale (as opposed to the C-minor scale, or one of the other scale-modes based on C), and the chord triad of C major serves the function of the tonic chord throughout the chord progressions in the song.
There are exceptions to everything. A song would generally be regarded as being in the key of C major if it started out in C major, even if it ended in another key. Some songs stay in the same key all the way through, and some songs change keys. Or it could start in C major but incorporate chords borrowed from other keys, use melody notes outside of the notes in the C major scale, or it could leave the key of C major entirely at one point, only to return to C major before it ends.
Comment: @bobobobo: The [aswer by slim](http://music.stackexchange.com/a/6490/249) includes a list of 5 good reasons for choosing a particular key for a song.
Comment: So what is the advantage of even saying a song is in a particular _key_?
Comment: bobobobo, I don't know about an "advantage", but the point of selecting a key for a piece of music is so that you can tell the band how you want them to pitch the song.
Comment: @bobobobo See the last paragraph of my answer below for one such advantage.
Comment: You don't actually describe what a "key center" is...
Answer: Both the existing answers are good. I want to add that depending on your definition of "song", it may not even have a defined key.
If you sing Yankee Doodle and you start on a 'C', you're singing it in C major.
If you sing Yankee Doodle and you start on a 'F', you're singing it in F major.
The song doesn't have a key; your performance of it does.
(Note: not all tunes begin with the root note of the key they are in. If you play the melody from Morning from Grieg's Peer Gynt, and you start on a 'G', you are playing it in C major. If you play that tune and you start with a 'C' you are playing it in F major.)
When you perform a song, you necessarily pick a key, the moment you play the first note.
When you write down a song, in most notations, you necessarily pick a key, because the notation requires that you write down absolute notes. Exceptions to this include Nashville numbers and Relative Sol-Fa
Reasons for picking a particular key include:

the range of the singer or instruments
faithfulness to a particular performance/recording
ease of playing (e.g. D major or G major for beginner guitarists)
bringing out particular timbres on some instrument
bringing out particular subtle rhythmic inflections on some instrument

Often there are compromises to be made. For example, you are singing and accompanying yourself on guitar. You think your C major chord on the guitar sounds particularly nice. But that means you have to play a Bb major later in the song, and you always mess those up, so you play in D instead -- but in D you find your voice strains to reach the lower notes, so you try playing in E instead. The more voices and instruments are involved, the more complicated this gets.
Comment: I'll add to the reasons: particular notes/keys have their own feel separate from the timbre of an instrument.  To me, at least, certain songs sound better in particular keys regardless of the instrument being used.  And I particularly enjoy E (both minor and major) and I'm not sure why ;)
Answer: Simply put, a song in the key of C Major will mostly contain notes from the C Major scale.

It can contain sharps and flats.
It can change keys in between.
There can be other anomalies.

Music is a hearing art.  When we write down the music, we base it on a set of rules/traditions/formats.  For example, the same note that we play on the piano can be called a G♯ or an A♭ on paper: it's just based on convention.
Having these conventions makes it easier for musicians to pick up the piece and play it.  When they see 'C Major,' they will understand where the majority of the action will take place, and how the music should sound.  Based on the notation, they'll not only be able to play any sharps and flats, but also will have a solid reference and will not have any confusion about what's going on in order to recreate the music themselves.
Answer: This answer is separate from my other one because it attempts give a more basic answer, to meet the bounty request.

What exactly does it mean if for example a song is written in C Major?
  Does it mean the song's notes cannot contain any sharps or flats?

In the most basic sense, yes, this is what it means. The melody and the chords will be constructed only from notes in C major scale -- and those are the white notes on a piano; no sharps or flats.

Does it mean the song can only have chords from ABCDEFG but use the major chords of those scales which could mean sharps and flats?

No. The chords will also only contain notes from the C major scale.
So the major and minor chords you have available are: C, Dm, Em, F, G, Am, Bm. These are the chords you get when you start on the note denoted in the chord name (C, D, ...), and play the third and fifth notes from there within the C major scale.
Now, if you see a piece that has no sharps or flats, that's not enough to tell you whether it's in C major or A minor -- since both of those are played with no sharps or flats. To decide which it is, you must work out what the tonal "centre" of the melody is. This is a matter of feel, so it's not possible give a strict definition. But it's often (but not always) the first note of the melody; even more often (but not always) the final note of the melody; and it's a note that will often end phrases within the melody.
So, if a tune has no sharps or flats, and seems to have a "home" at C, it's in C major. If it seems to have a "home" at A, it's A minor.
If its "home" seems to be a note other than A or C, then the tune is in a more obscure (in Western music) "mode"; I suggest avoiding that topic until you are comfortable with the basics.
The reason some of the other answers have been less clear, is that with more advanced pieces, things get more complex. If you sneak (for example) one Bb into a tune that's otherwise in C major, it's probably still C major. That's why we have to use words like "mostly".
Comment: By the way - A7sus4, since it contains neither C nor C#, has no indication of whether it's major or minor. To in a piece in C major, A7sus4 will feel as if it has a "missing" C. In a piece in A major, it will feel has if it has a "missing" C#.
Comment: Yes, any combination of the notes CDEFGAB is in the key of C. You can hold them all down together if you like (it doesn't mean it'll sound good).
Comment: Additional note about slim's comment on the A7sus4: This is because the 3rd is replaced with the 4th (which is the definition of sus4 chords), and since the difference between major and minor is defined within the 3rd, the distinction is removed. It is often used to add tension to a chord progression, which is resolved by landing on the non-sus4 version of the chord.
Comment: Thanks for clarifying that slim and @awe. I'll have to try it out some time in C. Also, that explains why A7sus4 sounds so damn good in E minor.
Comment: @slim: Bm has a F# (I don't mean you should put the b5 in there, but maybe omit Bm altogether). A7sus4 in A major would feel like a C# is missing, but mostly like a G# was altered to G.
Comment: Interesting answer. So does that mean you can actually use any chords that are made up solely of C major scale notes? for example, I could play an A7sus4 (A,E,G,D,E) instead of A minor, and that would still be in the key of C major?
Comment: This answer is great, and spot on for all the aspects of the question. I was thinking that something was missing in the previous answers. This answer completed it.
Answer: First, you really need to have a good understanding of what major and minor scales are. Once you know that, you can more easily understand chords. Then, you should study basic chord progressions for each key, which are based on scales. You are not necessarily limited to the sharps and flats in a given key just because you are writing in that key, but you will generally stick to them, which means you are writing music in that key. Writing in C Major does mean there are no sharps and flats, but it is possible to have sharps and flats in the music by means of accidentals. It sounds as though you would really benefit from getting a private teacher out taking some theory classes. Good luck with your endeavors.
Answer: There is a difference between "in C" and "in the key of C major".
A jazz tune in C can be ambiguous between several modes (like, say, parallel major and minor, or parallel mixolydian, dorian and natural minor, or all of these), with the common denominator being the root note of C. This root note sets the "tonality" of the music.
Similarly, blues in C does not necessarily mean major or minor. The tune could make parallel use of the minor and major pentatonic scales as well as the tritone.
The "key of C major" is somewhat more restrictive than just the tonality. It suggests that the music is probably organized around traditional concepts of harmony rooted in the European classical tradition.  (An empty key signature, by the way, does not imply the key of C major; it could be A minor, of course. If harmonic or melodic minor occurs, the F# and G# appear as incidentals.)
The key or tonality might apply to just the opening bars of the music. Music which modulates to another tonal centre is still usually identified by the starting tonality. Often, composers return the music to the original tonality, but not always.
For example, in Baroque music, the common two-part form often goes from I to V in the first part, and the second part returns from V to I. The overall piece is identified as just being in I major or minor. The excursions into other keys are not acknowledged in the basic identification.  So such and such a composer's "sonata in such and such minor key" can easily go through all twelve major and minor keys.   It's possible for a multi-part work to be identified in C major as a whole, but to have entire movements that are not in C major. An example of this is Vivaldi's "Concerto per Flautino" in C major.  (RV 443). The opening and closing movements are major (at least in their beginning and ending). The slow middle movement is in A minor.
Furthermore, a piece identified as C major could stay in C, but make small "parenthetical" modulations, such as the use of applied (a.k.a. "secondary") dominants. This is a harmonic device whereby the composer pretends that a target note or chord which is within the key is actually the tonic note of its own key. The composer then writes a cadence which resolves to that note.  The cadence could just be a V-I (where the I is not the surrounding key, but the target note), or something somewhat more extended like a II-V-I.
For example, you can definitely work an A7 chord into C major music. It can create tension which resolves to Dm.  The chord progression C A7 Dm G7 can be used as the basis of a C major song.
The A7 is just bit of "color" that is outside of the scale, but not a full-blown modulation. Identifying your music as being in the key of C major does not preclude the use of some sharps and flats which are not key changes.
Answer: I think it goes a bit stranger than a notion "of what chords you can use" and still be in a particular key, although of course that is an indicator.
Eg Brown Sugar by the Rolling Stones starts in G.
Then the main riff begins on a Cmaj .. next chord is an Ebmaj which doens't fit CMaj at all, and the sung notes are generally in line with a Cminor, yet I would say the whole song is in C major because if you try playing a Cmin chord instead of C major, it just doens't work.
I think it's more about where the song "feels" like it wants to home back to (Cadence?), and making that something that you have to work out or wait for builds the tension that is the skill in good songwriting. Brown Sugar seems to 'want' to resolve to a C Major after the context of a verse / chorus.
Some songs have an ambiguous key, such as My Woman from Tokyo (Deep Purple) - verses are in Emaj, choruses in Gmaj. Which key is it in? I don't know :-) I guess at that point you have to just go with the first played chord which is Emaj.
That's for popular rock- classical music gets more complicated but I guess the notion of a feeling of a "home key" (ie chord) still works.
Answer: I was taught in college music theory class that a key is defined by the tonic/dominant7 chord relationship. For example, C G7 in C major, or c(minor) G7 in c minor. A piece in C major might not use G7 chord, but G chord, it would still be in the key of C major, but the G7 chord could be used and still be in the key.
If a g minor chord was used in C this would indicate C mixolydian mode. If a g minor was used in c, key signature 3 flats, this would indicate that the piece was modal i.e. c aeolian. A g minor chord is within the key signature, but the 'key' of c minor uses a G7 or G major chord for the dominant chord.
Answer: If a song is in a key of C major, it cannot contain any sharps or flats, not even in the chord. As it follows in the major scales,WWHWWWH and the chords, I ii iii IV V vi vii°
(The capital letters are major, the small ones minor, and the one with the circle thing is diminished.) It means C major, D minor, E minor, F major, G major, A minor is how you play C major key.
C major and it's relatives are the easy keys to play in because you just play all the white notes.
Now, to answer your question, to write a song in a certain key (all songs have their keys) means the notes that are going to be used are the only ones the key is in. So for example, Am, a relative of C major to make it easy, all white notes are the only ones that are going to be used, however there are exemptions. If a song has key change, for example A minor to B minor, well then as soon as the key has changed then the notes has changed, too. The minors formula is WHWWHWW and if you look at that carefully at your instrument it means that B minor has C and F for its sharps. Then you have the notes the song is going to use. I recommend you study scales so music will be a lot easier. I hope this helps and I hope  my post isn't too complicated. =)


How can I get through some difficult runs in a piece otherwise at my level?

Question: I've been learning Chopin's Nocturne in E Minor, and I'm having too much trouble getting through some of the runs on page two.
Specifically, I'm an adult hobbyist, and I don't practice daily. My problem is that I don't know what volume, rate, and nature of practice will be necessary for me to be able to play this, or whether it's attainable. 20 minutes of scales a day? Sure, I can do that, if I know that within, say, 2 months, I'll be measurably better at playing these passages. I also don't know if these passages just really are too hard for me without genuinely improving my ability through many hundreds of hours of practice, and if the best strategy is to replace them with something easier.
One advantage to being a child with a disciplinarian parent is you will practice and practice and practice when you have no idea how you will possibly get better. I don't have this peculiar fearless focus as an adult hobbyist, who must, you know, enjoy it, to keep doing it. Plus, the rest of my life experiences tell me that patience is one thing, but patience must be accompanied by reasonable assurance of progress and expectation of eventual success, and that is what I am missing.
The passages are this arpeggio (actually this is more within my ability):

and these two runs:

Probably both general "theory of practice" answers and specific technical knowledge would help.
Answer: If I understand correctly, you are in essence asking, "How do I practice?" as applied to a specific piece and a specific challenge.  I looked at a couple questions that I would have expected to have more relevant answers.
Assuming that your goal is to perform this specific piece, you have already achieved a lot by determining that you are having problems with about three different spots.  So: practice them!  Don't worry about twenty-minutes-of-scales-a-day or the like in order to solve these specific problems.
For actually practicing these specific spots, isolate them, and practice them as slowly as you need in order to make them accurate.  Then, come back the next day and do it again, etc.  You are likely to retain more by playing the passages slowly and correctly for a little bit each day rather than cramming more practice into a day.
If you cannot practice daily, don't beat yourself up.  Just do what you can.  If you can get the passages "into your head," so to speak, and if no one will look at you funny, you can practice away from the instrument at times you might not otherwise be able to practice.  What I mean by "practice away from the instrument" is that you can actually "play" the passages on a desk or table when you are not at your instrument, and perhaps even when you are concentrating on other things.  The purpose is to retain the memory of how to play these passages.
Once you can play slowly and accurately, you can gradually speed up (both with and without the left hand).  If you are having trouble either with speeding up or with keeping the passages even, see my answer about "practicing in rhythms."  My answer was in response to a saxophonist's question, but the technique applies to piano as well.
As you are practicing, make sure to "back up," starting a bit earlier than the troublesome passage, to ensure that you are still able to play the difficult passage when you get to it within the broader context of the piece.  Otherwise, you may have difficulty playing the entire piece without error when you wish to do so.
Comment: Would you mind if I restructured this answer to be in a more skimmable list/bullet point form? I feel this works well for SE and quickly getting info on the fly, but this is just my opinion so I want to ask.
Comment: @djechlin Be my guest.
Answer: Try to memorize each difficult passage in a way you can "play" in your head (with your eyes closed and slowly, very slowly at the very begin) as you would playing on a keyboard, with the right fingering.
Then try to really play them (very) slowly. Finally try to speed up to a comfortable tempo.
And try to make those passages being a sort of technique study.
Of course, frequently check those passage in the context: two bars before and after, exactely as Andrew suggests.
Answer: First, I think you should practice each part in right tempo that you can play, then bring it up about for ex 10bpm and play that part. Sure it doesn't sound good, after a little practice, bring the tempo down about 5bmp. As you can see, you can play that part so clear but with more speed. Thats the way that I practice lead parts of guitar techniques. Then I will practice two parts together and ...
Good luck.
Answer: If you are having difficulty with runs, break them down into sections that you can play as chords (i.e. without changing hand position) and practice it once through as block chords and then once through as the actual run (starting from a slow tempo and working your way up.
Example: the first measure of the runs (the second part you posted) you have a run of:
A# G# A# B C# D E F# G# A#
Play G#, A# and B together (fingered as 2, 3 and 4); then B, C# and D together (1, 2, 3); then E, F#, G#, A# (1, 2, 3, 4).
In addition to what @Andrew suggested, when you are away from the piano, you can work on the rhythms, for example playing 10 32nd notes in your right hand against 3 8th notes in your left.


Handling empty request bodies for public/private key-based API

Question: I have a standard API set up in which clients are verified by hashing the request body with the private key attributed to the provided public key, and comparing it to the value of hash in the query string.
E.g., request body is "THIS IS REQUEST BODY", they would set hash as sha256('THIS IS REQUEST BODY'.PRIVATE_KEY), and then the server would do the same thing to validate it.
How can I secure this authentication process if the request body is empty? The hash would be the hashed value of the private key, and could then be re-used for similar "empty" requests by anyone listening to the traffic.

I'm assuming that the only answer will be "require content in the request body", but maybe I'm missing something obvious.
Answer: First off, don't do HASH(DATA + KEY). There are known vulnerabilities with it. This is precisely what HMAC is designed for. So your hash would be:
hash = HMAC(sha256, data, privateKey)

Now, the typical way of handling your question (how to prevent replay attacks) is by adding a randomizing factor to each request. There are a few ways to do this, but one that works well is a nonce based approach. So:
nonce = random(16)
now = time()
data = api_data + '|' + nonce + '|' + now
hash = HMAC(sha256, data, privateKey)

apiCall = data '&nonce=' + nonce + '&time=' + now + '&sig=' + hash

Then, on the receiving side, you keep track of the list of nonce's seen in the past 30 seconds. If you get one that you've seen, then reject the api call (as that would be a replay attack). If you get one that's more than 30 seconds old, reject the api call.
if (now < time() - 30) {
    return false;
} else if (nonceExists(nonce)) {
    return false;
}
addNonce(nonce);

data = api_data + '|' + nonce + '|' + now
myhash = HMAC(sha256, data, privateKey)
if (myhash == hash) {
    return api_data;
}
return false;

And then you can purge the databases on nonce's every 30 seconds (on a cron job) or every week, doesn't really matter. Depends on how active your API is.
The key here though is that you want to keep track of the nonce's while they are valid, otherwise you'd be vulnerable to replay attacks...
Answer: Why not use timestamp with the request. That will make the messages unique. Either you have time synchronization or you could send the timestamp in in plain text with the request to verify at the server.
Comment: So just have the timestamp required as part of the request body every time? I don't think it necessarily matters if it's a timestamp, I think it could be any old variable. But timestamp does add an extra dimension to authentication, however small.


Android movement sensor help

Question: I got this code from the site http://www.clingmarks.com/?p=25, and i would like some help with it!
This code registers shaking of the phone. It only allows updates every 100 millisecs and the value of the shaking has to be over 800, SHAKE_THRESHOLD.
What I have problem with is that if the phone detects a shake, (then variable i++) I would like not to be able to reach that block of code, before a certain time has passed.
Could someone help me?
public class ShakeActivity extends Activity implements SensorListener {
    // For shake motion detection.
    private SensorManager sensorMgr;
    private long lastUpdate = -1;
    private float x, y, z;
    int i = 0;
    private float last_x, last_y, last_z;
    private static final int SHAKE_THRESHOLD = 800;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...... // other initializations
            // start motion detection
            sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
        boolean accelSupported = sensorMgr.registerListener(this,
                SensorManager.SENSOR_ACCELEROMETER,
                SensorManager.SENSOR_DELAY_GAME);

        if (!accelSupported) {
            // on accelerometer on this device
            sensorMgr.unregisterListener(this,
                    SensorManager.SENSOR_ACCELEROMETER);
        }
    }

    protected void onPause() {
        if (sensorMgr != null) {
            sensorMgr.unregisterListener(this,
                    SensorManager.SENSOR_ACCELEROMETER);
            sensorMgr = null;
        }
        super.onPause();
    }

    public void onAccuracyChanged(int arg0, int arg1) {
        // TODO Auto-generated method stub
    }

    public void onSensorChanged(int sensor, float[] values) {
        if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
            long curTime = System.currentTimeMillis();
            // only allow one update every 100ms.
            if ((curTime - lastUpdate) > 100) {
                long diffTime = (curTime - lastUpdate);
                lastUpdate = curTime;

                x = values[SensorManager.DATA_X];
                y = values[SensorManager.DATA_Y];
                z = values[SensorManager.DATA_Z];

                float speed = Math.abs(x+y+z - last_x - last_y - last_z)
                    / diffTime * 10000;
                if (speed > SHAKE_THRESHOLD) {
                    // yes, this is a shake action! Do something about it!
                    i++;
                }
                last_x = x;
                last_y = y;
                last_z = z;
            }
        }
    }
}

Answer: Set a variable for time when you register a shake, with System.currentTimeMillis(). Then when you get another shake, compare the current time with the last shake time. If it's more than the desired delay, register a new shake and update the last shake time. If not, don't do anything.
Answer: The behavior you want is known as a "holdoff". You want to set a certain variable on your Activity object:
    private long last_shake_time = 0;

and then check and update that in the code that registers a shake:
            if (speed > SHAKE_THRESHOLD) {
                // yes, this is a shake action!
                long shake_time = System.currentTimeMillis();
                if (shake_time - last_shake_time >= SHAKE_HOLDOFF_MS) {
                    i++;
                    last_shake_time = shake_time;
                }
            }

With SHAKE_HOLDOFF_MS defined just like the SHAKE_THRESHOLD constant:
    private static final long SHAKE_HOLDOFF_MS = 5000;

Android movement sensor help


What is the probability a person sees a tree by looking out of the window?

Question: I'm familiar with the basic probability rules which problems come in the form of:

What is the probability of getting a head next by tossing a coin? 0.5
What is the probability of getting a 3 if a number is chosen uniformly at random from the set {1, 2, 3, 4}? 0.25

How more complicated forms of questions are calculated? for example: what is the probability a person sees a tree by looking out of the window given there are 2 trees that could be seen from that window?
There are many things to consider:

The person's eye vision.
Time of the day (and how many light bulbs are around in case it's after sunset)
The direction at which he looks.
How tall are the trees?
Can the person pass a drug test at the given moment?
Does he have a history of delusions?

And the list goes on which may contain infinite possibilities leading to seeing / not seeing a tree. Given we don't have a frequency of people who saw a tree by looking from that very same window, how to calculate the probability with any degrees of accuracy? How confident are we given that we are 100% confident the probability of getting 3 out of {1, 2, 3, 4} is 0.25? What if we don't have anything given in which case the question is the same as the title?
Comment: *"How to calculate the probability with any degrees of accuracy?"*

There is no way to compute this because the estimates that we make to perform the computation have an undefined accuracy due to lack of knowledge.
Comment: Without a probability model for "looking out a window," whatever that might be, *this question has no meaning.* Yes, it can be interpreted *psychologically* in a colloquial or subjective sense of probability, but then it is not amenable to analysis (and is off topic here anyway).
Comment: This seems like a philosophical question about epistemology. Or is the question asking about how to do the calculation?
Comment: Fix the subjective criteria (e.g. which direction a person looks; instead assume the entire FOV such that it becomes objective and constant), then sample 10,000 windows at random and estimate the probability based on that, and use bootstrapping to estimate the sampling variance. Don't try to estimate the probability based on a laundry list of semi-plausible assumptions if an empirical avenue via experiment to directly estimate the probability is readily available.
Comment: @Jade sampling 10,000 windows is not readily available and also not with troubles relating to accuracy.
Answer:
How to calculate the probability with any degrees of accuracy??

There is no way to compute this because the estimates that we make to perform the computation have an undefined accuracy due to lack of knowledge.
The way that it is generally tackled is that we use some simplified model and apply it to the problem. But the model is wrong and we have no way to express how wrong exactly. Still, as long as the range of error is small, or smaller than the statistical variations, then the model is good enough to apply.
See also: https://en.m.wikipedia.org/wiki/All_models_are_wrong
Answer: Well that's what statistics is about, right? All those variables you mentioned are unobserved and can impact the outcome, therefore we choose to encode this uncertainty about the problem as probabilities.
If you have no data, there is no way to answer the problem especially when probabilities are interpreted as relative frequencies. If you interpret probabilities as uncertainty about the problem as Bayesians do, then you can make a statistical conclusion based on that. For example in the absence of knowledge, you might assume that $Pr(tree) = 0.5$ which serves as your prior beliefs. Then whatever data you do observe, you update these beliefs and end up with some posterior beliefs. Obviously the more data you observe the better your estimates will be.
Comment: +1 But this part is contradictory *" you have no data, there is no way to answer the problem especially when probabilities are interpreted as relative frequencies. If you interpret probabilities as uncertainty about the problem as Bayesians do, then you can make a statistical conclusion based on that."* In addition the first sentence is a bit strong. Not all statistics is about this problem.
Answer: This is what supervised learn does, particularly so-called "classification" models (most of which make probability predictions, but "classification" is all but a euphemism for predicting the probability of a discrete outcome).
Consider a deck of cards. I draw a card and ask you to guess the card without showing it to you. You have a $1/52$ probability of guessing the right card, so little less than $2\%$ chance. If I then show you that that the card is red, you've ruled out half of the cards and know that it must be a diamond or a heart. Your probability of guessing the right card increased from $1/52$ when you were complexly ignorant about the card I drew to $1/26$ when I gave you some information about the card.
In machine learning or predictive modeling, those details about the cards are called features or predictors (probability some other terms, too).
How to use the available features and synthesize new ones from existing features is the special sauce of accurate predictive models.
If your example, in the absence of much information about the viewer, you might think there is a low chance of her seeing a tree. However, if you know that she looked in the direction of a tree in the middle of the daytime when she should be able to see, perhaps you would think there is a high probability of her seeing a tree. Conversely, if you knew that she looked at night without the help of a flashlight and on an overcast night that even had a new moon (so no moonlight), you might expect there to be a particularly low probability of her seeing a tree.
How to model something like this is an open question that machine learning and predictive modeling practitioners tackle every day.
Comment: I don't agree it is example of the classification problem. You could as well calculate it directly from the data or make a guesstimate from different data sources.
Comment: I'm quite familiar with machine learning and usually predictions obtained have a confidence score. The problem is usually in this case, we don't have training data and even the kind of data needed is obscure/non-existent, in which case I'm wondering whether exists a statistical approach which perhaps results in a suboptimal answer to the question.
Comment: It could be formulated as a binary classification problem: the person sees / doesn't see the tree.
Answer: When there are that many unknowns, generally you'd say "I don't know the probability". For example, your local book-maker will not give you odds on this event with the tree, and your local insurance agent will not sell you insurance against it.
In order to produce a proabability you could take one of at least two approaches:

Get the person to look out of the window lots of times, at various angles, times of day, etc, record when they saw a tree and when they didn't, and come up with a frequency. Use this as a probability. You do not even necessarily need to know how many of the trials occured during the day, and how many at night. You don't know what factors affect whether a tree is seen or not. You just know that you've measured the event you're interested in.

Consider all the variables, make lots of measurements, define a more precise model to describe what is going on, put probability distributions on each of the parameters of your model (such as "time of day", "angle of glance"), and derive a probability for the event from what your model tells you are the times/angles/etc that produce tree-sightings.

Very loosely speaking, the former approach might be used by an office manager for a question like "what is the probability that someone in my office has COVID-19?", where you really can't do a lot of careful research and modelling, but perhaps you do have access to the self-reported results of various kinds of tests, or failing that to government estimates of COVID-19 prevalance in your population as a whole.
The scond approach might be used by "scientists"[*] for a question like "what is the probability that a person with COVID-19, on walking into a crowded supermarket, will infect at least one other person?", which is the sort of thing a committed epidemiologist might try to tackle. Doesn't necessarily mean all epidemiologists would come up with the same answer, of course, since they might make decisions about what to ignore, what to include in the model, and how to model it, which means they get to a different number.
You can't generally put a probability on, "my theory of physics/biology/shopping is completely wrong and therefore everything which follows from it is bunk", since you have neither a good model nor good observed frequency for that. It's best not to think in terms of "every conceivable event has a probability, and my task is to calculate it". Rather, the actual physical world has observed events, and any probabilistic model you make of the world generates probabilities, and any relation between the two is down to whether your model is any good or not.
The reason we're 100% confident that a uniform selection from 1-4 has probability of 0.25 of giving the number 3, is that this is a mathematical theorem following immediately from the definition. We are sure of mathematical definitions. No real-world events are even described in the sentence whose truth we are sure of: it's just a straight application of the definition of "uniform discrete probability distribution". The fact that we're 100% sure of mathematics (which itself arguably is a matter of opinion, but you say you are and I believe you) doesn't help us put a number on how sure we are of optics, or the medical theory of hallucinations, or that those trees won't blow down in the night and therefore the probability of spotting them tomorrow is very different from what it is today.
Statisticians working for insurance companies, however, might actually have quite good data on the nationwide incidence of trees blowing down in the night. The reason they could plausibly care is that if you have a tree near your house, they might want to have an opinion on whether they should instruct you to remove it, or at least charge you higher premiums on your buildings insurance than they charge for buildings far from trees. So, any particular factor is subject to study, but to produce a probability you always have to decide at some point to ignore everything you haven't studied.
[*] The same ones from the dread-inducing journalistic expression, "scientists say that...", which with high probability means that all scientific theory and common-sense nuance will be omitted from the remainder of the article.
Answer: Consider the probabilistic subject
$$
\text{prob}(H | I)
$$
i.e. "the probability that $H$, given that $I$". Here $H$ and $I$ are meaningful propositions, and $I$ must be not necessarily false.
For some such pairs $(H, I)$, we cannot evaluate the subject. e.g.
$$
\text{prob}(\text{dogs are risible} | \text{it will rain next Tuesday})
$$
Now consider your subject:
$$
\begin{align}
\text{prob}(&\text{a person sees a tree by looking out of the window} | \\ &\text{there are two trees that could be seen from that window})
\end{align}
$$
You haven't supplied enough information to calculate the probability, so your subject falls into the same category as my example involving dogs and rain. That's the end of the matter.
To make some quantitative progress, we'd have to add information that gives rise to symmetries in the situation which enable us to assign probabilities. For example, let $I$ be:

There are two trees outside.
Each time Bob glances out the window, he sees tree 1 with probability 0.3, and if he sees tree 1, he sees tree 2 with probability 0.1, and if he doesn't see tree 1, he sees tree 2 with probability 0.4.
Bob takes two glances out the window.

and let $H$ be "Bob sees tree 1 or tree 2 or both". Then we could calculate the probability.
The business of forming probabilistic subjects that are relevant yet amenable to calculation, and evaluating them, is essentially the whole subject and art of probability!
Answer:
There are many things to consider [...] And the list goes on which may contain infinite possibilities leading to seeing / not seeing a tree.

If you want to consider even extreme cases like someone being delusional, then as you noticed, there is an infinite number of possibilities, so the the answer is simple: the probability is zero. It is something divided by infinity, so it approaches zero.
The calculation is pretty useless because the question is too broad. That is why we usually simplify such questions limiting the scenarios to consider (for most use cases you probably can ignore delusions, etc). Not seeing a tree because of being blind is a different thing than because of living in the desert.