Alarm application using timer in VB.NET

Question: I am trying to get the sound to play at a specified time but no matter what I try I can't seem to get it to work :/
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

    alarmtime = My.Computer.Clock.LocalTime.Date.ToString + " " +
                ComboBox1.Text.ToString + ":" + ComboBox2.Text.ToString + ":" + My.Computer.Clock.LocalTime.Second.ToString + " " +
                My.Computer.Clock.LocalTime.TimeOfDay.ToString

    If My.Computer.Clock.LocalTime.ToString = alarmtime.ToString Then
        If RadioButton1.Checked = True Then
            My.Computer.Audio.Play(Label2.Text.ToString, AudioPlayMode.WaitToComplete)
        End If
    End If

End Sub

Comment: I just tried plugging some values into your code and got this comparison: `If "2015/12/07 14:26:09" = "2015/12/07 00:00:00 2:3:9 14:26:09.5296945" Then`. The way you're trying compare times it's working.
Comment: If I were you I would forget mucking about with timers and NuGet "Rx-WinForms" so that you can use Microsoft's Reactive Extensions. You could get rid of `Timer1_Tick` and just make your code look something like this: `Observable.Timer(DateTimeOffset.Now.AddHours(1.0)).Where(Function (x) RadioButton1.Checked = True).ObserveOn(Me).Subscribe(Sub (x) My.Computer.Audio.Play(Label2.Text.ToString, AudioPlayMode.WaitToComplete))`.
Comment: @Enigmativity http://puu.sh/lMgF0/66e3f4e19e.png this is what i am setting up
Comment: That's fine. Just don't use timers - use my code. Just it in the `RadioButton1` checked event. The `Subscribe` method returns an `IDisposable` so you can deactivate a previous timer if you user turns it off. The parameter to `Timer` is a `DateTimeOffset` which you would calculate from your drop downs. Don't try to create a `String` like you've been doing as that's a bad way to do it.
Comment: @Enigmativity I'm not sure how that code works as I am used to the very "basics" of Visual basic - No pun intended
Comment: Please fix your tags - it's clear you're not using VBA here.
Comment: @timwilliams the tags are vb.net not vba...
Comment: @bytten official - Now they are...
Answer: I'm going to suggest laying your code out differently and also making some changes to how you handle your data.
I would reccomend that you use a DateTimePicker rather than two Text boxes as this will make sure that your time variables easier to maintain later on. In the design tab, disable Timer1 for the moment and set the interval to 1000ms so that it's not firing too often to swamp your computer, but often enough that the alarm plays reasonably promptly.
In form design mode, the DateTimerPicker will show the always show the date, but at runtime, the format of the picker can be changed so that you can only select the time. This code should go in your form's load event like this
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "HH:mm"
End Sub

This code should go in your Form's variable declarations so that it's accessible to the code further down my post
Dim alarmtime As New DateTime
Dim alarmsound As String = ""
Dim currenttime As New DateTime

The timer event should only contain the code that runs each time you want to compare local time and alarm time. I've put the code to set the alarm time into the Radiobutton1 CheckChanged event. I'll get to that in a Mo.Note that when I set the currenttime variable, I've formatted it so that it is in 24hr format just like the DateTimePicker. When the alarm plays, I've set Timer1.enabled to False so that the alarm doesn't keep playing for the whole minute that currenttime matches alarmtime. The last line in this sub resets the alarm time to 00:00. This is because the code that changes alarmtime in the next sub can only add hours and minutes, not just set them to a value (a peculiarity of VB.net).
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    currenttime = DateTime.Now.ToString("HH:mm")
    If currenttime.Hour = alarmtime.Hour And currenttime.Minute = alarmtime.Minute Then
        My.Computer.Audio.Play(alarmsound, AudioPlayMode.WaitToComplete)
        Timer1.Enabled = False
        alarmtime = New DateTime
    End If
End Sub

OK. Next. The code to set alarmtime and alarmsound has been placed in here so that it will only change if if select RadioButton1. Also if you accidentally change the DateTimePicker1 while the program is running, it wont change the alarm time. Personally, I would use a checkbox rather than 2 radiobuttons to enable/disable the alarm. But that's just me. So. This code fires when the check status changes.
If the radiobutton is checked, it sets alarmtime and alarmsound and starts the timer. If it isn't checked, the timer is disabled and alarmtime is set to "00:00" for the reasons I outlined above.
Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
    If RadioButton1.Checked Then
        alarmsound = Label2.Text
        alarmtime = alarmtime.AddHours(DateTimePicker1.Value.Hour)
        alarmtime = alarmtime.AddMinutes(DateTimePicker1.Value.Minute)
        Timer1.Enabled = True
    Else
        Timer1.Enabled = False
        alarmtime = New DateTime
    End If
End Sub

Later on though,if you want to develop the idea of an alarm, you could redesign alarm time as a class called Alarm with properties like Time as DateTime, Enabled as Boolean,AlarmSound as String and possibly its own timer so that you could have multiple alarms without having to add more timers as design time. Also you could include the code to play the alarm,snooze the alarm and kill it.This way you could use it in other programs and add code later for features such as repeating alarms
Comment: Thank you! this really helped me.
Comment: No problem.  Glad to help.
Answer: If you're working with dates then I'd recommend using the DateTime class instead of just plain strings.
eg.
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

    Dim alarmTime As New DateTime()
    alarmTime = alarmTime.AddHours(Convert.ToInt32(ComboBox1.Text))
    alarmTime = alarmTime.AddMinutes(Convert.ToInt32(ComboBox2.Text))

    Dim currentTime As New DateTime()
    currentTime = currentTime.AddHours(My.Computer.Clock.LocalTime.Hour)
    currentTime = currentTime.AddMinutes(My.Computer.Clock.LocalTime.Minute)

    If currentTime.TimeOfDay = alarmTime.TimeOfDay Then
        If RadioButton1.Checked = True Then
            My.Computer.Audio.Play(Label2.Text.ToString, AudioPlayMode.WaitToComplete)
        End If
    End If

End Sub

Or better yet, just set the timer interval to the difference between alarm time and LocalTime to have it trigger at the correct time.
eg.
Add a button click event to set the alarm time in which you set the timer interval as follows:
Dim alarmTime As New DateTime()
alarmTime = alarmTime.AddHours(Convert.ToInt32(ComboBox1.Text))
alarmTime = alarmTime.AddMinutes(Convert.ToInt32(ComboBox2.Text))

Timer1.Interval = alarmTime.TimeOfDay.Subtract(My.Computer.Clock.LocalTime.TimeOfDay).TotalMilliseconds

Alarm application using timer in VB.NET


Add user to a group after the user makes a comment in that group

Question: is this possible in Drupal Commons (Drupal 7) using Rules:
If a user makes a comment on a post in a certain group, have a rule which makes the user a member of the group automatically.
Why do I want to do this? Well, the contributors block in Drupal Commons is not showing all those who comment in a group. I found that the reason for this was that the particular user is not yet listed as an active member of the group.
Thank you!
Answer: The answer is ... yes, it is possible ... and easy to do ... with Rules.
If anyone coming across this is new to Rules or needs a refresher I highly recommend Johan Falk's free screencast series. It's excellent. http://nodeone.se/en/learn-the-rules-framework
See the screenshot for how I did it, and also the exported Rule below.
<code>{ "rules_lambeth_comment_join_group" : {
"LABEL" : "lambeth comment join group",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "og", "comment" ],
"ON" : [ "comment_insert" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "og_group_ref" } }
],
"DO" : [
  { "og_subcribe_user" : {
      "user" : [ "comment:author" ],
      "group" : [ "comment:node:og-group-ref:0" ]
    }
  }
]
}
}
</code>


Find all combinations of n1 elements from vector1 and n2 elements from vector2 in R?

Question: I have two vectors and I am trying to find all unique combinations of 3 elements from vector1 and 2 elements from vector2. I have tried the following code.
V1 = combn(1:5, 3)   # 10 combinations in total
V2 = combn(6:11, 2)  # 15 combinations in total

How to combine V1 and V2 so that there are 10 * 15 = 150 combinations in total? Thanks.
Answer: The function comboGrid from RcppAlgos (I am the author) does just the trick:
library(RcppAlgos)

grid <- comboGrid(c(rep(list(1:5), 3), rep(list(6:11), 2)),
                  repetition = FALSE)

head(grid)
#>      Var1 Var2 Var3 Var4 Var5
#> [1,]    1    2    3    6    7
#> [2,]    1    2    3    6    8
#> [3,]    1    2    3    6    9
#> [4,]    1    2    3    6   10
#> [5,]    1    2    3    6   11
#> [6,]    1    2    3    7    8

tail(grid)
#>        Var1 Var2 Var3 Var4 Var5
#> [145,]    3    4    5    8    9
#> [146,]    3    4    5    8   10
#> [147,]    3    4    5    8   11
#> [148,]    3    4    5    9   10
#> [149,]    3    4    5    9   11
#> [150,]    3    4    5   10   11

It is quite efficient as well. It is written in C++ and pulls together many ideas from the excellent question: Picking unordered combinations from pools with overlap. The underlying algorithm avoids generating duplicates that would need to be filtered out.
Consider the following example where generating the Cartesian product contains more than 10 billion results:
system.time(huge <- comboGrid(c(rep(list(1:20), 5), rep(list(21:35), 3)),
                              repetition = FALSE))
#>    user  system elapsed
#>   0.990   0.087   1.077

dim(huge)
#> [1] 7054320       8

Answer: You can try expand.grid along with asplit, e.g.,
expand.grid(asplit(V1,2), asplit(V2,2))

or
with(
  expand.grid(asplit(V1, 2), asplit(V2, 2)),
  t(mapply(c, Var1, Var2))
)

Comment: @YangYang Try the second option.
Comment: Hi Thomasls, this solution is very efficient, however, the final product is a dataframe that includes 150 rows and 2 columns. Is it possible to split the 2 columns into 5 columns as there are 5 elements in each row? Thank you.
Answer: You can use expand.grid():
g <- expand.grid(seq_len(ncol(V1)), seq_len(ncol(V2)))
V3 <- rbind(V1[, g[, 1]], V2[, g[, 2]])

The result is in a similar format as V1 and V2, i.e. a 5 × 150 matrix (here printed transposed):
head(t(V3))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    6    7
# [2,]    1    2    4    6    7
# [3,]    1    2    5    6    7
# [4,]    1    3    4    6    7
# [5,]    1    3    5    6    7
# [6,]    1    4    5    6    7

dim(unique(t(V3)))
# [1] 150   5

And a generalized approach that can handle more than two initial matrices of combinations, stored in a list V:
V <- list(V1, V2)
g <- do.call(expand.grid, lapply(V, \(x) seq_len(ncol(x))))
V.comb <- do.call(rbind, mapply('[', V, T, g))

identical(V.comb, V3)
[1] TRUE

Answer: After some helpful refactoring guidance from @onyambu, here is a shorter solution based on base::merge():
merge(t(combn(1:5, 3)),t(combn(6:11, 2)),by.x=NULL,by.y = NULL)

...and the first 20 rows of output:
> merge(t(combn(1:5, 3)),t(combn(6:11, 2)),by.x=NULL,by.y = NULL)
    V1.x V2.x V3 V1.y V2.y
1      1    2  3    6    7
2      1    2  4    6    7
3      1    2  5    6    7
4      1    3  4    6    7
5      1    3  5    6    7
6      1    4  5    6    7
7      2    3  4    6    7
8      2    3  5    6    7
9      2    4  5    6    7
10     3    4  5    6    7
11     1    2  3    6    8
12     1    2  4    6    8
13     1    2  5    6    8
14     1    3  4    6    8
15     1    3  5    6    8
16     1    4  5    6    8
17     2    3  4    6    8
18     2    3  5    6    8
19     2    4  5    6    8
20     3    4  5    6    8

original solution
A base R solution to create a Cartesian product with merge() looks like this:
df1 <- data.frame(t(combn(1:5, 3)))
df2 <- data.frame(t(combn(6:11, 2)))
colnames(df2) <- paste("y",1:2,sep=""))

merge(df1,df2,by.x=NULL,by.y = NULL)

...and the first 25 rows of output:
> merge(df1,df2,by.x=NULL,by.y = NULL)
    X1 X2 X3 y1 y2
1    1  2  3  6  7
2    1  2  4  6  7
3    1  2  5  6  7
4    1  3  4  6  7
5    1  3  5  6  7
6    1  4  5  6  7
7    2  3  4  6  7
8    2  3  5  6  7
9    2  4  5  6  7
10   3  4  5  6  7
11   1  2  3  6  8
12   1  2  4  6  8
13   1  2  5  6  8
14   1  3  4  6  8
15   1  3  5  6  8
16   1  4  5  6  8
17   2  3  4  6  8
18   2  3  5  6  8
19   2  4  5  6  8
20   3  4  5  6  8
21   1  2  3  6  9
22   1  2  4  6  9
23   1  2  5  6  9
24   1  3  4  6  9
25   1  3  5  6  9

Comment: this is a good solution, make it better: No need of the `df1` `df2`. Just do `merge(t(V1), t(V2), by=NULL)`
Answer: Similar idea, using apply
apply(expand.grid(seq(ncol(V1)), seq(ncol(V2))), 1, function(i) {
  c(V1[,i[1]], V2[,i[2]])})
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#> [1,]    1    1    1    1    1    1    2    2    2     3     1     1     1     1
#> [2,]    2    2    2    3    3    4    3    3    4     4     2     2     2     3
#> [3,]    3    4    5    4    5    5    4    5    5     5     3     4     5     4
#> [4,]    6    6    6    6    6    6    6    6    6     6     6     6     6     6
#> [5,]    7    7    7    7    7    7    7    7    7     7     8     8     8     8
#>      [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26]
#> [1,]     1     1     2     2     2     3     1     1     1     1     1     1
#> [2,]     3     4     3     3     4     4     2     2     2     3     3     4
#> [3,]     5     5     4     5     5     5     3     4     5     4     5     5
#> [4,]     6     6     6     6     6     6     6     6     6     6     6     6
#> [5,]     8     8     8     8     8     8     9     9     9     9     9     9
#>      [,27] [,28] [,29] [,30] [,31] [,32] [,33] [,34] [,35] [,36] [,37] [,38]
#> [1,]     2     2     2     3     1     1     1     1     1     1     2     2
#> [2,]     3     3     4     4     2     2     2     3     3     4     3     3
#> [3,]     4     5     5     5     3     4     5     4     5     5     4     5
#> [4,]     6     6     6     6     6     6     6     6     6     6     6     6
#> [5,]     9     9     9     9    10    10    10    10    10    10    10    10
#>      [,39] [,40] [,41] [,42] [,43] [,44] [,45] [,46] [,47] [,48] [,49] [,50]
#> [1,]     2     3     1     1     1     1     1     1     2     2     2     3
#> [2,]     4     4     2     2     2     3     3     4     3     3     4     4
#> [3,]     5     5     3     4     5     4     5     5     4     5     5     5
#> [4,]     6     6     6     6     6     6     6     6     6     6     6     6
#> [5,]    10    10    11    11    11    11    11    11    11    11    11    11
#>      [,51] [,52] [,53] [,54] [,55] [,56] [,57] [,58] [,59] [,60] [,61] [,62]
#> [1,]     1     1     1     1     1     1     2     2     2     3     1     1
#> [2,]     2     2     2     3     3     4     3     3     4     4     2     2
#> [3,]     3     4     5     4     5     5     4     5     5     5     3     4
#> [4,]     7     7     7     7     7     7     7     7     7     7     7     7
#> [5,]     8     8     8     8     8     8     8     8     8     8     9     9
#>      [,63] [,64] [,65] [,66] [,67] [,68] [,69] [,70] [,71] [,72] [,73] [,74]
#> [1,]     1     1     1     1     2     2     2     3     1     1     1     1
#> [2,]     2     3     3     4     3     3     4     4     2     2     2     3
#> [3,]     5     4     5     5     4     5     5     5     3     4     5     4
#> [4,]     7     7     7     7     7     7     7     7     7     7     7     7
#> [5,]     9     9     9     9     9     9     9     9    10    10    10    10
#>      [,75] [,76] [,77] [,78] [,79] [,80] [,81] [,82] [,83] [,84] [,85] [,86]
#> [1,]     1     1     2     2     2     3     1     1     1     1     1     1
#> [2,]     3     4     3     3     4     4     2     2     2     3     3     4
#> [3,]     5     5     4     5     5     5     3     4     5     4     5     5
#> [4,]     7     7     7     7     7     7     7     7     7     7     7     7
#> [5,]    10    10    10    10    10    10    11    11    11    11    11    11
#>      [,87] [,88] [,89] [,90] [,91] [,92] [,93] [,94] [,95] [,96] [,97] [,98]
#> [1,]     2     2     2     3     1     1     1     1     1     1     2     2
#> [2,]     3     3     4     4     2     2     2     3     3     4     3     3
#> [3,]     4     5     5     5     3     4     5     4     5     5     4     5
#> [4,]     7     7     7     7     8     8     8     8     8     8     8     8
#> [5,]    11    11    11    11     9     9     9     9     9     9     9     9
#>      [,99] [,100] [,101] [,102] [,103] [,104] [,105] [,106] [,107] [,108]
#> [1,]     2      3      1      1      1      1      1      1      2      2
#> [2,]     4      4      2      2      2      3      3      4      3      3
#> [3,]     5      5      3      4      5      4      5      5      4      5
#> [4,]     8      8      8      8      8      8      8      8      8      8
#> [5,]     9      9     10     10     10     10     10     10     10     10
#>      [,109] [,110] [,111] [,112] [,113] [,114] [,115] [,116] [,117] [,118]
#> [1,]      2      3      1      1      1      1      1      1      2      2
#> [2,]      4      4      2      2      2      3      3      4      3      3
#> [3,]      5      5      3      4      5      4      5      5      4      5
#> [4,]      8      8      8      8      8      8      8      8      8      8
#> [5,]     10     10     11     11     11     11     11     11     11     11
#>      [,119] [,120] [,121] [,122] [,123] [,124] [,125] [,126] [,127] [,128]
#> [1,]      2      3      1      1      1      1      1      1      2      2
#> [2,]      4      4      2      2      2      3      3      4      3      3
#> [3,]      5      5      3      4      5      4      5      5      4      5
#> [4,]      8      8      9      9      9      9      9      9      9      9
#> [5,]     11     11     10     10     10     10     10     10     10     10
#>      [,129] [,130] [,131] [,132] [,133] [,134] [,135] [,136] [,137] [,138]
#> [1,]      2      3      1      1      1      1      1      1      2      2
#> [2,]      4      4      2      2      2      3      3      4      3      3
#> [3,]      5      5      3      4      5      4      5      5      4      5
#> [4,]      9      9      9      9      9      9      9      9      9      9
#> [5,]     10     10     11     11     11     11     11     11     11     11
#>      [,139] [,140] [,141] [,142] [,143] [,144] [,145] [,146] [,147] [,148]
#> [1,]      2      3      1      1      1      1      1      1      2      2
#> [2,]      4      4      2      2      2      3      3      4      3      3
#> [3,]      5      5      3      4      5      4      5      5      4      5
#> [4,]      9      9     10     10     10     10     10     10     10     10
#> [5,]     11     11     11     11     11     11     11     11     11     11
#>      [,149] [,150]
#> [1,]      2      3
#> [2,]      4      4
#> [3,]      5      5
#> [4,]     10     10
#> [5,]     11     11

Created on 2022-12-02 with reprex v2.0.2


Is there a name for this phenomenon in the circle of fifths?

Question: I've recently come across some interesting properties of the circle of fifths in relation to diatonic modes. I'm wondering whether this has been noted elsewhere and if so, in what capacity? A name to Google would help. So far, I've found nothing.
The general idea is that tritone can move chromatically and imply a modal shift in fifths. Each diatonic mode has one tritone in it and it's position relative to the root can be considered distinctive of that mode as no two modes share the same tritone position. Let's consider an exercise. Say a tritone is imperfect and needs to be either widened to a perfect fifth or narrowed to a perfect fourth. We'll start with a series of narrowings using D Dorian as a starting point. I chose it for its symmetry, but it's really arbitrary. It will work regardless.
D Dorian's tritone is from F to B, the minor third to the major sixth. We'll flatten the B to a Bb, making the interval a perfect fourth. Well now the the interval from E to Bb is a tritone. We flatten the E to Eb. Note that we don't further flatten the Bb. We're operating with fourths, so we must use the inversion spelled as an augmented fourth, not a diminished fifth. We'll continue this process. We have the mode, the major scale it is derived from, and the note that was just flattened from the last mode:
Mode          Major Scale  Flattened Note
D  Dorian     C           --
D  Aeolian    F           Bb
D  Phrygian   Bb          Eb
D  Locrian    Eb          Ab
Db Lydian     Ab          Db
Db Ionian     Db          Gb
Db Mixolydian Gb          Cb
Db Dorian     Cb          Fb

We can do the same for sharpening diminished fifths into perfect fifths:
Mode          Major Scale  Sharpened Note
D  Dorian     C            --
D  Mixolydian G            F#
D  Ionian     D            C#
D  Lydian     A            G#
D# Locrian    E            D#
D# Phrygian   B            A#
D# Aeolian    F#           E#
D# Dorian     C#           B#

Of course, we see that the corresponding series leads us the circle of fifths with sharps and the circle of fourths with flats. A circle of fourths moves the tritone down a halfstep for each pass until it is a perfect fifth away from its original position and the mode is now the same, just a chromatic half step down. The circle of fifths performs the complement. So again, does this have a name and who has written about it?
Edit: I'm specifically asking about a mode's tritone moving chromatically as the modes move through the circle of fifths.
Comment: It has a name, it's the circle of fifths. What else do you want to name it?
Answer: As mentioned by Raskolnikov it is indeed just the circle of fifths and nothing else. If you have no sharps and no flats, and you add one sharp, you can say you go from C major to G major. You can also say you go from A minor to E minor. Equivalently, you go from D dorian to A dorian, or from D dorian to D mixolydian, or from A aeolian to A dorian, etc.etc. It's just all exactly the same.
I actually use this as an exercise for students who learn modes. Choose a root and play the locrian mode, then add a sharp and play phrygian with the same root. Keep adding sharps at the appropriate places until you've reached lydian (still with the same root). Question: what happens if you add one more sharp? As soon as they understand how this works, they've mastered modes (at least theoretically). The same exercise also works of course the other way round, i.e. start with lydian, add flats until you've reached locrian, add one more flat and you're back to lydian, but one semi-tone lower.
As mentioned before this is just another way of looking at the circle of fifths. Instead of changing the root and keep the mode the same, you keep the root the same and the modes change from dark to open (by adding sharps), or the other way around.
Comment: @DanDavis: This is what every jazz musician uses when playing e.g. the bridge of rhythm changes: D7 - G7 - C7 - F7: F#+C => F+B => E+Bb => Eb+A
Comment: Well I've known this part for a while. I'm referring specifically to how a mode's tritone moves chromatically as a circle of fifths progresses. I can edit that to make it clearer.
Comment: That's definitely cool. I didn't think that would have been a conscious thing.
Comment: @DanDavis: Also in a standard blues, the way to move from I7 to IV7 is by chromatic resolution. E.g., for a blues in C: C7 (I) => F7 (IV) goes from the tritone E+Bb to the tritone Eb+A. This resolution is used for comping as well as for soloing.
Comment: Not just jazz and blues -- Bach manages to use the same descending chromatic tritones technique in his music! (see an excerpt in my answer)
Answer: It's because of beauty of symmetry (and asymmetry) of musical scale. (WARNING: some math ahead)
Take a C major scale, and write it down the intervals between each note in number.  So a halftone is 1, whole tone is 2 because it's two times the halftone.

    C   D   E   F   G   A   B   C   D   E   F   G   A   B   C
      2   2   1   2   2   2   1   2   2   1   2   2   2   1

(repeated twice for later use.)
2 2 1 2 2 2 1 .. -- you see this pattern looks a bit repetitive, but not perfectly.  There is 2 2 in one side and 2 2 2 in another side.  2 2 2 means three whole tones in a row, and it's where the tritone comes in, between F and B.
Now you want to transpose the scale to the nearest.  That is, make the scale of the same structure with a little change as possible, changing only one single note.  With some trial-and-error, you would find out there are only two ways to do that.  As we already know, they are F and G major:

     C   D   E   F   G   A   B   C   D   E   F   G   A   B   C
       2   2   1   2   2   2   1   2   2   1   2   2   2   1

                 F   G   A   Bb  C   D   E   F
                   2   2  (1   2)  2   2   1

                    G   A   B   C   D   E   F#  G
                      2   2   1   2   2  (2   1)

Compare them with C major.  With our notation here, to transpose to the nearest scale means to change the position of 1 and 2 appropriately.  By doing that, you see the tritone 2 2 2 flips to the other side, and each note at the end of the tritone is shifted halftone, for the reason more or less clear.
More story to read:

Set theory (music) is an amalgam between mathematics and music theory to discuss such phenomena.
Modes of limited transposition are the musical scales constructed to be so symmetrical that such phenomena won't occur.
Comment: Thanks for the reading. I'm aware of these things, but this will give me some incentive to actually dive in and read about them. Thank you.
Answer: I want to point out a few things:
First of all, as others have mentioned, the tritone is symmetric. What this means is that if you take a tritone, and transpose it up or down by a tritone (6 half steps) the result is the same as the interval that you started with (assuming enharmonic equivalence). As a result of the above, moving a tritone up or down by 1 half step results in an interval that is equivalent to the one you would get by moving it up by 5 or 7 half steps (respectively) -- which, of course, are the intervals of a fourth or a fifth. Due to these properties, it's really no surprise that moving a tritone by a half step harmonizes with a scale a fourth or a fifth away. And of course that scale can also be considered a different mode of the scale you're currently in. I don't think there's any specific name for this beyond it being a specific voice leading option for a circle of fifths progression. Changing through modes like that isn't really that common (possible counterexample: modal jazz, where each chord gets its own mode, but this is a special case of chord progressions).
I'm going to take exception with your statement that a tritone uniquely determines a mode. Assuming your root is C, consider the interval C-F♯. This looks like C Lydian (C, D, E, F♯, G). But, using enharmonic equivalence (which we already had to assume), this interval could also be written as C-G♭, which indicates C Locrian (C, D♭, E♭, F♭, G♭). What I would instead say, is that a given tritone uniquely determines two distinct major scales a tritone apart (e.g. C-F♯/G♭ can indicate either G or D♭). There are only 6 possible tritones (after enharmonic equivalence), and each gives you two keys, thus all 12 major scales. For any given root, 7 of these scales will contain the root, and can be seen as a mode based off that note. Since there are 6 tritones, and 7 modes, the tritone that contains the root gets to have two possible modes. BTW, this dual nature of tritones is the basis for the tritone substitution (i.e., replacing V7 with ♭II7, since they share the same tritone).
While switching between modes isn't all that common, switching between chords is. The practice of voice leading is all about creating smooth chord progressions with a minimum of voice movement, and chord progressions by a fourth or a fifth are one of the most common progressions, so of course this type of chromatic motion has been used quite extensively. Others have mentioned jazz and blues, which both use it, but I wanted to point out that even as early as Bach, this type of progression was already known. I was just listening to the St. John Passion, and about 40 seconds into the opening movement (in the linked video) he has a chord progression of ascending fourths in the bass, accompanied by a chromatically descending tritone in the wind parts. This type of progression would not normally be acceptable in Baroque music, because of the leading tone's need to resolve upward to a consonance rather than downwards to a dissonant minor seventh. Bach manages to work around this limitation by having the leading tone of the tritone drop by a half step before the bass moves (thus removing the leading tone, and it's need to resolve upward), and then holding that note into the next bar, creating a suspended seventh. It makes sense that Bach would want to use a descending chromatic scale here, since, in the Baroque era, that was a musical symbol of death, and this is a Passion (a musical representation of Christ's death).
Here's an excerpt (of the wind parts and the bass line), with boxes highlighting the relevant chord progression: D7 -> G7 -> C7 -> F7 -> B♭7.
Comment: This seems pretty comprehensive of everything I was looking for. Also, that Bach is fascinating. There's so many hidden joys in his music.


Qual é a diferença entre reset e clear no Terminal?

Question: No Terminal, qual é a diferença entre os comandos reset e clear?
Estou utilizando o Terminal do Ubuntu e, aparentemente, os dois comandos limpam a tela.
Comment: Utilize o comando `man`, `man reset` e `man clear`, você vai ver exatamente o que cada comando faz e vai entender a diferença entre eles
Comment: reset aparentemente reseta todos os comandos, e clear apenas limpa as telas, no caso o reset seria a mesma coisa que reescrever todos os comandos novamente.
Comment: Isso foi uma metáfora?
Answer: clear

Elimina o conteúdo da área visível. O que ele na verdade faz é rolar a barra para que você veja somente a área limpa. Mas se você der um scroll para cima verá todo o conteúdo anterior lá.
reset

Realmente limpa o terminal. Equivale a fechar e abrir um novo terminal.


How to bind a property from my usercontrol content control to a property in my viewmodel?

Question: I have a usercontrol like this:
<UserControl x:Class="MySample.customtextbox"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="20" d:DesignWidth="300">
    <Grid>
           <TextBox x:Name="Ytextbox"  Background="Yellow"/>
    </Grid>
</UserControl>

I want use this control in a View such as MainWindowView
How can I Binde my Ytextbox Text Property to a property in my MainWindowViewModel?
<CT:customtextbox  Text="{binding  mypropertyinviewmodel}"/>

I know that I must define a DependencyProperty for my control until  I can bind a property in my viewmodel to it so i define a dependency property for my control like this:
public static readonly DependencyProperty InfoTextProperty =
        DependencyProperty.Register("InfoText", typeof(string), typeof(customtextbox), new FrameworkPropertyMetadata(false));

public string InfoText
{
    get { return (string)GetValue(InfoTextProperty);}
    set
    {
        SetValue(InfoTextProperty, value);
    }
}

When I define a dependency property for my control I have a xaml error:

Error 1   Cannot create an instance of "customtextbox".
Answer: new FrameworkPropertyMetadata(false)

You cannot set the default value of a string property to false (which of course is a bool).
There may be some other problems (e.g. you have no binding on the TextBox in the user coontrol declaration and you try to set a property you did not register where you create an instance) but for those you should search SO.
Answer: You're trying to set boolean value to a string DependencyProperty. Should be something like that
 new FrameworkPropertyMetadata(string.Empty)

or
new FrameworkPropertyMetadata(null)

Answer: Umm try this as the code for your dependency property.
public static readonly DependencyProperty InfoTextProperty =
    DependencyProperty.Register(
        "InfoText",
        typeof(string),
        typeof(customtextbox)
    );

    public string InfoText
    {

        get { return (string)GetValue(InfoTextProperty);}
        set {SetValue(InfoTextProperty, value); }
    }

I just removed the last parameter from when you register the property, I think that's supposed to provide a default value for the property and you were providing a boolean instead of a string, it's an optional parameter anyways.


Boost sockets. Working code no longer working after format / reinstall of ubuntu. permission problems?

Question: i am running ubuntu 16.04 and using ROS kinetic (irrelevant for this question). unrelated to this project, i broke my system and decided to reinstall ubuntu. everything went fine and i thought that i had put my system back together. so now i have this code to send a packet to a LiDAR and decode the information i get back. you can see i put a couple cout's for debugging. the program freezes after sending the packet and waiting for the data back. this code has been working correctly for several months now and has not changed after the reinstall of ubuntu.
things i have tried
sudo adduser my_username dialout
sudo adduser my_username root
sudo adduser my_username sudo

I have also edited /etc/sudoers.d to add my username in there with all permissions.
the reason i suspect that the hangup is due to permissions is because i have another piece of code that uses UART communication through /dev/ttyUSB1 and i must use sudo chmod a+rw /dev/ttyUSB1 before it will work. this was not necessary before.
The relevant code is below although i strongly suspect this is not the issue. the code compiles and runs as expected except for the hangup. i would appreciate any feedback and suggestions and i will do my best to keep on top of replies.
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <sensor_msgs/LaserScan.h>

using boost::asio::ip::udp;

class KeyenceLaser
{
    public:
        KeyenceLaser(boost::asio::io_service& io_service, const std::string& host, const std::string& port):io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0))
        {
            udp::resolver resolver(io_service_);
            udp::resolver::query query(udp::v4(), host, port);
            udp::resolver::iterator iter = resolver.resolve(query);
            endpoint_ = *iter;

            if (socket_.is_open()){std::cout<<"socket open"<<std::endl;;}else{std::cout<<"socket not open"<<std::endl;}
        }

        ~KeyenceLaser()
        {
            socket_.close();
        }

        void send(const std::string& msg)
        {
            socket_.send_to(boost::asio::buffer(msg, msg.size()), endpoint_);
        }
        void poll(sensor_msgs::LaserScan::Ptr scan)
        {
            char request[1920];
                            char srequest[]={0x90,0,1,0,0,0,0,0,0,0};// sends the request to get all beam data back
            size_t request_length = strlen(srequest);
            unsigned char reply[1920];
            scan->ranges.resize(953);

            try
            {
std::cout<<"1 sending request"<<std::endl;
                boost::system::error_code errcode;
                boost::asio::socket_base::message_flags flags=NULL;
                int bytesSent =-1;
                bytesSent= socket_.send_to(boost::asio::buffer(srequest, 10), endpoint_ );
std::cout<<"sent " << bytesSent << " bytes\n2 waiting for data back"<<std::endl;
                size_t reply_length = socket_.receive_from(boost::asio::buffer(reply, 1920), endpoint_);
std::cout<<"3 got data back"<<std::endl;

                scan->angle_min = -.090757;
                scan->angle_max = 3.23234;
                scan->angle_increment = 3.323106 / 953.0;
                scan->range_min = 0.00;
                scan->range_max = 5.0;
                scan->ranges.reserve(953);
                scan->ranges.resize(953);
                scan->ranges.clear();

                for (int i=14;i < 1921; i++)
                    {
                    //std::cout << i/2-7<<":"<<(((reply[i+1]<<8) + reply[i])/1000.0) << std::endl;
                    scan->ranges.push_back(((reply[i+1]<<8) + reply[i])/1000.0);

                        i++;
                    }

            }
            catch (std::exception& e)
            {
                std::cout << "Exception: " << e.what() << "\n";
            }
        }

    private:
        boost::asio::io_service& io_service_;
        udp::socket socket_;
        udp::endpoint endpoint_;
};

EDIT 1:
i have modified the code to the following...
std::cout<<"1 sending request"<<std::endl;
                    boost::system::error_code errcode;
                    boost::asio::socket_base::message_flags flags;
                    int bytesSent =-1;
                    bytesSent= socket_.send_to(boost::asio::buffer(srequest, 10), endpoint_ ,flags, errcode);
std::cout<<"sent " << bytesSent << " bytes\ngot error code: " << errcode << "\n2 waiting for data back"<<std::endl;
                    size_t reply_length = socket_.receive_from(boost::asio::buffer(reply, 1920), endpoint_);
std::cout<<"3 got data back"<<std::endl;

and i get error 95 - operation not supported , but i think thats cause i didnt instantiate my flags correctly (and google isnt helping me do that)
EDIT 2:
i just wanted to make it clear that i think i've installed all the required software. i'm open to apt-get some more stuff if you think that i'm just missing some library.
P.S. i did modify the code again slightly and the socket is being shown as open with 10 bytes sent. the LiDAR "link" light does not blink after i send the packet though (it did before), so I don't think the packet is actually getting through the cable
Answer: So it turns out that this issue was unrelated to Boost Sockets. The error came from the connection to the LiDAR itself. It showed as connected via my network connections but it was not actually connected to the LiDAR. After I switched that conecttion IPv4 method to Link-Local, it worked immediately.thank you to everyone who read and considered my issue


Software to find out adjacency matrix of a graph.

Question: I am looking for a graph theoretical software. I can draw a graph delete or add its vertices and edges whatever I want. The software shall give me the Adjacency matrix, degree matrix etc.
Is such a software exists? If available please provide its name and publisher.
Anyhow how can I implement it in C or C++?
I am currently using Matlab, but it is not much helpful.
Thank you for your help.
Answer: You can use  sage, http://www.sagemath.org/. Suppose, for example, to find the adjacent matrix of $K_5$, then the following program will find it for you.
sage: g= graphs.CompleteGraph(5)
sage: g.adjacency_matrix()
The manual is here http://www.sagemath.org/doc/reference/graphs/sage/graphs/generic_graph.html
Comment: Can you draw there?
Comment: Yes we can draw graphs also.
Comment: Sage draws graphs, but can you give a drawing as input?
Comment: Thank you for your help. Let me try.
Comment: @draks... I don't think we can input a drawing. But we can input the set of vertices and set of edges.
Answer: I wrote some software in Matlab for this task for my own purposes, and it is available
for download from my website: Graph Manager. It was designed to work with Matlab 6.5 (the only version I own which was released over 10 years ago) and you should unzip it and run it with graphm from inside the created directory. It should look like this:

You can use the mouse to add/delete vertices and edges and do other things. Since it was for my use there are probably a few things that are unclear, feel free to ask here if there is a problem.
Since it was mainly used to look at graphs on the torus you will need to switch that off if you see the green box; you do that with "Save/Disp" and the "shape" submenu.
To get the adjacency matrix you can just go to the main Matlab window and it will be in the global variable A.
Comment: Excuse me, two days I was out of station and could not check this post. I have downloaded it. I shall contact you latter. Thank you.
Comment: The last paragraph is not clear. How to access "Miscellaneous" ?
Comment: Sorry, I just realised that version 1 is the one on the website. It should be simpler for your use. I've adjusted the instructions about how to get the adjacency matrix now.
Comment: Dear Sir, Thank you very much for your help. I am very new with MATLAB and the graph theory...
Comment: +1 I've searched too long for something like that. Is there a manual? Oh I just realized that I can't upvote today, since I reached my daily limit...
Comment: Sorry, no manual, but if there's something that doesn't do what you think, feel free to ask here.
Comment: @jp26 are there any key shortcuts? And does it support an algorithm to color the edge?
Comment: There are shortcuts using the underlined letters, so alt V to get to the vertex menu, etc. I've never needed edge colouring, so didn't implement it, sorry. It should be possible to add it with a bit of coding knowledge though.
Answer: Current releases of Matlab (from 2016 at least) implement the graphs in the Bioinformatics toolbox, the functions are pretty advanced right now and allow you to draw graphs, extract adjacency matrices etc.


Is the determinant of this matrix positive or negative?

Question: $\left( \begin{array}{ccc}
1 & 1000 & 2 & 3 &4\\
5 & 6 &7&1000 &8\\
1000&9&8&7&6\\
5 & 4&3&2&1000\\
1&2&1000&3&4\\ \end{array} \right)$
When I compute the determinant online, I find that it is positive, but I'm supposed to "see" something about the matrix that allows me to know the determinant is positive. What properties does this specific matrix have that allow you to deduce the determinant will be positive?
Comment: Just for fun, if you replace $1000$ with $x$ [you get](http://www.wolframalpha.com/input/?i=det%28%5B%5B1%2Cx%2C2%2C3%2C4%5D%2C%5B5%2C6%2C7%2Cx%2C8%5D%2C%5Bx%2C9%2C8%2C7%2C6%5D%2C%5B5%2C4%2C3%2C2%2Cx%5D%2C%5B1%2C2%2Cx%2C3%2C4%5D%5D%29%3D0) $x^5-169 x^3+1508 x^2-4972 x+5232$. This function has three real roots, the largest one being $4.8639\cdots$. So, the determinant is positive for $x \ge 5$. You don't really need $x=1000$. But of course, none of this is "easy to see".
Comment: If you're supposed to 'see' something, the first thing that should pop right out is those massive `1000`.  So can you see something about their placement?
Answer: Expand the determinant as a sum of $120$ terms, each being a product of $5$ factors.  (That is, imagine you expand it; don't write it out. . . )
All these terms will be positive; then $60$ of them will be added and $60$ will be subtracted.  Just one of the terms will be $1000^5$, and by checking the permutation you can see that it will have a positive coefficient.
Every other term will be at most $1000^3\times8\times9$; since exactly $60$ of these terms will be subtracted, we have
$$\eqalign{D
  &\ge1000^5-60\times1000^3\times8\times9\cr
  &>1000^5-100\times1000^3\times10\times10\cr
  &=990\times1000^4\ .\cr}$$
Answer: Using the position occupied by the terms $1000$ we can write the determinant in a nicer way
$$\left| \begin{array}{ccc}
1 & 1000 & 2 & 3 &4\\
5 & 6 &7&1000 &8\\
1000&9&8&7&6\\
5 & 4&3&2&1000\\
1&2&1000&3&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
 1000 & 1 & 2 & 3 &4\\
6 & 5 &7&1000 &8\\
9& 1000&8&7&6\\
4 & 5&3&2&1000\\
2&1&1000&3&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
 1000 & 3 & 2 & 3 &4\\
6 & 1000 &7&5 &8\\
9& 7 &8&1000&6\\
4 & 2&3&5&1000\\
2&3&1000&1&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
 1000 & 3 & 3 & 2 &4\\
6 & 1000 &5&7 &8\\
9& 7 &1000&8&6\\
4 & 2&5&3&1000\\
2&3&1&1000&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
 1000 & 3 & 3 & 4 &2\\
6 & 1000 &5&8 &7\\
9& 7 &1000&6&8\\
4 & 2&5&1000&3\\
2&3&1&4&1000\\ \end{array} \right|=10^{15}+x.$$
Now, having in mind that in a determinant of a matrix of order $5$ there are $120$ terms and one of them is $10^{15}$ we can bound $x.$ Indeed, we have that
$$x>-119 \cdot 1000^3\cdot 9\cdot 8= -8568\cdot 10^9.$$
So,
$$10^{15}+x>10^{15}-8568\cdot 10^9>0.$$
Answer: By definition, the determinant is the sum of $60$ positive and $60$ negative terms, one of which is $\mbox{sgn}{\left(
\begin{array}{ccccc}
 1 & 2 & 3 & 4 & 5 \\
 3 & 1 & 5 & 2 & 4 \\
\end{array}
\right)}(1000)^5=\mbox{sgn}\left((13542)\right)(1000)^5=+(1000)^5$.
Each of the other terms has absolute value at most $9\cdot1000^4$, so the sum of the 60 negative terms is greater than or equal to $-60\cdot9\cdot1000^4$, and the determinant is greater than or equal to $(1000)^5-60\cdot9\cdot1000^4$, which is positive.
Answer: With an even number of adjacent row swaps, you can put the $1000$s on the diagonal.  That determinant must be positive.  Using the algorithm which looks at minors, the largest term is always positive.
Comment: Alternatively, note that only 60 of those 119 terms are negative.
Comment: ...and the important thing is that the largest term is very large compared to all the others.  Obviously it's at least $1000/9 \approx 111$ times larger than any other term, but there are $119$ other terms so a small amount of subtlety is needed.  But if you think about it, it's actually at least $1000^2/9^2$ times larger than any other term, which is plenty large enough to dominate the sum.
Answer: You can use 1000 in every row to eliminate the other element to get an upper triangular matrix, and in the process for 1000 is large enough, you can reckon the element in other column won't change. Then you can get the elements on the diagonal all are1000, which shows the determinant is positive.`


Why is $(AX)\cdot Y=X\cdot (A^{T}Y)$?

Question: Can this equation $(AX)\cdot Y=Y\cdot (A^{T}X)$ be proved? where $A$ is a symmetric matrix, and $X$, $Y$ are the eigenvectors of $A$.
Comment: The dot product is defined as $X\cdot Y=X^TY$. So $(AX)\cdot Y=(AX)^TY=X^TA^TY=X^T(A^TY)=X\cdot(A^TY)$. It has nothing to do with $X$ and $Y$ being eigenvectors.
Answer: $$(AX)\cdot Y = \lambda X\cdot Y$$
$$Y\cdot (A^TX) = Y\cdot X \lambda = \lambda X\cdot Y$$
$$\Rightarrow (AX)\cdot Y = X\cdot(A^T Y)$$
Remember that in a symmetric matrix, $A = A^T$, and that the dot product of vectors is commutative.
Comment: could this be proved without using eigenvalues
Comment: Yes, you could just flip $Y\cdot (A^TX)$ and use the equality $A=A^T$. I figured that since you gave $X$ and $Y$ as eigenvectors that it was a practice problem that was intended to illustrate their usefulness.

Why is $(AX)\cdot Y=X\cdot (A^{T}Y)$?


Joomla's modal window removing id and class names

Question: I have a form in a module that I want to appear in a modal window.  Depending on the id the window may be blank, or if it does show any content all classes and ids are removed, so I can't validate or style the form.
Truncated Code:

      ...

This triggers the modal window without any ids or classes (using Firefox Web Developer outline current elements):
Click for ugly unstyled form that won't validate

This triggers a blank modal window:
Click if you like staring at a blank white box

So most importantly how do I keep all the ids and classes inside the modal window, and why won't calling the parent div work?
( As a work around I moved the form to a component view then called it using handler: 'iframe' instead of clone.  I still want to know what's going on with the modal window. )
Thanks!
Comment: You need to post more code - I really don't understand how to produce the problem
Answer: not seen the code but implications of using Element.clone on an element are apparent. By nature of HTML, id is meant to be unique. This means you are not really supposed to have more than one element with the same id injected into the DOM at the same time.
MooTools mirrors the sentiment correctly by implicitly removing the id from any element it creates a clone of:
https://github.com/mootools/mootools-core/blob/master/Source/Element/Element.js#L860
the .clone method accepts optional arguments which allow you to override stuff:
clone: function(contents, keepid){ - see http://mootools.net/docs/core/Element/Element#Element:clone as well.
cloned elements also lose all the events you may have assigned to them (but cloneEvents can help with that).
I would recommend looking at the squeezebox implementation and double check that the clone is implemented in the intended way. A better practice may be to adopt and re-attach the elements instead - or to copy the whole innerHTML (though this will once again cause non-delegated events to fail).


Is there a MySQL engine for in-memory tables that support row locks?

Question: The default MySQL in-memory engine only supports table-locks. This is killing our performance on our session table (using Joomla on the front-end).
Is there a (third-party) engine of an in-memory table that supports row-based locking?
Answer: ndb's memory engine does row-level locking:
http://dev.mysql.com/doc/refman/5.5/en/memory-storage-engine.html
I'm not aware of any other plugin that does.
Have you considered using tmpfs or ramfs for storage?


How to retrieve default Title in custom module block

Question: I have custom module that implements a block with our own template file to render:
function MODULE_NAME_block_view($delta = ''){
    $blocks = array();
    switch($delta){
        case 'twitter_feed':{
            $blocks['subject'] = t('');
            $blocks['content'] = theme_render_template(drupal_get_path('module', 'MODULE_NAME').'/inc/block--twitter-feed.tpl.php', twitter_feed_config());
            break;
        }
    }
    return $blocks;
}

I would like to pass the title value set in UI in blocks section to the template via the function twitter_feed_config specified above as following:
function twitter_feed_config(){
  return array(
       'title' => 'title set by user i am unable to retrieve'
   );
}

However, I don't seem to find a way to retrieve the value of title for this block configured via UI in the admin/block section. How to get this title value, so i can pass it to the template for rendering? Thank You
Answer: I think you should use hook_block_views_alter(&$data, $block).
Var $data['subject']; will have the title info of the block as per my knowledge.
Comment: Thank you Rajeev. This does not work for me because its parameters is array of data as returned from the hook_block_view() from a scope i need the 'title' accessible in first place.


AWS Cognito: dealing with token expiration time

Question: I am experimenting with Cognito and when I thought it was starting to be OK, I am facing the issue of (Google) token expiring after 1 hour.
When I start with a clean device, I can sign up, use the app for 1 hour, then as soon as I need to refresh a dataset, I get and error saying the the token is not authorised.
Are there any example on how to deal with this?
Is it really something the app developers should be doing?
I was expecting the SDK to manage such things in the background.
Is it meaning that we have to check the credentialsProvider.getSessionCredentitalsExpiration() before each dataset synchronisation ?
Many thanks,
JM
Edit 1 : Added code
I do have a SigninActivity, but it is only called when no credentials exists at all, in theory only once the first time the user logs in.
It is built as follows (removed useless bits).
So what happens is that I authenticate right the first time, but as I never enter this activity again, maybe something is missing.
But there must be a way to refresh this token silently?
<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.signin);

    // Aws Credential provider
    credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(), // Context
            getString(R.string.aws_identity_pool), // Identity Pool ID
            Regions.EU_WEST_1 // Region
    );

    // Google connect
    findViewById(R.id.signin_with_google_btn).setOnClickListener(this);

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestProfile()
            .requestIdToken(getString(R.string.google_server_client_id))
            .requestId()
            .build();

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this )
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    SignInButton signInButton = (SignInButton) findViewById(R.id.signin_with_google_btn);
    signInButton.setSize(SignInButton.SIZE_WIDE);
    signInButton.setScopes(gso.getScopeArray());
    signInButton.setColorScheme(SignInButton.COLOR_DARK);
}

@Override
public void onClick(View view) {
    this.signinWithGoogle();
}

/**
 * Triggers Google signin
 */
private void signinWithGoogle() {
    Log.v(this, "Signing in with Google...");

    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    this.startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GOOGLE_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        this.handleGoogleSignInResult(result);
    } else {
        // Other stuff
    }
}

/**
 * Handle Google sign in result
 */
private void handleGoogleSignInResult(GoogleSignInResult result) {

    if (result.isSuccess()) {

        Log.v(this, "Successfully logged in with Google...");

        GoogleSignInAccount acct = result.getSignInAccount();
        Log.v(this, "Signed in as %s / %s (token %s)", acct.getDisplayName(), acct.getEmail(), acct.getIdToken());
        Map<String, String> logins = new HashMap<>();
        logins.put("accounts.google.com", acct.getIdToken());
        Log.v(SigninActivity.this, "Google token <<<\n%s\n>>>", logins.get("accounts.google.com"));
        credentialsProvider.setLogins(logins);
    } else {
        // Signed out
        Log.w(this, "Failed to authenticate against Google #%d - %s", result.getStatus().getStatusCode(), result.getStatus().getStatusMessage());

        SimpleMessageDialog.show(SigninActivity.this,
                R.drawable.icon,
                R.string.error,
                R.string.sorry_error_signing_you_in_please_try_again,
                R.string.try_again);
    }
}
</code>
Answer: Are you following all the steps documented here? The SDK will get you AWS credentials in exchange of a valid token automatically, but if your Google token is expired, then you need to refresh it.
Comment: Hi Rachit, thanks for your answer, I have edited my question and added my code.

Generally speaking an examples on how to handle token refresh and gerenally "post sign on errors" (user did withdraw auth, this kind of things) would really really help.
Comment: So refreshing the google token is upto personal preference and we have seen developers do something along the lines of http://stackoverflow.com/questions/18572088/how-to-get-oauth-2-refresh-token-using-access-token.

That being said, we have heard customer requests about providing helper methods to refresh tokens and we will consider adding those in future releases.
Comment: Rachit, I can only second this requirement.
I am not having a go at you, but this is pretty disappointing that this is not managed out of the box.

Unless I am confused, this is sounding like a pretty basic requirement and the SDK should deal with kind of things in order to allow us to focus on our added value.
Comment: We have heard this request from other customers also and will consider adding this feature in future updates to the service. As always feel free to post in our forums or here if you have any questions.
Comment: What puzzles me is that I was able to reproduce a situation where Cognito deals with this on its own (see here https://github.com/ironbird-software/aws-cognito-sync-issues). So I cannot understand why the onus is on the developper when it would be much simpler for us all if the SDK was dealing with it consistently.


replace value with condition

Question: I want to replace more than one values if that values satisfy a condition
this is the code that I used
set.seed(2001)
x <- rnorm(15, 1, 3)
mu <- mean(x)
h= -2.456
C.CUSUM <- function(x) {
  c <- numeric(length(x))
  for (i in seq_along(x)) {
    c[i] <- min(0, c[i-1] + x[i-1] - mu)
  }
  c
  }
  C.CUSUM(x)

After running C.CUSUM function, I want to write this line in R
if c[i] > h then k=i, for instance if c[3] > h and c[4] > h then k = 3, 4
Comment: I think this OT here. Also, what is `k` and what is your desired output?
Answer: This should work
c <- C.CUSUM(x)
# calling the function to store a vector of values in c
c.test <- ifelse (c > h, 1, 0)
# creates a new vector and assigns 1 to values that are above h, 0 to the rest
k.test <- which(c.test==1)
# creates a vector of the position numbers from c.test where c.test is 1

replace value with condition


confused about CIDR interpretation

Question: I am beginner in networking and trying to understand subnetting. What I understood is that

CIDR notation (Classless Inter-Domain Routing) is an alternate method of representing a subnet mask. It is simply a count of the number of network bits (bits that are set to 1) in the subnet mask.

Meaning that a CIDR in this form 10.0.0.0/30 means that

The networkID is 10.0.0.0 and the subnet mask 255.255.255.253
The subnet has two host addresses (10.0.0.1 and 10.0.0.2 ) and one broadcast address 10.0.0.3
Does the CIDR mean anything else than the two points mentioned above ? and What is the default gateway address in this case ?

The following notations confuses me. Sometimes I see

10.0.0.2/30, 10.0.0.3/30 (for instance, IP 10.0.0.3 exits in the two networks )
or 10.0.0.0/30 and 10.0.0.0/8
Wouldn't there be an intersection between networks in this case, in other words, meaning same IP addresses exit in two different networks?
Comment: This [question and answer](https://networkengineering.stackexchange.com/questions/7106/how-do-you-calculate-the-prefix-network-subnet-and-host-numbers) from our sister site Network Engineering SE  may help you.
Comment: One small comment on item #1: the mask should be 255.255.255.252
Answer: For your first question:
Well CIDR is just another notation for the Subnet Mask. So i think your question is more about the subnet mask.
The Subnet mask exists, to let you determine the network prefix and the host identifier out of an ip address.
That's the only thing the subnet mask is really here fore. Of course you can then conclude more out of this information, which includes:

Boradcast Address
Network range
Choose Gateway address
Check if two peers are in the same network
Routing configuration

About your question regarding the gateway: Usually in inside networks the gateway address, is the first address of a network (10.0.0.1), however i have also seen networks, where the last address of the network is the gateway address (10.0.0.2). But the most corporations choose the first network address for the gateway ip address. But technically, you could use any ip adress in the network for your gateway address. It's just a convention and not a technically necessity.
For your second question:
You are absolutely right, these two ip addresses can not communicate with each other. Every ip address is unique in his network. To see if two ip addresses are in the same network and can communicate with each other, you just need to calculate the network prefix and see if it matches. So there you found already another purpose of the subnet mask: You can check if two ip addresses are on the same network.
Answer: Many questions in one and not so easy to refer to different sections as there are multiple numbered lists...

CIDR notation (Classless Inter-Domain Routing) is an alternate method of representing a subnet mask. It is simply a count of the number of network bits (bits that are set to 1) in the subnet mask.

Indeed, this is the information it contains.

Meaning that a CIDR in this form 10.0.0.0/30 means that

The networkID is 10.0.0.0 and the subnet mask 255.255.255.253

Actually 10.0.0.0 and netmask 255.255.255.252, but I get the impression that you probably have the right idea regarding this part even if the numbers were wrong here.
And regarding the question, yes, this is all that it means.
(It's not necessarily used with a network id specifically, it can be any address depending on the context. Just like you can specify eg a host address with netmask, depending on the context.)

The subnet has tow host addresses (10.0.0.1 and 10.0.0.2 ) and one broadcast address 10.0.0.3

I suppose, yes. The information it directly conveys (see 1), has the same implications regardless if it's written as 10.0.0.0/30 or network: 10.0.0.0, netmask: 255.255.255.252.

Does the CIDR mean anything else than the two points mentioned above ? and What is the default gateway address in this case ?

No, it doesn't mean anything else.
Just like your netmask version of the same information, it doesn't say anything about what address might be the default gateway (if such a thing is even relevant).

The following notations confuses me. Sometimes I see

10.0.0.2/30, 10.0.0.3/30 (for instance, IP 10.0.0.3 exits in the two networks )
or 10.0.0.0/30 and 10.0.0.0/8
Wouldn't there be an intersection between networks in this case, in other words, meaning same IP addresses exit in two different networks?

There are several aspects to consider here:

You can trivially rephrase this second block of questions using "netmask notation" if you like (as per 1 in the previous set of questions). I don't know if that might change anything regarding your understanding of the scenarios that you are describing?
Either way, as I see it, there is nothing specific to CIDR notation going on here.

When you say 10.0.0.2/30, 10.0.0.3/30 these might well refer to addresses in the exact same network if that fits the context.

Your example uses RFC1918 addresses, which is fine if that is what is part of the scenario that you ask about. But these private addresses are duplicated in many networks across the world, meaning there's nothing strange about these private addresses being used in different/conflicting ways in separated networks.

You wouldn't generally want the same IP address being used on two different network links in the same network (the RFC1918 situation is a factor here, with reuse in separated networks as per the above), but do keep in mind that the notation is also used in other contexts than just on-link addresses.
Example: Maybe on router1 you route 10.0.0.0/16 to router2, and router2 then might have 10.0.0.0/24 on one network link and 10.0.1.0/24 on another.
Addresses in both these /24 networks match the 10.0.0.0/16 route, but there is no conflict there; eg 10.0.0.7 exists in exactly one place and 184.108.40.206 exists in exactly one (other) place.

confused about CIDR interpretation


Why does it make sense to define the Probability mass function of e.g. the binomial distribution like this?

Question: In Wikipedia (for example) the Probability mass function of for example a the binomial distribution is given by
$$
f(k,n,p):=\binom{n}{k}p^k(1-p)^{n-k}
$$
In some literature I read
$$
P_{n,p}:=\sum_{k=0}^n\binom{n}{k}p^k(1-p)^{n-k} \delta_k
$$
where $\delta_k$ is the Dirac delta function.
I see that the result is the same, because $\delta_k$ nullifies each not needed addend. Why this verbosity? Does it have a sense, that I didn't get so far?
Thanks for any feedback!
Comment: Rather than a function, each $\delta_k$ is a (probability) measure (as $P_{n,p}$).
Comment: Could you be more specific about where you saw this notation?  Also, in your second equation, the right hand side is a constant independent of $k$ since $k$ is a dummy variable. Can you double check that equation?
Comment: @Srivatsan: There was a typo, sorry. It is script of a german professor. I'll give the link anyway. [You can find the notation in this pdf](http://www-wt.iam.uni-bonn.de/~ferrari/Lectures/WS11ProbaI/wt.pdf) on page 44.
Comment: After the recent edits: Now I see the intended meaning. $\delta_k$ is not a variable as I assumed, but a function that is $1$ at $k$ and $0$ everywhere else. This is mostly for notational convenience; also manipulating algebraic expressions becomes easier using the second notation as compared to the first.
Answer: The Wikipedia page considers a discrete probability distribution defined on the natural numbers. The use of the Dirac measure $\delta_k$ suggests that a probability density function of a continuous random variable is defined. In the latter setting the former definition would not do, because $\tbinom nk$ can be given a non-zero meaning at non-integral $k$ using the Beta function (or using the Gamma function if you prefer), and this would not be the right thing for getting a probability distribution.
Answer: As Didier Piau hinted, the first expression is a density function for your random variable (implicitely distributed on the integers), while the second expression is the law of your random variable.
Answer: Here $\delta_k$ is a set-function defined such that for any $A \subseteq \mathbb{N}$,
$$\delta_k(A) = \left\{ \begin{gathered}
  {1} \quad{\text{if}}\quad k \in A \\
  {0} \quad{\text{if}}\quad k \notin A \\
\end{gathered} \right.$$
i.e., expressed as an Iverson bracket, $\delta_k(A) = [k \in A]$.
Thus, the probability measure $P_{n,p}$ is such that for any event $A \subseteq \mathbb{N}$,
$$
P_{n,p}(A) = \sum_{k=0}^n\binom{n}{k}p^k(1-p)^{n-k} \delta_k(A) = \sum_{k \in \{0,1,\cdots,n\}\cap A} \binom{n}{k}p^k(1-p)^{n-k}
$$


Is there a reason for "one set full out" strategy during deadlift for reps event in strongman competitions?

Question: I have seen a few records of "deadlift for reps" event in various strongman competitions and it seems that they do an all-out first set quite often, no matter how much time left till time limit. This is going against common sense, experience, observations of other sports, and any theory I can relate to this subject.
It seems that it is quite common for them to start with an all-out set and get exhausted far from the time limit - for example 6 fast reps in 30 seconds and no successful rep (or at least try) in the next 30 seconds.
See for example:

If am correct, there is not a single one competitor using evenly spaced sets of one rep (in records I have seen). This lack of timing discipline seem to be really irrational in those professional athletes. My question:
Is there a reason for this unusual strategy?
The possible hypothesis to explain this behaviour I already reject:

Their body works in a different way (I have not found any reason why it should be like that). Even though they could have superior genetics and use various drugs and have decades of training, they are still humans obeying the laws of this universe.

They do not really know what they are doing - I do not think this is possible, they are professionals, they should know that 60 seconds is way too much time for all-out set.

The only hypothesis that seems to be somehow possible:

They are avoiding doing too much work/reps (via resting between reps) to preserve energy for other events/days of the competition.
Answer: Your hypothesis about the strongmen conserving energy is certainly one part of it. A few times in World's Strongest Man, I've seen a competitor do just enough reps to take the lead, and then just put the bar down and walk away even though they could probably do more. They would also be reducing their risk of injury, by not straining themselves for more reps.
But the main factor in this, at least in my opinion, is that if two strongmen tie for repetitions, whoever completed their reps in the fastest time wins. So if one strongman paces himself as you suggest and does 6 reps just inside the time limit, and another strongman goes all-out and does 6 reps in 30 seconds, the one who went all-out will win. The first strongman would have been better off going all-out too, and seeing if he could get 7 reps.
Comment: The second paragraph is truly interesting. I have not thought about that in this way.


Delegate methods not being called/ChildViewController somehow ending up nil

Question: I'm new to delegation, so I've been looking for answers, and I've looked at method delegates doesn't get called and Delegate method not being called to see if my answer would be there.  I've also looked at How do I set up a simple delegate to communicate between two view controllers? for a brief rundown of delegates and have done my best to follow it correctly.  I have been checking my code and I thought I doing it right, but in my debugging, I've learned that I'm clearly not.
What I want to do is reload a tableView from the file "Data.plist" (stored in the Documents directory) when a user segues back to the parent ViewController (the user has just added a new value to the dictionary).  The app loads the new entered correctly upon reopening, so I know that file is being saved correctly.
This is my ParentViewController.h file.
#import <UIKit/UIKit.h>
#import "ChildViewController.h"

@interface ParentViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource, ChildViewControllerDelegate>

@end

This is my ParentViewController.m file.
#import "ParentViewController.h"

@interface ParentViewController ()
@end

@implementation ParentViewController
-(void)addEvent {
    NSLog(@"We are before [self loadNewEvent];");
    [self loadNewEvent];
    NSLog(@"We are after [self loadNewEvent];");
}

-(void)loadNewEvent {
    [self.tableView scrollToRowAtIndexPath:0 atScrollPosition:UITableViewScrollPositionNone animated:YES];
    [self.tableView reloadRowsAtIndexPaths:0 withRowAnimation:UITableViewRowAnimationLeft];
    //[self.tableView reloadData];//This doesn't seem to do anything but leave the tableview blank when this line is in viewDidLoad and viewWillAppear.
    NSLog(@"WHY IS THIS NOT WORKING?!?!");
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //stuff that loads data initially into tableView
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //cell formatting stuff
    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"addEvent"]) {
        [(ChildViewController *)[[segue destinationViewController] topViewController] setFilePath:filePath];
        ChildViewController *detailViewController = [[ChildViewController alloc] init];
        [detailViewController setDelegate:self];
        //[self.navigationController pushViewController:detailViewController animated:YES];
    }
}
@end

This is my ChildViewController.h
#import <UIKit/UIKit.h>

@protocol ChildViewControllerDelegate;

@interface ChildViewController : UIViewController
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;
- (IBAction)dismissAndSave:(id)sender;//in implementation
- (IBAction)dismissCancel:(id)sender;//in implementation
@end

@protocol ChildViewControllerDelegate <NSObject>
-(void)addEvent;
@end

and finally my ChildViewController.m file.
#import "ChildViewController.h"
@interface ChildViewController ()
@end

@implementation ChildViewController
- (IBAction)dismissAndSave:(id)sender {
    //perform file-saving operations
    if ([self.delegate respondsToSelector:@selector(addEvent)]) {
        [self.delegate addEvent];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end

I've run through and debugged, and the last point where the ChildViewController is not nil is at the [detailViewController setDelegate:self]; line in the parent's prepareForSegue method.
The reason I knew my delegate methods weren't being called was because NSLog(@"We are before [self loadNewEvent];"); was not happening.
In addition to the method not being called, when I try to do a [self.tableView reloadData]; in the addEvent delegate method, everything appears blank.
Thank you in advance for your help; you are doing a great service to a student who is teaching himself the ways of iOS programming and Objective-C!
Comment: is it stepping into the if for respondsToSelector?
Comment: I have a feeling your "`self.tableview`" IBOutlet property is not connected.  Heck, I don't even see it declared in your .h "`@interface`" file.
Comment: @Ben Avery, I just added a `NSLog(@"We are inside dismissAndSave respondsToSelector");` line inside of the if statement, and it didn't print out.  That's probably where the issue is. @Michael Dautermann I didn't think I needed one since the information loads on launch without one.  If I need one, how do I set it up without breaking my existing tableView?
Comment: Just before the if respondsToSelector, is delegate = nil?
Comment: delegate is set to 0x0
Answer: Expanding on my comment, I believe you need to declare a tableview property in your .h file:
e.g.
@property (strong) IBOutlet UITableView *myTableView;

which, once connected to the actual table view in your Storyboard or XIB, you can then reference in your .m file like this:
[self.myTableView reloadData];

Comment: I added both to my code, but I put the `[self.myTableView reloadData];` into my viewWillAppear method but no luck.  Did I put it in the wrong method?
Comment: did you connect your tableview in your storyboard to your new "`myTableView`" outlet in your view controller?
Comment: Yep.  There was a blue box around the whole thing.
Comment: oh and you need to set your data source for your tableview object in your storyboard back to your view controller, so it knows where to draw the data from.
Comment: The ParentViewController is currently the dataSource and delegate, and the myTableView is a "Reference Outlet".  Still doesn't seem to reload the data.  Am I putting the call in the wrong spot or do I have myTableView hooked up to the wrong place?
Comment: Another method you are missing is the *required* datasource one named ["`tableView:numberOfRowsInSection:`"](https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDataSource/tableView:numberOfRowsInSection:).  Can you implement that?
Comment: I figured the reload issue out.  Thanks!!  I was putting the line in the viewWillAppear method instead of viewDidAppear.  Now I know what the differences are.  However, I still don't have the delegation working, but as long as it refreshes, I'm happy.  It's probably a more standard practice to use delegation though...so I should still find out why that's not working.
Answer: It looks like you're allocating a new view controller, setting its delegate and then don't do anything with it.  It'll get dealloc'd once it is out of scope.
[(ChildViewController *)[[segue destinationViewController] topViewController] setFilePath:filePath];
ChildViewController *detailViewController = [[ChildViewController alloc] init];
[detailViewController setDelegate:self];

Try something like this...
ChildViewController * detailViewController = (id)[segue destinationViewController];
[detailViewController setDelegate:self];

Comment: What do I do about the filePath parameter?


cálculo de porcentagem jquery

Question: Tenho este código e coloquei no jsfiddle  para facilitar a compreensão
http://jsfiddle.net/opeta/L7e73zx2/
Ele faz um cálculo de porcentagens somando no valor do preço da compra e coloca o resultado no preço da venda.
ele funciona se eu colocar um número inteiro no preço de compra, mas em toda a aplicação eu uso o maskmoney e faço cálculos com ele, ficando inviável eu retirar esta máscara.
alguém pode me ajudar nesta questão?
Comment: Qual deveria ser a fórmula do calculo? `Exp: PC + (CE * 0,2) + ST + (IPI * 0,5)`
Comment: seria PV = (PC * CE / 100) + (PC * ST / 100) + (PC * IPI / 100)
Comment: @opeta Eu não entendi a sua dúvida, seja mais claro.
Answer: opeta, tenta fazer assim:
P.S.: o $.fn.val é um workaround para poder setar o valor do input apos aplicar a mascara.

var originalVal = $.fn.val;
$.fn.val = function(value) {
    if (typeof value == 'undefined') {
        return originalVal.call(this);
    } else {
        setTimeout(function() {
            this.trigger('mask.maskMoney');
        }.bind(this), 100);
        return originalVal.call(this, value);
    }
};

function calcular(event)
{
    var inputs = {
        precoCompra: $('#precoCompra'),
        custoempresa: $('#custoempresa'),
        st: $('#st'),
        ipi: $('#ipi'),
        precoVenda: $('#precoVenda')
    };
    var valores  = {
        precoCompra: parseFloat(inputs.precoCompra.val()),
        custoempresa: parseFloat(inputs.custoempresa.val()),
        st: parseFloat(inputs.st.val()),
        ipi: parseFloat(inputs.ipi.val()),
        precoVenda: 0.0
    };

    valores.custoempresa = isNaN(valores.custoempresa) ? 0.0 : valores.precoCompra * (valores.custoempresa / 100);
    valores.st = isNaN(valores.st) ? 0.0 : valores.precoCompra * (valores.st / 100);
    valores.ipi = isNaN(valores.ipi) ? 0.0 : valores.precoCompra * (valores.ipi / 100);

    valores.precoVenda = valores.precoCompra + valores.custoempresa + valores.st + valores.ipi;
    inputs.precoVenda.val(valores.precoVenda.toFixed(2));
}

$(document).ready(function(){
    var inputs = $(".money").maskMoney();

    var inputs = $("input[name='custoempresa'], input[name='st'], input[name='ipi'], input[name='precoCompra']");
    inputs.on({
        //keypress: calcular,
        keyup: calcular,
        //keydown: calcular,
    });
});

    Preço de Compra*

        <input id="precoCompra" class="money" type="text" name="precoCompra" value=""  />

    Custo Empresa*

        <input id="custoempresa" type="text" name="custoempresa" value=""  />

    Subs. Tributária*

        <input id="st" type="text" name="st" value=""  />

    IPI*

        <input id="ipi" type="text" name="ipi" value=""  />

    Preço de Venda*

        <input id="precoVenda" class="money" type="text" name="precoVenda" value=""  />

Comment: aqui esta dando certo mais quando jogo na aplicação por algum motivo ta duplicando os número. se digito 33 no preço de compra fica 33.33 :(
Comment: descobri o motivo e já corrigi, muito obrigado pela sua ajuda.
Answer: Bom, segue minha versão do seu código(tava terminando de montar quando o @Toby postou a resposta rs)
Acredito que o mais fácil seria utilizar o evento onkeyup para receber os valores dos inputs, você pode realizar a conta de forma direta:
  var PV = (PC * CE / 100) + (PC * ST / 100) + (PC * IPI / 100);

(function($) {
  $("#precoCompra").maskMoney({thousands:'', decimal:'.', allowZero:true, suffix: ' R$'});
  $("#custoempresa").maskMoney({thousands:'', decimal:'.', allowZero:true, suffix: ' R$'});
  $("#st").maskMoney({thousands:'', decimal:'.', allowZero:true, suffix: ' R$'});
  $("#ipi").maskMoney({thousands:'', decimal:'.', allowZero:true, suffix: ' R$'});
})(jQuery);

function calcular(){
  var PC = $("#precoCompra").val().substring(0, $("#precoCompra").val().length-2);
  var CE = $("#custoempresa").val().substring(0, $("#custoempresa").val().length-2);
  var ST = $("#st").val().substring(0, $("#st").val().length-2);
  var IPI = $("#ipi").val().substring(0, $("#ipi").val().length-2);
  console.log(PC,CE,ST,IPI);
  var PV = (PC * CE / 100) + (PC * ST / 100) + (PC * IPI / 100);
  $("#precoVenda").html("R$ "+PV);
}

Preço de Compra*
<input id="precoCompra" class="money" type="text" name="precoCompra" onkeyup="calcular()"/>

Custo Empresa*
<input id="custoempresa" type="text" name="custoempresa" onkeyup="calcular()"/>

Subs. Tributária*
<input id="st" type="text" name="st" onkeyup="calcular()"/>

IPI*
<input id="ipi" type="text" name="ipi" onkeyup="calcular()"/>

Preço de Venda:

cálculo de porcentagem jquery


How (in)secure are cell phones in reality?

Question: I was recently re-reading an old Wired article about the Kaminsky DNS Vulnerability and the story behind it.
In this article there was a quote that came across a little bit exaggerated to me:

"The first thing I want to say to
  you," Vixie told Kaminsky, trying to
  contain the flood of feeling, "is
  never, ever repeat what you just told
  me over a cell phone."
Vixie knew how easy it was to
  eavesdrop on a cell signal, and he had
  heard enough to know that he was
  facing a problem of global
  significance. If the information were
  intercepted by the wrong people, the
  wired world could be held ransom.
  Hackers could wreak havoc. Billions of
  dollars were at stake, and Vixie
  wasn't going to take any risks.

When reading this I could not help but feel like it was a bit blown-up and theatrical. Now, I know absolutely nothing about cell phones and the security problems involved, but to my understanding, cell phone security has quite improved over the past few years.
So my question is: how insecure are cell phones in reality? Are there any good articles that dig a bit deeper into this matter?
Comment: As with most systems, a targeted attack by people who know what they're looking for generally will be successful, and in *drastically* less time than you'd think. If you are a very high risk target, you should be very paranoid. Most people aren't nearly as much a target as they'd like to think, and thus don't need to be very worried.
Answer: I'd recommmend reading this from slashdot:  GSM Decryption Published. Following the links in the article and reading the comments.
more info at  A5/1 Security Project aims at publicizing cryptographic weaknesses found in today's cellular networks


Not getting all lines from a text file when using getline() in C++

Question: I was given a homework assignment to generate a txt file containing a random number of lines, each with a random amount of integers, ranging between a minimum value and a maximum value. Lots of rand() fun.
In any case, that was the easy part. The second part of the problem is to read over the first file and create a second file that contains some statistics, such as: the sum of all integers in the file, their average, min and max values, and my main issue: the sum of all integers in each line.
I have written the following code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cmath>
using namespace std;

int main()
{
        string newLine;
        stringstream ss;
        int newInput = 0, oldInput = 0;
        int lineSum = 0;
        int lineCounter = 0;
        int allSum = 0;
        int intCounter = 0;
        double averageOfAll = 0;
        int minInt = 0;
        int maxInt = 0;

.... // generating the first file. No issues here.
ifstream readFile;
readFile.open("inputFile.txt");

ofstream statFile;
statFile.open("stat.txt");

if(readFile.is_open()) {
        while (getline(readFile, newLine)) {    //my problem should be somewhere
                                                //around here...
                ss.str("");
                ss << newLine;
                while(!ss.eof()) {
                        oldInput = newInput;
                        ss >> newInput;

                        cout << newInput << endl;
                        lineSum += newInput;
                        allSum += newInput;
                        intCounter++;
                        minInt = min(oldInput, newInput);
                        maxInt = max(oldInput, newInput);
                }

                lineCounter++;
                statFile << "The sum of all integers in line " << lineCounter
                << " is: " << lineSum << endl;
                lineSum = 0;
        }

        readFile.close();

        averageOfAll = static_cast<double>(allSum)/intCounter;

        statFile << endl << endl << "The sum of all integers in the whole file: "
        << allSum;
        statFile << endl << "The average of value of the whole stream of numbers: "
        << averageOfAll;
        statFile << endl << "The minimum integer in the input file: "
        << minInt;
        statFile << endl << "The maximum integer in the input file: "
        << maxInt;
        statFile << endl << endl << "End of file\n";

} else
        cout << endl << "ERROR: Unable to open file.\n";

statFile.close();

return 0;
}

When running the program, it seems like my loops do iterate over all the lines in the file. However, they only collect the integers from the first line, and the rest remains 0.
I would post screenshots of my outputs, but I do not have enough rep :(
can anyone help out?

It worked!
inputFile.txt ^

statFile.txt (my output) ^
And like P0W and James Kanze suggested, it was a flag issue and a misuse of my streamstring. I corrected my code as follows:
.
.
.
 while (getline(readFile, newLine)) {
                    stringstream ss(newLine);

                    while(ss >> newInput) {

                            lineSum += newInput;
                            allSum += newInput;
                            intCounter++;
                            minInt = min(minInt, newInput);
                            maxInt = max(maxInt, newInput);
                    }
.
.
.

Thank you all!
Comment: You might add c++ to the subject list.  A lot people probably don't follow the more precise labels (or even know that they exist).
Comment: Just did, JGrice suggested an edit that I accepted :)
Thank you all
Answer: You can try following for your inner while loop
ss << newLine;

while( ss >> newInput )
{
  //.... Your logic,
 // might need little update

  oldInput = newInput;
}

ss.clear( ); // clear the flags !

Comment: @GilDekel It's almost certainly a flag issue, but a stream has a lot more flags than you'd imagine, and `clear()` only resets the error flags.  Unless you really know what you're doing, and have a performance problem, don't try to reuse a stream; just create a new one.
Comment: Oh, so it might be a flag issue? because it was not cleared for the next iteration??
Answer: There are several issues, but the main one is that you're trying
to reuse ss (which should properly be an
std::istringstream).  It's possible to do so, but it's fairly
difficult to get right, since streams hold a lot of state which
needs reinitializing.  (In this case, the stream memorizes that
it has seen end of file, and doesn't do anything else until that
has been reset.)  Your loop should look like:
while ( getline( readFile, newLine ) ) {
    std::istringstream ss( newLine );
    //  ...
}

And once you've got the std::istringstream, you don't want to
loop until eof (which may or may not be set after the last
successful input); you want to loop until an input fails.
(After the input fails, you may want to check eof: if it
isn't set, the input failed because of a format error in the
line; e.g. someone entered "abc" instead of an integer.)


Android tutorial (first) app crashed

Question: Stuck on myfirstapp tutorial.
So, app crashed after button was clicked.
There are a few answered question here(stackoverflow) but in my case error is:
"Unable to find explicit activity class {com.murr.mid.clanscript/com.mid.test.MainActivity$DisplayMessageActivity}; have you declared this activity in your AndroidManifest.xml?"
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"/>
    </activity>
</application>

Can't get it, why it ask for MainActivity$DisplayMessageActivity ?
More code:

public class MainActivity extends ActionBarActivity. Method binded to button onClick

public void sendMessage(View view) {

    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText et = (EditText) findViewById(R.id.edit_message);
    String msg = et.getText().toString();
    intent.putExtra(EXTRA_MSG, msg);
    startActivity(intent);
}

//public class DisplayMessageActivity extends ActionBarActivity.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Intent intent = getIntent();
    //String message = intent.getStringExtra(MainActivity.EXTRA_MSG);
}

Comment: hmmm http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html ... activity classes should not be nested ... (ok they can ... but then they should be public static ... and name in manifest should be `.MainActivity$DisplayMessageActivity`)
Comment: Where are you declaring DisplayMessageActivity??? same file or separate file?
Comment: separated http://puu.sh/eJCAV/3d3543c360.png
Answer: You are not defining a package in your manifest making it unable to find your MainActivity class.
Read about Android Manifest here, specially the Defining Class Names paragraph.
Answer: Try to change your AndroidManifest.xml to
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.murr.mid.clanscript" >
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"/>
    </activity>
</application>
</manifest>

Answer: Solved. Thanks to Selvin and his comment to my question.
So, I have a bad habit to play around tutorial and run the code before read to the end.
In the tutorial we have a code:
Intent intent = new Intent(this, DisplayMessageActivity.class);

and this code generates error, because we have no DisplayMessageActivity defined yet. I add this class to MainActivity file. And forgot about it.
Do not do like me. Read tutorials to the end :)
Thank for your attention, guys.

Android tutorial (first) app crashed


Homework problem. What is the answer supposed to look like?

Question: I am taking a statistics course this semester, and this is part of our first homework assignment, only I don't know what the answer is even supposed to look like.

When the process is functioning correctly, the adhesive strength X is
  normally distributed with a mean of 200 N and a standard deviation of
  10 N. Each hour, you make one measurement of the adhesive strength.
  You are supposed to inform your supervisor if your measurement
  indicates that the process has strayed from its target distribution.
a. Find P(X ≥ 203), under the assumption that the process is
  functioning correctly.
b. Based on your answer to part (a), if the process is functioning
  correctly, would a strength of 203 N be unusually large? Explain.
c. If you observed an adhesive strength of 203 N, would this be
  convincing evidence that the process was no longer functioning
  correctly? Explain.

Just to be clear, I don't necessarily need the answer, just what the answer would look like. I have no idea what Find P(X ≥ 203) means really. Thanks.
Comment: Here's a hint. X is random variable with known properties. You are asked what is the probability that X exceeds 203. Intuitively, X tends to hover around 200, so the probability that X is slightly greater than the mean of 200 should be a bit less than one half.
Answer: You are given a normally distributed attribute X with a known mean and standard deviation. As you may already know, the area under the normal curve is one (unity). By P(x ≥ 203), you are asked the area under the curve to the right of x=203. To determine that, calculate the number of standard deviation units x=203 lies above the mean (i.e., the z-score). Then from a z-table, you can read the area under the curve above the z-score you calculated which is the area to the right of x=203. That is p(x≥203).


Java Graphics2D to erase to a alpha background

Question: I'm making an application that has a drawing board where you draw with your mouse, it draws ontop of an Label in a BUfferedImage. What I'm trying to implement right now is an eraser, the problem is I cannot find anywhere help to make an eraser to clearRect() to an alpha background. (I cannot have a defined color background since the user can change the background to any image he wants). To sum up:

How can you erase/overwrite Graphics2D pixels with alpha pixels? The way i found was with clearRect but you need to specify a background color.

The following is my DrawBoard class which constains everything to draw.
<code>public class DrawBoard extends JPanel implements MouseListener, MouseMotionListener{

public JLabel status;
private JLabel imgLabel; // this is where the drawing happens
public Point pstart, pfinish;
private List<Point> points = new ArrayList<Point>();
private List<BufferedImage> lines = new ArrayList<BufferedImage>();

private static final int BI_WIDTH = 1024;
private static final int BI_HEIGHT = 800;
private static int STROKESIZE = 7;

private BufferedImage bImage = new BufferedImage(BI_WIDTH, BI_HEIGHT,
        BufferedImage.TYPE_INT_ARGB);

public Color currentColor;

public static boolean eraser = false;

private int xX1, yY1;

public DrawBoard(){

   Graphics2D g2d = bImage.createGraphics();
   g2d.dispose();

    Dimension size = getPreferredSize();
    size.setSize(1024,800); //w, h
    setPreferredSize(size);
    //status =  new JLabel("default");
    //add(status, BorderLayout.SOUTH);
    addMouseListener(this);
    addMouseMotionListener(this);

     imgLabel = new JLabel(new ImageIcon(bImage)) {
     @Override
     protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        paintInLabel(g);
     }
   };
     imgLabel.setOpaque(false);
     setOpaque(false);
      add(imgLabel, BorderLayout.CENTER);

}

private void paintInLabel(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  g2d.setColor(getColor()); // this colour is when mouse is pressed
  g2d.setStroke(new BasicStroke(STROKESIZE));
  if (points.size() < 2) {
     return;
  }
  for (int i = 1; i < points.size(); i++) {
     int x1 = points.get(i - 1).x;
     int y1 = points.get(i - 1).y;
     int x2 = points.get(i).x;
     int y2 = points.get(i).y;
     g2d.drawLine(x1, y1, x2, y2);
  }
 }

@Override
public void mouseExited(MouseEvent e){
}

@Override
public void mouseEntered(MouseEvent e){
}

@Override
public void mouseMoved(MouseEvent e){
}

// Where the drawing happens
@Override
public void mousePressed(MouseEvent e) {
    //status.setText("you pressed down the mouse");
    xX1 = e.getX();
    yY1 = e.getY();

        points.add(e.getPoint());
}

@Override
public void mouseDragged(MouseEvent e) {
  //status.setText("you draged the mouse");
        points.add(e.getPoint());
        imgLabel.repaint();

}

@Override
public void mouseReleased(MouseEvent e) {
    //status.setText("you release the mouse click");
    Graphics2D g2d = bImage.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setColor(getColor()); // this is the final colour
    g2d.setStroke(new BasicStroke(STROKESIZE));

     if (points.size() >= 2) {
        for (int i = 1; i < points.size(); i++) {
           int x1 = points.get(i - 1).x;
           int y1 = points.get(i - 1).y;
           int x2 = points.get(i).x;
           int y2 = points.get(i).y;
           g2d.drawLine(x1, y1, x2, y2);
        }
     }
     g2d.dispose();

     points.clear();
     imgLabel.repaint();

}
// End of where the drawing happens

public void clearDrawBoard() {

}

private Color getColor() {

    return ColourToolbar.selectedColor;
}

private void setColor(Color col){

    this.currentColor = col;
}

@Override
public void mouseClicked(MouseEvent e) {
    //throw new UnsupportedOperationException("Not supported yet.");
}

}
</code>
Comment: Did you already try `g2d.setColor(new Color(0, 0, 0, 0))` and then 'fillRect'?
Answer: You should set a custom Composite for your Graphics2D, specifically AlphaComposite.Clear before drawing the rectangle. Don't forget to reset the composite to the default (SRC_OVER) when you are done, because the same Graphics object will be reused to paint other components.
Comment: The answer could do with some example code, from here it isn't clear how to reset to SRC_OVER, as AlphaComposite.Clear and SRC_OVER are different types. You in fact want to set it back to AlphaComposite.SrcOver.
Comment: This definitely did the job, I lost hope since I read last night that you couldn't overwrite with alpha pixels, but now it works like a charm! Thanks so much and hopefully people looking for this will get help from this answer!