La campanella: How to play the D sharp and G (left hand)

Question:
How do you play the D sharp and the G (F double sharp) with your left hand at the same time? Thats just not possible if you dont have a big hand right?
(I am not sure why the picture is tilted at a weird angle)
Comment: It's "only" a tenth, and made easier because the D sharp is a black key with two white keys next to it, so there is nothing to get in the way of your pinky finger. If your hand is too small, just break (roll) the chord. Liszt often assumes the performer can reach a 10th. If your hands are too small, best to choose another composer!
Comment: If you've never encountered a wide interval before, you're not ready to play this piece.
Comment: @MattPutnam I usually even see professional pianists who cant play this HARMONIC  interval, so they roll the chord. This piece requires a good technique, not just a big hand.
Comment: Well, I don't consider I have "really big" hands, but that 10th is no problem. But there are several things that *might* be wrong with your technique that make it "impossible" even if your hands are big enough. Looking at the videos you posted in your question about Chopin Op 10 no 11 https://music.stackexchange.com/questions/67142/how-to-play-chopin-etude-op-10-no-11, there's probably nothing that 6 or 12 months work with a good teacher wouldn't fix IMO... (your hand position is **completely** wrong for any sort of advanced playing, for a start!)
Comment: @alephzero Can you play the D# and G at the same time (harmonically), I have no problems with playing huge intervals melodically
Comment: @Stallmp Yes. That's what I said in the first comment.
Answer: We can't see what you are doing when you try to play this, so it's a guess, but the videos you posted in this question looks as if your hand position is completely wrong there, so it's probably wrong here as well.
You need to get your hand higher so your fingers and aiming down onto the keys, not aiming sideways or at the end of the keys. Possibly your sitting position is too low (by several inches) for the keyboard you are playing, and you are sitting at the wrong distance away the keyboard as well.
Also, you want to make the distance between the notes as small as possible. If your pinky is positioned properly on top of the D sharp (not trying to reach in from the side) then the "shortest straight line" to the F double sharp means your thumb should be playing the note right next to the black keys, or even slightly in between the F sharp and G sharp keys - but not so far in between that the black keys are getting in the way, of course.
Three bars after the chord you posted, it occurs again with an extra C sharp (i.e. three notes of D#7) and to keep the same hand position, you want to play that note with either 2 or 3, right at the back of the C sharp key.
If that seems very unnatural, you really need to back off from trying to play pieces like this until you have got your hand positions right in very simple music. There are plenty of youtube videos showing piano hand position. Even better, get a teacher to help sort out the basics of your technique.
One of the big problems of self-taught players is that you can "sort of" play simple music with just about any hand position, however terrible it is, and by the time it matters that you are doing it right, doing it wrong has become a deep-rooted habit. If you want to progress, you have to break that habit somehow.
An easy way to get your hand in the right position is to start by practicing a B major scale. With your 2 3 4 fingers on the black notes, your thumb and pinky will naturally want to be on top of the white notes. If you start with C major, it's all to easy to have your hand too low and all your fingers poking forwards towards the extreme end of the white keys, not sitting on top of the keys and moving down.
Comment: Thank you very much for your advice, but one thing though. The issue here is that my hand is simply not big enough to play the D sharp and F double sharp at the same time, so I have to roll the chord right?
Comment: And also, I have been taught that your arm should be just a bit higher than the keyboard. Is this true?
Comment: "So I have to roll the chord right" - Right, you can't do anything else, but if your hand position is like the Chopin videos, you won't be able to roll it fast.  "Your arm should be just a bit higher than the keyboard" - Well, it depends what you call "just a bit". I reckon the underside of my wrist in normal playing is about 2 inches higher than the keys, and my arm is level or slopes slightly *down* from elbow to wrist. Basically, you want everything, from your shoulders downwards, to have room to move around freely, not be "cramped up" and tense.


Choose Function Through Metaprogramming

Question: Assume the following two functions may or may not be provided by the user:
void foo(int) { std::cout << "foo int" << std::endl; }
void foo() { std::cout << "foo void" << std::endl; }

In my implementation, I want to call foo(int) if the user defined it, and foo() otherwise. This can be done as follows:
template<class Int> auto call_foo(Int i) -> decltype(foo(i)) { return foo(i); }
template<class... Int> void call_foo(Int... i) { return foo(); }

If, however, we want to do the opposite, i.e. prefer foo() over foo(int), the following naive attempt does not work.
template<class Int> auto call_foo(Int i) -> decltype(foo()) { return foo(); }
template<class... Int> void call_foo(Int... i) { return foo(i...); }

The problem is that decltype(foo()) does not depend on Int, so the possible non-existence of foo() does not result in SFINAE.
A possible solution is to require the user to define either of
void foo(int, void*) { std::cout << "foo int" << std::endl; }
void foo(void*) { std::cout << "foo void" << std::endl; }

Like this, we always have a parameter of foo on which we can do the "template vs. parameter-pack" trick. While this technically solves the problem, it's quite ugly as it requires the user to take an additional parameter whose meaning might not be obvious to him/her. So is there a way to achieve the same effect without the additional parameter?
Answer: No need for SFINAE. Just standard overload resolution is sufficient.
void call_func(void (*f)(), int) { f(); } // #1

template<class = void>
void call_func(void (*f)(int), int x) { f(x); } // #2

call_func(foo, 1); // #1 is preferred if viable. All others being equal,
                   // non-templates are preferred over templates

Comment: You may use *tag inheritance* to order multiple overload (and avoid template).
Comment: +1. Although I was hoping to see a nice TMP solution which would work for a user specified precedence. For example, if he has `N` `foo`'s which all take the corresponding number of `int`s, and the user wants to specify some permutation of `{1,...,N}` as the precedence order. Of course, I don't see any practical significance. Just that it would lead to some interesting code :)
Comment: Your solution is perfect for the situation I described in the question. Unfortunately, in the actual code I have more than two functions and not all of them have the same name. Then, you do need SFINAE to rule out the non-existing names.
Comment: @Pradhan You find something in that direction here: http://stackoverflow.com/questions/26176516/choose-best-available-function-through-tag-inheritance
Answer: Following may help:
template<typename ... Ts> void foo(Ts...) = delete;
void foo(int) { std::cout << "foo int" << std::endl; }
//void foo() { std::cout << "foo void" << std::endl; }

namespace detail
{

struct overload_priority_low {};
struct overload_priority_high : overload_priority_low{};

template <typename Int>
auto call_foo(Int i, overload_priority_low) -> decltype(foo(i)) { return foo(i); }

template <typename Int>
auto call_foo(Int , overload_priority_high) -> decltype(sizeof(Int), foo()) { return foo(); }

}

void call_foo(int i)
{
    return detail::call_foo(i, detail::overload_priority_high{});
}

Live example.
Comment: Very useful trick, this tag inheritance. I cleaned your code up here: http://stackoverflow.com/questions/26176516/choose-best-available-function-through-tag-inheritance
Comment: @MarcoA.: Removing the `=delete` seems to fix the error with clang.

Choose Function Through Metaprogramming


When to use TouchableNativeFeedback, TouchableHighlight or TouchableOpacity?

Question: In React Native, there are at least three ways to make a button: TouchableNativeFeedback, TouchableHighlight and TouchableOpacity. There is also TouchableWithoutFeedback, which the documentation clearly states you should not use because "all the elements that respond to press should have a visual feedback when touched".

TouchableNativeFeedback is Android only and "replaces the View with another instance of RCTView"
TouchableHighlight "adds a view to the view hierarchy"
TouchableOpacity works "without changing the view hierarchy"

Are there any other significant differences between the three? Is one of them the goto component? In what case should you use TouchableHighlight over TouchableOpacity? Are there any performance implications?
I am writing an application right now, and find that all three have a significant delay between tap and the action (in this case a navigation change). Is there any way to make it snappier?
Comment: As far as snappiness is concerned... outputting anything to console.log slows down scene transitions considerably. I'm just getting started in react native and was somewhat un-impressed of the speed while developing my first components. I removed all console.log commands (including disabling redux logger) and built for release target and the speed blew me away. This is coming from developing Cordova apps.
Answer: source: https://medium.com/differential/better-cross-platform-react-native-components-cb8aadeba472, by Nick Wientge
TouchableHighlight
• What it does: Darkens or lightens the background of the element when pressed.
• When to use it: On iOS for touchable elements or buttons that have a solid shape or background, and on ListView items.
TouchableOpacity
• What it does: Lightens the opacity of the entire element when pressed.
• When to use it: On iOS for touchable elements that are standalone text or icons with no background color.
TouchableNativeFeedback
• What it does: Adds a ripple effect to the background when pressed.
• When to use it: On Android for almost all touchable elements.
Comment: when using TouchableNativeFeedback, it has this square background (i dont mean ripple) How do we customize that (e.g. increase its size, make it round, or maybe remove it and just have ripple alone) ?
Comment: Thank you! I had read this article since, but couldn't find it anymore to answer my own question. It is exactly what I was looking for.
Answer: Well, This is how I typically decide what to use:

If I'm building for Android-only, and the component is large enough that the native feedback will be visibly different than using the others then I use TouchableNativeFeedback
If I want to control the opacity on the component or I want the button to have color when touched, and I don't want to control the focused state of some element inside the Touchable, then I use TouchableHighlight. (TouchableOpacity has got some weird parts when you control opacity yourself).
In all other cases, I use TouchableOpacity because it's more "bare" than TouchableHighlight
Comment: This answer is a helpful start… but I was hoping to find more solid technical and/or design related reasons for why to use one vs another.
Answer: I think the main essential difference as stated in Docs:
TouchableHighlight must have one child (not zero or more than one). If you wish to have several child components, wrap them in a View.link
TouchableHighlight

TouchableHighlight A wrapper for making views respond properly to
  touches. On press down, the opacity of the wrapped view is decreased,
  which allows the underlay color to show through, darkening or tinting
  the view.
The underlay comes from wrapping the child in a new View, which can
  affect layout, and sometimes cause unwanted visual artifacts if not
  used correctly, for example if the backgroundColor of the wrapped view
  isn't explicitly set to an opaque color.

TouchableOpacity

TouchableOpacity # A wrapper for making views respond properly to
  touches. On press down, the opacity of the wrapped view is decreased,
  dimming it.
Answer: If you want to

highlight button on press — use TouchableHighlight
change button's opacity on press — use TouchableOpacity
Comment: I think the author is aware of this a is asking for some more complex answer.
Comment: Furthermore, you can even use ``... and Facebook mixes all of those in their F8 App https://github.com/fbsamples/f8app/blob/master/js/common/F8Touchable.js


How to pass class method as an argument to another class method

Question: I'm learning C++, and I was wondering how to pass class method as an argument to another class method. Here's what I have now:
class SomeClass {
   private:
      // ...

   public:
      AnotherClass passed_func() {
          // do something
          return another_class_obj;
      }

      AnotherClassAgain some_func(AnotherClass *(func)()) {
          // do something
          return another_class_again_obj;
      }

      void here_comes_another_func() {
          some_func(&SomeClass::passed_func);
      }
};

However, this code gives error:
cannot initialize a parameter of type 'AnotherClass *(*)()' with an rvalue of type 'AnotherClass (SomeClass::*)()': different return type ('AnotherClass *' vs 'AnotherClass')

Thanks!!
Answer: The type of a member function pointer to SomeClass::passed_func is AnotherClass (SomeClass::*)(). It is not a pointer to a free function. Member function pointers need an object to be called, and special syntax (->*) :
struct AnotherClass{};
struct AnotherClassAgain{};

class SomeClass {
   private:
      // ...

   public:
      AnotherClass passed_func() {
          // do something
          return {};
      }

      AnotherClassAgain some_func(AnotherClass (SomeClass::*func)()) {
          (this->*func)();
          // do something
          return {};
      }

      void here_comes_another_func() {
          some_func(&SomeClass::passed_func);
      }
};

Comment: I got `error: expected expression` where it does `(this->*func)();`.
Comment: @bichanna compiles fine here: https://godbolt.org/z/TKa9PPW6G. Maybe you made a typo somewhere
Comment: I'm using g++, but I think you are using gcc. Could you please convert it so g++ can compile?
Comment: basically g++ is gcc (https://stackoverflow.com/questions/172587/what-is-the-difference-between-g-and-gcc). Can you show the code you tried to compile? If it is an exact copy paste of the code in my answer then something else is wrong
Comment: Oh, nvm. I got it. I tried to compile another file.


Xamarin.Android: Get filepath from CacheDir

Question: How do I get the filepath from the cache? Android: getCacheDir() / Xamarin: CacheDir. I can't find any useful information on this ...
What is meant with the 1 MB size limit? Each file or the file size of all files in the cache directory? Where should one place temporary files which exceeds that limit? On the device's internal storage?
Answer: The CacheDir property returns a Java.IO.File. This object has a property AbsolutePath that contains the path of the cache directory.
// e.g. in your activity
public class MyActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        System.Diagnostics.Debug.WriteLine(CacheDir.AbsolutePath);
    }
}

This 1MB is just an example. You can use more space. It is just a hint from google, to set a limit to yourself.
Here is a really nice answer to this question: https://stackoverflow.com/a/10069679/1489968
Comment: In wich context do you use it? I updated my example. You need to be in a scope of a `Context`, e.g. an `Activity`.
Comment: Thanks for your answer. He doesn't recognize `CacheDir`. I can't build the app.
Comment: The name `CacheDir` doesn't exist in the current context.
Comment: That's the reason. I'm implementing an interface and here I'm not in the scope of a `Context`. But I found a solution by accessing the `Context` in `MainActivity`.


66 Transaction Process id was deadlocked on resources with another processand has been chosen as the deadlock victim rerun the transaction

Question: I have the following VB Code which is inserting record in TRACK table. Also in the same time I am doing insert/update/delete in this tables CONTENT, COMNMENTRECORDED, NOTESASFILE, MASTER NOTIFICATION, DETAIL NOTIFICATION.
Dim Obj_trans As SqlTransaction = Nothing
        Dim cmd As New SqlCommand()
If objcOnn.Initialize_cOnnection = True Then

                            cmd.Connection = objcOnn.cOnn
                            Obj_trans = objcOnn.cOnn.BeginTransaction
                            cmd.Transaction = Obj_trans
  If ForwadContent(intBasketID, 0, .SubItems(3).Text, str, _                                                              intBasketID, .SubItems(2).Text, .SubItems(4).Text, "Forward", Forward, Now.TimeOfDay.ToString, _                                                                    strComments, ContentState, Ascuflag, cmd, strAttachedFile) = True Then
                                                  dset_bsktUser = obj_notification.GetBasketUser(Forward, cmd)
                                        If Not dset_bsktUser Is Nothing Then
                                            'Update the DetailNotification
                                            Dim SelUserid As String
                                            SelUserid = LoginUserID ' oLogin.ReadFromLogFile("UID")
                                            'what happen if forwarded by Administrator ?
                                            If obj_notification.UpdateDetNotification(3, CInt(lvView.Items(iSelected).SubItems(3).Text), CInt(SelUserid), 3, cmd) = True Then

                                                'Insert Into Master notification

                                                Dim id As Integer
                                                id = obj_notification.InsertMasterNotification(Forward, destibsktname, CInt(lvView.Items(iSelected).SubItems(3).Text), DocSNo, indexcardid, cmd)

                                                'now Insert the record into DetailNotification

                                                For i = 0 To dset_bsktUser.Tables(0).Rows.Count - 1
                                                    Dim userid As Integer
                                                    userid = CInt(dset_bsktUser.Tables(0).Rows(i).Item(0))
                                                    obj_notification.InsertDetailNotification(id, CInt(userid), 0, 0, cmd)
                                                Next
                                            End If
                                        End If

                                    Else
                                        TransRolloback(Obj_trans)
                                    End If
                                End With

                            End If
                            lvView.Items.RemoveAt(iSelected)
                        End If 'End Connection
                        Obj_trans.Commit()
                        objcOnn.dispOse_cOnn()

Public Function CreateDocumentTrack(ByVal Sender As Integer, ByVal IndexCard As String, ByVal DocumentNo As Integer, ByVal Status As String, B

> Blockquote

yVal SentTo As Integer, ByVal SentTime As String, ByRef cmd As SqlCommand, ByVal lstview As ListView, ByVal listFiles As ListView) As Boolean
        Dim Ds_Track As New DataSet()
        Dim Da As New SqlDataAdapter()
        Dim TrackID As Integer = 0
        Try
            If oTableInfo.Exists(TBL_TRACK, SP_CREATE_TRACK_TABLE) = False Then Exit Function

            cmd.CommandText =  "Insert into TRACK (SENDER,INDEXCARDNAME,DOCUMENTnO,STATUS,SENTTO,SENTDATE,SENTTIME,nOTEid,uSERid) VALUES(@SENDER,@INDEXCARDNAME,@sTATUS,@sENTTO,@sENTdATE,@sENTtIME,@nOTEid,@uSERid)
            With cmd.Parameters
                .Add("@sENDER, SQLDBTYPE.INT,9, "SENDER").Value = Sender
                .Add("@iNDEXCARDnAME", SQLDBTYPE.NVARCHAR,75,"iNDEXCARDNAME").Value = IndexCard
                .Add("@dOCUMENTnO",SQLDBTYPE.INT,9, "dOCUMENTnO").Value = DocumentNo
                .Add("@sTATUS", SQLDBTYPE.NVARCHAR,25, "STATUS".Value = Status
                .Add("@sENTTO", SQLDBTYPE.INT,9, "SENTTO").Value = SentTo
            End With
            cmd.ExecuteNonQuery()
            cmd.Parameters.Clear()
            'Get Inserted ID of Track

           TrackID = CInt(Ds_Track.Tables(0).Rows(0).Item(0))

            'cmd.Dispose()
            cmd.Parameters.Clear()

            'Insert into Notes corrsponcding  with inserted trckid
            'INSERT INTO CommentRecorded    (TID, RID, TrackTag, BasketID, ContentID, UserName, ComDt, DocumentSno, IndexCardName, SourceTab)  VALUES     (,,,,,,,,,)
            cmd.CommandText = "INSERT INTO CommentRecorded    (TID, RID, TrackTag, BasketID, ContentID, UserName, ComDt, DocumentSno, IndexCardName, SourceTab)  VALUES  (@TID, @RID, @TrackTag, @BasketID, @ContentID, @UserName, getDate(), @DocumentSno, @IndexCardName, @SourceTab)"
            With cmd.Parameters
                .Add("@TID", SqlDbType.Int) ' .Value = TrackID
                .Add("@RID", SqlDbType.Int)
                .Add("@TrackTag", SqlDbType.NVarChar, 100)
                .Add("@BasketID", SqlDbType.Int)
                .Add("@ContentID", SqlDbType.Int)
                .Add("@UserName", SqlDbType.NVarChar, 75)
                ' .Add("@ComDt", SqlDbType.DateTime)
                .Add("@DocumentSno", SqlDbType.Int)
                .Add("@IndexCardName", SqlDbType.NVarChar)
                .Add("@SourceTab", SqlDbType.NVarChar)

            End With
            Dim sValues() As String
            Dim i, j As Integer
            For i = 0 To lstview.Length - 1

                If Not lstview(i) Is Nothing Then
                    If Not lstview(i) = "" Then
                        sValues = Split(lstview(i), "ç")

                        With cmd.Parameters
                            .Item("@TID").Value = TrackID
                            .Item("@RID").Value = sValues(8)
                            .Item("@TrackTag").Value = sValues(1)
                            .Item("@BasketID").Value = sValues(9)
                            .Item("@ContentID").Value = System.DBNull.Value '  sValues(8)
                            .Item("@UserName").Value = sValues(4)
                            '.Item("@ComDt").Value = Format(Now.Date, "dd-MMM-yyyy")
                            .Item("@DocumentSno").Value = sValues(11)
                            .Item("@IndexCardName").Value = sValues(12)
                            .Item("@SourceTab").Value = sValues(13)

                        End With
                        cmd.ExecuteNonQuery()

                    End If

                End If
            Next
            cmd.Parameters.Clear()
            'INSERT INTO NotesAsFile    (TID, AFID, TrackTag, BasketID, ContentID, UserName, ComDt, DocumentSno, IndexCardName)  VALUES     (,,,,,,,,)
            cmd.CommandText = "INSERT INTO NotesAsFile    (TID, AFID, TrackTag, BasketID, ContentID, UserName, ComDt, DocumentSno, IndexCardName)  VALUES     (@TID, @AFID, @TrackTag, @BasketID, @ContentID, @UserName, GetDate(), @DocumentSno, @IndexCardName)"
            With cmd.Parameters
                .Add("@TID", SqlDbType.Int) ' .Value = TrackID
                .Add("@AFID", SqlDbType.Int)
                .Add("@TrackTag", SqlDbType.NVarChar, 100)
                .Add("@BasketID", SqlDbType.Int)
                .Add("@ContentID", SqlDbType.Int)
                .Add("@UserName", SqlDbType.NVarChar, 75)
                '.Add("@ComDt", SqlDbType.DateTime)
                .Add("@DocumentSno", SqlDbType.Int)
                .Add("@IndexCardName", SqlDbType.NVarChar)

            End With

            For i = 0 To listFiles.Length - 1

                If Not listFiles(i) Is Nothing Then
                    If Not listFiles(i) = "" Then
                        sValues = Split(listFiles(i), "ç")
                        If sValues(0) <> "" Then
                            With cmd.Parameters
                                .Item("@TID").Value = TrackID
                                .Item("@AFID").Value = sValues(2)
                                .Item("@TrackTag").Value = "" ' sValues(1)
                                .Item("@BasketID").Value = sValues(4)
                                .Item("@ContentID").Value = System.DBNull.Value '  sValues(8)
                                .Item("@UserName").Value = sValues(6)
                                '.Item("@ComDt").Value = Format(Now.Date, "dd-MMM-yyyy")
                                .Item("@DocumentSno").Value = sValues(7)
                                .Item("@IndexCardName").Value = sValues(8)

                            End With
                            cmd.ExecuteNonQuery()
                        End If

                    End If

                End If
            Next

            cmd.Parameters.Clear()
            CreateDocumentTrack = True

        Catch ex As Exception
            MsgBox(Err.Description, MsgBoxStyle.Information, "Rosetta")
            'oConn.DisposeConnection()
            'oMessage.DisplayException(ex.ToString)
            CreateDocumentTrack = False
        Finally
            Ds_Track.Dispose()
            Ds_Track = Nothing
            Da.Dispose()
            Da = Nothing
        End Try
    End Function

    Public Function CheckDocumentTrack(ByVal SentTo As Integer, ByVal DocumentNo As Integer, ByVal IndexCard As String, ByRef ContentState As Integer, ByRef cmd As SqlCommand) As Boolean
        Dim dset As New DataSet()
        Dim adp As New SqlDataAdapter()
        Dim count As Integer = 0
        Try
            If oTableInfo.Exists(TBL_TRACK, SP_CREATE_TRACK_TABLE) = False Then Exit Function
            'Check that this already come from the basket or not
            cmd.CommandText ="Select Count(SENTTO) FROM TRACK" where SENTTO=@SENTTO AND DOCUMENTNO=@DOCUMENTNO AND INDEXCARDNAME=@INDEXCARDNAME
            With cmd.Parameters
                .Add("@SeNTTO", SqlDbType.Int, 9, "sENTTO").Value = SentTo
                .Add"@dOCUMENTnO",SqlDbType.Int, 9, "dOCUMENTnO").Value = DocumentNo
                .Add("@iNDEXCARDNAME",SqlDbType.NVARCHAR, 75,"iNDEXCARDnAME").Value = IndexCard
            End With
            adp.SelectCommand = cmd
            adp.Fill(dset, "tRACK")
            count = dset.Tables(0).Rows(0).Item(0)
            If count > 0 Then
                ContentState = 4
            Else
                ContentState = 1
            End If

            cmd.ExecuteScalar()
            cmd.Parameters.Clear()
            Return True
        Catch ex As Exception

            oMessage.DisplayException(ex.ToString)
            Return False
        Finally
            cmd.Parameters.Clear()
            dset.Dispose()
            dset = Nothing
            adp.Dispose()
            adp = Nothing
        End Try

 Friend Function UpdateContent(ByVal approved As Integer, ByVal BasketID As Integer, ByRef cmd As SqlCommand, ByVal ContentID As String, ByVal Description As String, ByVal asu_Rec_flag As Integer, ByVal sender As Integer) As Boolean
        Try
            If oTableInfo.Exists(TBL_CONTENT, SP_CREATE_CONTENT_TABLE) = False Then Exit Function

            cmd.CommandText = "Update  CONTENT  Set BASKETID=@BASKETID, Description=@Description,Approved=@Approved,AssuReceivingFlag=@AsuReceivingFlag,FbkDate=getdate(),Sender=@Sender where ContentID=@ContentID
            With cmd.Parameters
                .Add("@BASKETID",SqlDbType.Int, 9, BasketID).Value = BasketID
                .Add("@Approved",SqlDbType.Int, 9, aPPROVED).Value = approved
                .Add"@ContentID", SqlDbType.Int, 9, CONTENTID).Value = ContentID
                .Add("@Description", SqlDbType.nvarchar, 500, dESCRIPTION).Value = Server_Time_Content() & Description
                .Add("@AsuReceivingFlag", SqlDbType.Int, 9, AsuReceivingFlag).Value = asu_Rec_flag

                .Add("@Sender", SqlDbType.Int, 9).Value = sender
            End With
            cmd.ExecuteNonQuery()
            cmd.Parameters.Clear()

            UpdateContent = True

        Catch ex As Exception
            oMessage.DisplayException(ex.ToString)

            UpdateContent = False
        Finally
            cmd.Parameters.Clear()
        End Try
    End Function

 Private Function ForwadContent( _
                        ByVal BskID As Integer, _
                        ByVal approved As Integer, _
                        ByVal ContentID As String, _
                        ByVal description As String, _
                        ByVal Sender As Integer, _
                        ByVal indexCardName As String, _
                        ByVal documentNo As Integer, _
                        ByVal Status As String, _
                        ByVal SentTo As Integer, _
                        ByVal SentTime As String, _
                        ByRef NoteID() As String, _
                        ByVal ContentState As Integer, _
                        ByVal ASU_Rec_FLAG As Integer, _
                        ByVal cmd As SqlCommand, _
                        ByRef listFiles() As String) As Boolean

        Try

            Dim Obj_trans As SqlTransaction

            If oTrack.CheckDocumentTrack(SentTo, documentNo, indexCardName, ContentState, cmd) = True Then
                approved = ContentState
                'If oContent.UpdateContent(SentTo, approved, cmd, ContentID, description) = True Then
                If Status = "Approved" Or Status = "Reject" Then
                    If oContent.DeleteContent(ContentID, cmd) = True Then

                    Else
                        TransRolloback(Obj_trans)
                    End If ' end if delete content
                Else
                    If oContent.UpdateContent(SentTo, approved, cmd, ContentID, description, ASU_Rec_FLAG, Sender) = True Then
                    Else
                        Try
                            Obj_trans.Rollback()
                            ForwadContent = False
                        Catch
                            MsgBox(Err.Description, MsgBoxStyle.Information, "Rosetta")
                        End Try
                        Obj_trans = Nothing
                        Exit Function
                    End If 'End if update content
                End If 'end if Approved/Reject

                If oTrack.CreateDocumentTrack(Sender, indexCardName, documentNo, Status, SentTo, SentTime, cmd, NoteID, listFiles, LoginUserName) = True Then
                    ForwadContent = True
                Else
                    Try
                        Obj_trans.Rollback()
                        ForwadContent = False
                    Catch
                        MsgBox(Err.Description, MsgBoxStyle.Information, "Rosetta")
                    End Try
                    Obj_trans = Nothing
                    Exit Function
                End If

            Else
                Try
                    Obj_trans.Rollback()
                    ForwadContent = False
                Catch
                    MsgBox(Err.Description, MsgBoxStyle.Information, "Rosetta")
                End Try
                Obj_trans = Nothing
                Exit Function
            End If
END IF
        Catch
            MsgBox(Err.Description)
        End Try
END FUNCTION

When I retrieve a record from TRACK table,
SELECT * FROM TRACK WHERE DOCUMENTNO=12 AND INDEXCARDNAME='ASD' ORDER BY TrackID

I will get this error sometimes(DEAD LOCK occurred ON TRACK),
66-transaction-process-id-was-deadlocked-on-resources-with-another-process-and-has-been-chosen-as-the-deadlock-victim-rerun-the-transaction

ALL ABOVE TABLES HAVE NON-CLUSTERD ON AUTO GENERATED ID'S
Comment: And your question is ... ?
Comment: i am getting deadlock exception when write, SELECT * FROM TRACK WHERE DOCUMENTNO=12 AND INDEXCARDNAME='ASD' ORDER BY TrackID
Comment: Yes you are.  Did you have a specific question about that?
Comment: @RBarryYoung, How to avoid this error? I am getting deadlock. How to solve this?
Answer: The quickest way to try and get around this would be to change this:
SELECT * FROM TRACK WHERE DOCUMENTNO=12 AND INDEXCARDNAME='ASD' ORDER BY TrackID

to
SELECT * FROM TRACK (NOLOCK) WHERE DOCUMENTNO=12 AND INDEXCARDNAME='ASD' ORDER BY TrackID

There are downsides to this:
http://www.sqlservercentral.com/Forums/Topic177803-8-1.aspx
However, for the most part situations they will not come into play. This is a remedy for the problem rather than solving the underlying problem, without knowing what calls are made to your database and more about your data access in general that is going to be very difficult to do.


Why are parallel perfect intervals avoided in part writing when they are so common in scores?

Question:
In this concerto there are a couple of places where parallel octaves are used. I I am a harmony student but This is the first score that I have studied and see what just about every harmony book and counterpoint text teaches against. So what gives? Did Mozart not care about parallel perfect octaves and if they are so forbidden why do they appear in the very first score I have looked at? And most importantly, why are we taught not to use them?
Comment: Note that no one should be teaching you not to use them. What is good to teach is that there was a period of practice in Western Europe where they were essentially never used. Music theory is descriptive, no proscriptive. As in, it's about what has been done, not what can or should be done.
Comment: Those octaves are doubled voices which are *entirely* parallel and don't count as "different" voices in the counterpoint sense. The entire craft of orchestration rests on such judicious doubling. For instance, cellos and basses basically play parallel octaves *for the entire classical period*!
Comment: Doubled voices just in 2 chords?
Comment: @ToddWilcox there's plenty of proscriptive music theory out there, and the most notable such proscription is that against parallel fifths, followed closely by the rule against parallel octaves; both were observed very strictly by practicing composers for several centuries before Mozart and at least a century after.  It wasn't simply that they were "never used"; students were explicitly taught that they were not to use them.
Comment: People are writing answers about why that rule doesn't really apply here, which is interesting and valuable (I too have had this rule cited to me in a place where I now understand it didn't apply), but what I'm most curious to learn is why the rule exists at all. In what way does it (a) sound bad and/or (b) impair contrapuntal voice movement?
Comment: I'll throw in one thing that I haven't noticed said yet: the top violin staff is one part, the first violin part. It's not written in multiple "voices"; it's just one voice, playing multiple stops to beef out the texture at that moment. That observation doesn't bear on the vla/vc approach to the cadence, but it's something.
Comment: @LukeSawczak there are plenty of questions about that on the site, but if none of them satisfy you then you are certainly welcome to ask more.  The basic explanation is that in strict part writing there is a fixed number of voices, and parallel octaves between any two voices causes the affected voices to merge into a single voice, reducing the number of voices, which is inconsistent with strictly maintaining the fixed number of independent voices. In orchestration, by contrast, there are more parts than independent voices, so parallel octaves between non-independent voices are ok.
Comment: @AndyBonner but isn't a violin playing two voices just that?  Two voices?  In other words, don't composers tend to follow proper voice leading in double stops?  (Also, _would_ a D be playable instead of the A on the downbeat of 497?  It would certainly be better voice leading.)
Answer: Counterpoint theory generally handles the case of writing for a certain number of independent voices. Here it is a general rule to avoid certain parallels as these impair the independence of the voices.
An real world score such as this violin concerto is not made up of only independent voices. Take for example the violins in an orchestra: In a Mozart time orchestra you'd have about 6-8 first violins, all playing the same part. These can be seen as parallel unisons, but you would not consider them independent voices in the first place. And similarly not all parts of the score need to be independent voices in a contrapunctal sense. You will find though that on a large basis if you distill the core subjects and counterpoints from such a score there will not be such parallels, as these can quickly make the whole thing sound quirky.
Comment: @armani but the piece wasn't written to be played only with the violins.  Also, you're allowed not to like Mozart's music (if this even is by Mozart) or his style of orchestration.
Even in pieces of undisputed authorship these techniques of orchestration are present; if you find them tolerable in those cases and awful here then perhaps you can identify the reason behind the difference and potentially contribute to the scholarly debate about the piece's authenticity.
Comment: The point is that if you play this part just with the violins, The parallels are not only audible but make the violin section sound thin at that point. those other parallels with the viola are awful too.
Comment: @armani Are they? https://www.youtube.com/watch?v=MOZ2CsKWoBY&t=427s
Comment: @armani the viola and the cello are playing the same voice at that little section before the fermata, the eightnotes G-G-Fsharp-Fsharp-B-B-A in both parts. The viola is playing every second eight note an octave up, which gives some extra life to the line.
Answer: The prohibition is when writing counterpoint, which Mozart is not doing. When one instrumental part doubles another, there is no attempt to maintain the independence of voices — in fact, specifically the opposite.
Comment: @armani You've marked two passages in the score. Viole and Celli can very well be seen as doubling. You will see that with second half of 496 Viole and Celli play the same notes, the Viole just alternating between octaves. The first Violin is of course not doubling, it is triple stops, i.e. playing multiple strings at the same time. This mostly serves to add more notes to the tutti, which is generally a situation where polyphony not the first thing on your mind, and is written in a way that is hopefully comfortable to play.
Comment: @armani It's not math or engineering. Context matters. There aren't any fixed, consistent rules. When Bach was writing counterpoint, voice independence was key. When Mozart was writing homophony, doubling sounded appropriate. The entire history of Western music is one of constant change in practice. What was idiomatic for one composer was completely ignored or contradicted by another composer. Just because you lose points for doing something in a music theory class doesn't mean it wasn't a popular thing to do at some point in the last 400 years.
Comment: Under that premise one could say that all instances of perfect parallel intervals were "doublings". No. For it to be "doubling" there has to be some consistency... This is not what I have indicated in the score notes I added. Those are parallel perfect intervals and they do exactly what parallel perfect intervals do, which is thin out the texture.. Maybe with the whole orchestra it is not so obvious but it is with the 3 part violins
Answer: Counterpoint is one thing, this concerto is another. Voices here can (and do) get 'doubled', and as such, with so many different voices, those 'rules' have to be disobeyed.
Answer: As other answers indicate, it is because scores are often not engaged in "part writing" per se.  The classical period is characterized by instrumental figurations that are not directly subject to voice leading rules.  Such figurations were also common in the baroque period.
The middle voice of the violin triple stops might better be a D instead of an A at the downbeat of 497.  (I'm no violinist, but I assume it's playable because the next chord has D in that position.)  It's also possible that Mozart didn't write this piece (the attribution is uncertain) and that if he had he would have done it differently.
But in general, this passage is characterized by relatively free doubling.  It's basically a three-voice texture from the voice leading perspective (as is often the case with a series of 6 chords).  The violas are more or less doubling the basses, though not strictly so, just as the first violins are more or less doubling the first oboe.  The part writing is basically this:
<code>X:1
M:2/4
L:1/2
K:D
%%score {RH|LH}
V:RH clef=treble
[b d]|[a/ d][g/ d]|[f/ d]
V:LH clef=bass
G,|F,/B,/|A,/
</code>
The differing figures and the manner in which various parts jump from one voice to another are concerns of a different discipline from part writing: welcome to the world of orchestration.
Comment: @armani not completely, no, but seriously, I looked at one other violin concerto of Mozart and one symphony and I found examples of parallel octaves and unisons from this sort of quasi doubling, whatever you want to call it, both violas with basses and violins with woodwinds. If it's that easy to find it must be idiomatic. There's also a similar phenomenon in baroque music, especially choral/orchestral, where the texture stays basically in 4 parts but the voice leading in the orchestra and chorus are different. Parallel octaves occur but there are still (at least) 4 independent parts.
Comment: Free doubling? Now thats a new one. Can you explain what that is? My textbooks show doubling as a consistent duplication of one of the voices. Like a bass and cello might double at the octave. They dont double just sometimes. Doubling is clearly doubling and I dont see how my notes I highlighted can be conceived as doubling
Comment: If orchestration is a different discipline, what is the point of part writing then?
Comment: @armani look at the viola: D-B-G-F♯-B-A.  Now look at the basses: G-F#-B-A.  Look at the oboe: B-A-G-F♯.  Compare the first violin: G-B-A-G-F♯.  They are playing more notes in common than not. It's common in Mozart for the violas to double the basses without necessarily playing exactly the same thing.  The same is true of melody instruments.  Look at some other Mozart concertos or symphonies and you'll find other examples.
Comment: "What's the point of part writing": to establish the norms for harmony and voice leading in a homophonic texture, or indeed in a _stile antico_ polyphonic texture.  In a newer style concerted texture, the rules are a bit relaxed.  Consider your own recent question: "I wrote this 5 part texture this morning only to discover that all I had done was double the tenor line an octave higher. ... I was going to elaborate the top line for a solo violin part."  Look at the violins and winds in other orchestral pieces by Mozart.  It's common to have different melodic material following the same shape.
Comment: Ok so when orchestrating music, should I abandon completely the ideas and rules taught to me in harmony class?
Answer: To answer the question briefly and succinctly: because orchestral writing does not have the same principles nor is bound by the same rules as theoretical counterpoint. Or to quote the probably overused saying, this is apples and oranges.
When writing for an orchestra, there are various concerns (balance [between voices and between instrumental groups], texture, clarity) which do not exist when writing a mere counterpoint exercise. Doubling an important voice (in this instance: the bass, which is doubled [with octave jumps] by the violas; and the top note of the "melody", which is played by both the violins and the oboes) to give it more prominence is a natural solution to this.
In short, the issue here isn't one of counterpoint: these simply aren't independent voices (in the same way that the strings doubling the lower voices in this Bach cantata [BWV 182, mvt 7, see score image below] are not; or the flute and violin doubling the chorale melody at the octave later on are not; an independent voices), and thinking of it through the lens of counterpoint misses the forest for the trees. What you're looking at here is more properly called orchestration.

To answer your penultimate question (and with that put to rest any doubts about the final one), you will note that, if you disregard the doubling (in the Mozart as well as in the Bach example), the voice-leading still very much does follow the usual rules of voice-leading.
Comment: Re. before anybody says something about the belated answer: one important element missing from previous answers was the fact that the topic being discussed here has a name, i.e. "orchestration", and the main reasons for that.
Answer: If one views music "theory" as making predictions about how various musical constructs will be perceived, what music theory says about parallel perfect intervals is that a group of instruments playing parallel octaves and fifths is apt to sound somewhat like a single instrument with a different tonal character.
Having some melody lines played by trumpets, some played by violins, and some by a tuba, is apt to make a piece more interesting than if every melody line were played by the same instrument, and having a melody line played mostly by violins except for a few carefully chosen accents which are played by trumpet can space things up, but only if transitions between instruments "make sense".
Likewise, using parallel fifths and parallel octaves is fine if the transitions between the portions of the music where lines move in that fashion and the portions where they move independently are sensibly placed in the context of the piece.  Music theory suggests that such transitions may be perceived as being analogous to transitions between different instruments, but whether that's a good or a bad thing would depend upon what one is trying to accomplish.


GCC 7.X C++17 template auto parameter type deduction with enum class bug

Question: I noticed a probable bug in GCC 7.X but I can't find anything recognizing this bug anywhere. It would be nice to know if this was ever reported as a compiler bug or was hidden and until you know about it, you will assume that it works as it should. Especially that the feature is listed as supported for this version.
Until now I used this check to determine if I can use template auto patameters.
#if (__cpp_template_auto >= 201606L) || (__cpp_nontype_template_parameter_auto >= 201606L)
    #define TEMPLATE_AUTO_AVAILABLE 1
#endif

In older code you'd have to declare template like that:
template <typename EnumType, EnumType enumValue>
auto func() { exclusive version for EnumType::enumValue }

Then call it like that:
auto value = func<MyEnumType, MyEnumType::value>();

With auto template parameter it is tempting to use it like this:
template <auto enumValue>
auto func() { exclusive version for decltype(enumValue)::enumValue }
auto value = func<MyEnumType::value>();

The problem is that it is not an equivalent in GCC 7.X and can lead to nasty bugs.
Minimal example code:
enum class FirstEnum : short { firstVal = 7 };
enum class SecondEnum : size_t { secondVal = 7 };

template <typename T>
struct TypeName;

template <>
struct TypeName<FirstEnum>
{
    static constexpr auto name = "FirstEnum";
};

template <>
struct TypeName<SecondEnum>
{
    static constexpr auto name = "SecondEnum";
};

template <auto t>
void func()
{
    std::cout << TypeName<decltype(t)>::name << std::endl;
}

int main()
{
    func<FirstEnum::firstVal>();
    func<SecondEnum::secondVal>();
}

Answer: It seems as if template was instantiated for first integer value instead of actual template parameter. Because of that it does not distinguish enum classes by their type and instantiates single template for first enum class that is used with the template. All following uses with different enum types will be linked with first instantiated version. It does not respect enum class underlying type as well.
Godbolt example: https://godbolt.org/z/8P9vEn
In slightly more complicated example you can notice that the template is actually not generated per enum class type and value but some other type. This thing I'm not able to comprehend. You can see that decltype(t) is different in template parameter list and in template function itself and oddly enough, it does not depend on the type of "t" but function parameter type. Well, this answer leads to more questions than it really answers.
https://godbolt.org/z/sorbMr
GCC 7.X is not newest version of GCC but is still commonly used, especially in embedded solutions. Avoiding such known bugs is quite crucial in many applications and obviously it is better to be aware of those issues. Feel free to add more information if you understand how it was broken or how to work around this issue and still be able to use auto parameter to deduce enum class type.
In case godbolt link did not work in future, here is extended example:
#include <type_traits>
#include <typeinfo>
#include <iostream>
#include <memory>
#include <string>
#include <cxxabi.h>
#include <limits>

inline std::string demangle(const char* name)
{
    int status = -1;
    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, nullptr, nullptr, &status),
        std::free
    };
    return (status == 0) ? res.get() : name;
}

template<typename T>
std::string fullTypeName()
{
    return demangle(typeid(T).name());
}

template <typename EnumType>
constexpr auto extractEnum(EnumType val)
{
    return static_cast<std::underlying_type_t<std::remove_reference_t<EnumType>>>(val);
}

enum class FirstEnum : unsigned char { val = 0 };
enum class SecondEnum : size_t { val = 0 };
enum class ThirdEnum : int { val = 0 };

template <auto t, typename T = decltype(t)>
void func(T param)
{
    std::cout << fullTypeName<decltype(t)>()
        << "/" << fullTypeName<T>()
        << " size T: " << sizeof(decltype(t))
        << " size t: " << sizeof(T)
        << " value: " << param << std::endl;
}

int main()
{
    func<FirstEnum::val>(0);
    func<FirstEnum::val>(0U);
    func<SecondEnum::val>(500);
    func<SecondEnum::val>(50000000000000000);
    func<ThirdEnum::val>(-1);
}

Result on GCC 7.X:
FirstEnum/int size T: 1 size t: 4 value: 0
FirstEnum/unsigned int size T: 1 size t: 4 value: 0
FirstEnum/int size T: 1 size t: 4 value: 500
SecondEnum/long size T: 8 size t: 8 value: 50000000000000000
FirstEnum/int size T: 1 size t: 4 value: -1

Result on GCC 8.1+ or Clang:
FirstEnum/int size T: 1 size t: 4 value: 0
FirstEnum/unsigned int size T: 1 size t: 4 value: 0
SecondEnum/int size T: 8 size t: 4 value: 500
SecondEnum/long size T: 8 size t: 8 value: 50000000000000000
ThirdEnum/int size T: 4 size t: 4 value: -1

Answer: You can use this workaround as long, as you don't declare any parameter of type T
template <auto t, typename T = decltype(t)>
void func()
{
    std::cout << TypeName<decltype(t)>::name << std::endl;
}

This way T is the actual type of t and forces the template to be instantiated separately.
https://godbolt.org/z/Y967Ps
This solution will not work if you declare parameter of type T as it will be deduced from function parameter type instead of the default template type parameter.
I'm posting this as a separate answer in case you are looking for workaround, not explanation. This way you can vote for the answer that is more useable for others in your opinion.


Intensity normalization with segmented ROI on black background

Question: I have a set of segmented ROIs .jpgs against a black background. Pixels in the ROI range from 0 to 255 in grayscale (1 channel only). I want to normalize these intensities in order to feed it into a CNN.
When I initially just do a simple subtraction by mean and divide by the std, the output ROI image is essentially bright white. Am I doing this correctly?
When I instead try to subset the image to only nonzero pixels, find the mean and std, the ouput image is nearly as bright, with tremenedous loss of detail.  Here is how I did it:
import cv2
import numpy as np
from matplotlib import pyplot as plt

image = cv2.imread("/media/sf_share/out/slice080.jpg")
subset_mean = np.mean(np.where ( image > 0))
subset_std = np.std(image)
transformed = (diff_im - subset_mean) / subset_std
plt.imshow(transformed, cmap = 'gray', interpolation = 'bicubic')
plt.show()

Visually, the output image has lost a considerable amount of the detail that makes it unique. I understand that this is an expected output of the transformation, but the details of the images make it important. Any idea what I can do? Am I doing this properly?
Answer: As it turns out, I had an error in my code. particularly I forgot to include this line
this line
subset_std = np.std(image)

should be
subset_std = np.std(np.where( image > 0))

The output then looks reasonable.


Can I run kotlin as script with Java Scripting API

Question: I want to run kotlin code as script from java with Java Scripting API similar to this for javascript:
import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("print('Hello, World')");
    }
}

or with similar APIs like this.
Comment: I'm sure you *could*, but why? The point of Kotlin is that it compiles to JVM bytecode.
Comment: I want to use it for load kotlin [Type-Safe Builders](https://kotlinlang.org/docs/reference/type-safe-builders.html) dsl or something like this in runtime.
Answer: Yes, it's possible starting from the Kotlin 1.1: http://kotlinlang.org/docs/reference/whatsnew11.html#javaxscript-support
KEEP-75 has an example of the JSR-223 API call:

val engine = ScriptEngineManager().getEngineByExtension("main.kts")!!
engine.eval("""
@file:DependsOn("junit:junit:4.11")

org.junit.Assert.assertTrue(true)

println("Hello, World!")
""")

Configuration below adds Kotlin scripts engine to my Kotlin 1.2 project:

META-INF/services/javax.script.ScriptEngineFactory file with the content from the https://github.com/JetBrains/kotlin/blob/master/libraries/examples/kotlin-jsr223-local-example/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory

2 libraries:

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-script-runtime</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-script-util</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

Update:
Starting from Kotlin 1.2.20 kotlin-script-util doesn't depend on kotlin-compiler explicitly (see https://youtrack.jetbrains.com/issue/KT-17561). So one more module should be provided (as of the build file in example project):
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-compiler-embeddable</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

Answer: Kotlin support for the Java Scripting API is planned, but as of version 1.0.3 is not available yet. For the mean time, you can try to use an existing open-source implementation.


Como fazer aparecer e esconder um menu?

Question: Como fazer o menu aparecer e esconder? Não estou conseguindo.
Código:

let close = document.querySelector('.btn-menu')

close.addEventListener('click', function() {
  var menu = document.querySelector('.menu')
  if (menu.style.display == 'none') {
    menu.style.display = 'show'
  }
})
.menu {
  display: none;
  width: 100%;
  height: 100%;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.9);
  top: 0;
  left: 0;
}

NodeProp - Especializado em Soluções Digitais

      <button class="btn-menu"></button>

      x

Home

Cursos

Sites

Jobs

Blog

Publi

Comment: `if (menu.style.display !== 'block') { menu.style.display = 'block'; }`
Comment: O problema também é que o botão de _toggle_ está **dentro** do link. Quando você clica nele, você é redirecionado para a próxima página — no caso, `index.html`.
Comment: Entendi Luiz Felipe, muito obrigado, Fico grato pela resposta. Valeu!!!
Answer: Em primeiro lugar, não existe display: show no CSS. Conforme apontado nos comentários, o ideal neste caso é utilizar display: block como oposto ao display: none, de modo a mostrar o menu.
O block é ideal neste caso já que é o padrão para a propriedade display para elementos .
Um outro problema é que o botão de fechar está dentro da âncora (). Desse modo, embora o handler de evento do JavaScript seja propriamente executado ao clicar no botão, o usuário será redirecionado ao href do link, o que evidentemente não é a ação desejada.
Corrigindo esses problemas (e com algumas outras mudanças), ficamos com:

let open = document.querySelector('.btn-menu');
let close = document.querySelector('.btn-close');
let menu = document.querySelector('.menu');

open.addEventListener('click', function() {
  menu.style.display = 'block';
});

close.addEventListener('click', function() {
  menu.style.display = 'none';
});
.menu {
  display: none;
  width: 100%;
  height: 100%;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.9);
  top: 0;
  left: 0;
  color: #fff;
}

    NodeProp - Especializado em Soluções Digitais

  <button class="btn-menu"></button>

    x

Home

Cursos

Sites

Jobs

Blog

Publi

Mas eu fiz algumas mudanças:

Como existem dois botões separados (um para abrir e outro para fechar), não há, evidentemente, a necessidade de se utilizar um if, já que o botão para abrir sempre fará o menu ser mostrado e o para fechar, sempre fará o menu ser escondido.

Removi o
 de dentro do  e coloquei o  dentro do
 (inverti o aninhamento). Fiz isso porque o elemento  foi feito para aceitar dentro de si somente elementos inline (e o
 não é inline). Saiba mais nesta pergunta do SOen.

Adicionei ponto e vírgula no final de cada statement. Pode parecer "frescura" e sei que o JavaScript "aceita" o código sem ponto e vírgula e "funciona", mas isso evita algumas situações bizarras que podem ocorrer se você não os usar, como esta e esta (veja mais sobre isso aqui).

Mas se você quiser, pode adicionar um único handler aos dois botões e fazer a verificação com o if. Assim:

let btns = document.querySelectorAll('.btn-menu, .btn-close');
let menu = document.querySelector('.menu');

// Como agora temos uma lista de elementos, precisamos de usar o `forEach`
// para adicionar o listener de evento a cada um deles.
btns.forEach((btn) => btn.addEventListener('click', () => {
  if (menu.style.display !== 'block') {
    menu.style.display = 'block';
  } else {
    menu.style.display = 'none';
  }
}));
.menu {
  display: none;
  width: 100%;
  height: 100%;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.9);
  top: 0;
  left: 0;
  color: #fff;
}

    NodeProp - Especializado em Soluções Digitais

  <button class="btn-menu"></button>

    x

Home

Cursos

Sites

Jobs

Blog

Publi

Como fazer aparecer e esconder um menu?


How to BIND IP Address on Centos 5? Need Tutorial

Question: Can someone show me a simplified tutorial that explains how to bind IPs in Linux (Centos / Redhat)?
For example, got a dedicated server with a /29
22.214.171.124/29
So I have to bind that /29 where 188.8.131.52 is the IP I'll access via ssh in order to do so.
Thanks.
Comment: Check my recently posted answer for this question: http://serverfault.com/questions/131339/centos-multiple-ip-addresses/131366#131366
Answer: CentOS is based on Red Hat Enterprise Linux.  I've linked some of their documentation.  If you have a more detailed question, we will likely be able to assist further.
Interface Configuration Files


Script de afiliados com ajuda equipa (Problema com recursividade)

Question: Estou a escrever um código em CodeIgniter, para divulgação de um software de cloud storage gratuito e sem fins lucrativos.
Contudo, para funcionar, vamos ter um sistema de afiliados, que atribui uma certa quantidade de armazenamento a quem mais divulgar, bem como aos membros acima.
A dificuldade maior, é que o sistema de afiliados é forcado, ou seja, cada nível so pode ter no máximo 5 utilizadores, quando está completo, procura nos níveis abaixo para incorporar nos membros abaixo.
Esta é a estrutura da tabela users:
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| created      | datetime     | NO   |     | NULL    |                |
| join_ip      | varchar(30)  | NO   |     | NULL    |                |
| is_active    | tinyint(1)   | NO   |     | 0       |                |
| is_deleted   | tinyint(1)   | NO   |     | 0       |                |
| name         | varchar(100) | NO   |     | NULL    |                |
| email        | varchar(50)  | NO   |     | NULL    |                |
| country_id   | int(2)       | NO   |     | NULL    |                |
| sponsor_id   | int(20)      | NO   |     | NULL    |                |
| upline_id    | int(11)      | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

A função que tenho no Model em PHP (CodeIgniter) é esta:
public function getAvailableSponsor($sponsor = NULL)
{
    if ($sponsor == NULL) return array();
    $this->db->select('id, sponsor_name, sponsor_id, upline_id')
        -> from('users')
        -> where('upline_id', $sponsor);

    $query = $this->db->get();
    $result = $query->result();
    $total = count($result);

    if ($total < 2){
        return $sponsor;
    }else {
        foreach ($result as $row){
            return $this->getAvailableSponsor($row->id);
        }
    }

}

A sequência que estou a ter de resultado é esta:
Sponsor ID 1 has 2 sponsored users FULL.
Sponsor ID 2 has 2 sponsored users FULL.
Sponsor ID 4 has 0 sponsored users Available :)

Next upline: 4 (AQUI deveria de ser 3, e nao 4.)

Query na base de dados:
 select id, sponsor_id, upline_id from users;

 +----+------------+-----------+
 | id | sponsor_id | upline_id |
 +----+------------+-----------+
 |  1 |          0 |         0 |
 |  2 |          1 |         1 |
 |  3 |          1 |         1 |
 |  4 |          1 |         2 |
 |  5 |          1 |         2 |
 +----+------------+-----------+

Alguma sugestão?
Comment: Entendi. Tu estás a percorrer os sub-níveis da esquerda para a direita, por isso, pode ser que o 4 esteja no mesmo nível que o 3 mas apareça primeiro, faz um *select all* a base de dados e posta aqui a resposta.
Comment: Explica melhor o teu problema. O que queres fazer exatamente?
Comment: Olá Jorge. O que quero fazer é que os registos sejam inseridos pela ordem os seus respectivos niveis. Por exemplo se o sistema for de 2 users por niveis, o user 1, insere o 2 e o 3. Depois o 1 volta a inserir mais 2, mas serao ja inseridos debaixo do 2. Este artigo explica de forma detalhada o que será necessario fazer,  mas aplicado a este software gratis e opensource.
Comment: Então queres um sistema de inserção de utilizadores em árvore?
Comment: Sim, de forma a que a árvore fique preenchida automaticamente até N níveis.
Comment: A ideia é mais ou menos a mesma de esta: http://jam.jrox.com/kb/article/what-is-forced-matrix
Comment: Pergunta editada. So trouxe os campos mais importantes
Comment: Como estas a fazer recursivamente o que acontece é que tu vais seguir dois caminhos diferente, por rotas diferentes.

 id=4 tem pai id=2
 id=3 tem pai id=1

ou seja, são dois caminhos diferente na recursividade. E por algum motivo o caminho por pai id=2 é mais rápido a verificar que tem um filho livre.
Comment: Pois, esse é o meu problema. Eu sou um programador com conhecimento médio, mas no que toca a recursividade tenho muitas dificuldades.
Comment: No seu foreach, quando executa o return ele não continua o for, sai na primeira iteração.
Answer: Podes tentar algo com sub-select como:
SELECT a.id FROM users a
WHERE (SELECT count(*) FROM users b WHERE upline_id = a.id) < 2
ORDER BY a.id


Decision Theory: Why is it called a "least favorable prior"?

Question: I'm currently reading the chapter on Statistical Decision Theory in Larry Wasserman's "All of Statistics". Reading the section 13.4 about Minimax Rules he introduces the so called Least favorable prior.

Theorem $13.11$ Let $\widehat{\theta}^{\pi}$ be the Bayes rule for some prior $\pi$ :
$$
r\left(\pi, \widehat{\theta}^{\pi}\right)=\inf _{\widehat{\theta}} r(\pi, \widehat{\theta})
$$
Suppose that
$$
R\left(\theta, \widehat{\theta}^{\pi}\right) \leq r\left(\pi, \widehat{\theta}^{\pi}\right) \text { for all } \theta
$$
Then $\widehat{\theta}^{\pi}$ is minimax and $\pi$ is called a least favorable prior.

Why is $\pi$ called the "least favorable" prior ? Is it because the minimax approach is more pessimistic that the bayes one and this prior therefore is the most "pessimistic" one out of all the possible priors ?
Comment: I previously struggled with this part also, and from a self-study perspective, this is one of the terser parts of the book if you've never encountered minimax theory before. Have you considered working through and understanding the proof by contradiction he has supplied, as a starting point?
Comment: Yes I did, and I actually understood how it works. I'm still not certain whether I understand why this proof is important though, but today I'm going to look at the examples that follow it.
Answer: I'm not sure how the name originates but here is my opinion on it.
The Bayes risk is some average of the risk function of the Bayes estimator, weighted by the prior. The least favorable prior only places weight on the part of the risk function that achieves the supremum. One example of such could be a Dirac delta at the $\arg \sup_{\theta} \text{R} (\theta, \hat{\theta})$.
However, there is a slight problem with this example. Namely, we cannot choose the least favorable prior after fixing a risk function, since the risk function is determined by the prior. So in reality, the prior comes first and the risk function of the Bayes estimator can be determined. If then we realize the prior happens to place all the weights on the supremum of the risk, we have found the least favorable prior.


How can I count the time spent in a day in establishing connections between two servers?

Question: I have two servers, one is a SQL Server and the other one is a webserver with IIS installed.
I'd need to find a -weird, admittedly- information: how much time the webserver spend during a day, in total, in establishing connections to the SQL Server?

To give things a little more context...
The issue is that our current web application is so badly designed that it executes thousands of queries for even the simplest task: the user clicks a button and, voila', 3 minutes and 70k calls later the result is given. This is clearly bad, and I want the company to address it, but I want to get some numbers too.
What I want to extract here is how much total time is spent daily in the connection process -both connection and disconnection-, with the time spent waiting for the answer itself not included.
Let's say that the communication goes this way:

The webserver open the connection
The webserver send the request to the DB server
The DB server is doing its stuff, while the webserver is waiting for result
The DB server sends back the results
The connection get closed.

What I'd want is the total of 1+2+5, lag included, for every communications between the two servers, for an entire day. Possible? Impossible?
Comment: *"how much total time is spent daily in the connection process -both connection and disconnection"* - that doesn't seem to be a very useful metric.  Usually logging/graphing the number of connections is already enough to make a solid argument to implement connection pooling in an application.
Comment: Wouldn't it be more useful to calculate how much time is spent executing the queries on the database server? How is knowing how much time is spent NOT executing queries on the database server helpful?
Answer: There are other network-related performances that you won't be appreciating AFTER the connection has established. Most notably, the effect of round-trip delay, but also TCP slow-start.
You should be able to avoid most of the slow-start and connection overhead by using a connection pool (I could be wrong... implementation details and all), but the biggest problem will your performance will be scale very poorly the further you get from the server.
70k requests is a big number. Ping a machine very close to you on the network. Now ping a machine in a different part of the network. Let's say that's like the difference between a small SoHO network and a large network, where the client application is for example on a user's desktop, and the database in housed in a database server in a datacentre.
Now how many TCP round-trips are actually required on average for one of these requests. Now work and how many round-trips, and thus the total time spent in waiting for round-trips.
This is a good reason why a client-side application and database are a bad idea; you want an application-server component that is close to the database, so the business logic and the database are always close together.


What is the difference between t() and @Translation()?

Question: When writing a (translatable) plugin in Drupal 8, you have to use Drupal\Core\Annotation\Translation;, and then wrap your value in @Translation("value"), however when implementing the FormInterface, you can use t() freely as you would in Drupal 7.
I found Annotation-based plugins on Drupal.org, but it just mentions the fact that you should use it, and the Doctrine reference doesn't seem to include @Translation
I assume it is because the plugin system is part of doctrine, and not part of core, whereas t() is  -is this the correct assumption?
Basically, what is the difference between @Translation(); and t() - is it just because plugins are Doctrine based?
Comment: @Mołot Not :) _is it just because plugins are Doctrine based?_ not quite, it's because they're _annotation_ based. You can't call a PHP function from inside annotation metadata, so a special annotation has been defined to handle the same work that `t()` does. http://php-and-symfony.matthiasnoback.nl/2011/12/symfony2-doctrine-common-creating-powerful-annotations/ might be interesting reading as a grounding in custom annotations. I don't know the technical terms for these concepts inside Drupal so I won't put an answer in
Comment: @Mołot I think the simplest way to put it is that `@Translation` is a wrapper around `t()`, only _practically_ accessible for use in the context of an annotation. The `Translation` plugin actually uses `t()` internally anyway. Chapabu, check out the comments in [`Drupal\Core\Annotation\Translation`](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Annotation!Translation.php/8) and [`Drupal\Core\Annotation\Plugin`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Annotation%21Plugin.php/class/Plugin/8), they should go some way towards explaining this stuff :)
Comment: Aport from actually translating it (that would also be possible by simply defining which keys for each plugin should be translated), an important aspect of it is that translatable strings can be extracted just like they can for t() using potx.module.
Comment: @Clive Awesome. I've just grokked the routing, `FormInterface` and `SystemConfigFormBase` (and `ConfigFactory` stuff) so custom entities/fields was my next port of call anyway :)
Comment: Isn't `@` in `@Translation("value")` just an [php error control operator](http://php.net/manual/en/language.operators.errorcontrol.php)? Just asking.
Comment: @Clive so the basic difference is that `t()` is a PHP function, and `@Translation()` is not? Neat ;)
Comment: Best advice I can give for understanding how this stuff works is actually to build a custom entity/custom field/entity reference extension/views extension/etc. for Drupal 8. It all falls into place very quickly
Answer: In short, @Translation() is a string used in annotations, meta data written in PHP comments and pertinent to a Drupal 8 class.
For example, this is the annotation for the PathItem entity field class.
/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = @Translation("Path field item"),
 *   description = @Translation("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */

When Drupal loads the class annotations from a file, and it finds @Translation("Content") in the annotation, it creates an instance of the Translation class whose constructor receives the "Content" string; the instance is then used to get the value of t("Content").
As for the differences, they are the following ones:

@Translation() is a string used in class annotations: plain text that follows a specific format and it is written in PHP comments before the class that is being annotated. You cannot use it in code similar to the following one, except in the case a module defines a Translation() function. In that case, the @ before it would be understood from PHP as the error control operator.
$form['salary'] = array(
  '#type' => 'textfield',
  '#title' => @Translation('Salary'),
  '#size' => 10,
  '#maxlength' => 10,
  '#description' => @Translation('Please enter a valid number'),
);

t() is a Drupal function. It cannot be used inside class annotations like the following one, since it doesn't follow the syntax annotations follow. If it were used in an annotation as in the following, it would not cause Drupal to call t() and use its return value.
/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = t("Path field item"),
 *   description = t("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */


Validação dos campos e dados na table não funcionam

Question: Estou querendo fazer a validação dos campos se estão devidamente preenchidos e verificar se a soma dos campos for maior que 10 e mostrar os dados na table mas nada disso está acontecendo.
Se eu deixo os campos vazios e tento clicar em cadastrar, em vez de mostrar a mensagem que os campos estão vazios, ele mostra esta mensagem:

HTML:
<form action="" method="post" class="formcss" name="form1"  >

Dados do Aluno

RGM :

        <input id="rgm" type="text" name="rgm" placeholder="Digite seu RGM" class="entrada" />

Nome :

        <input id="nome" type="text" name="nome" placeholder="Nome completo" class="entrada" />

Nota parcial :

        <input type="text" id="notaparcial" name="notaparcial"
               placeholder="Digite aqui a nota parcial" class="entrada" />

Nota exercícios :

        <input type="text" id="notaexercicios" name="notaexercicios"
               placeholder="Digite aqui a nota dos exercícios" class="entrada" />

Nota projeto :

        <input type="text" id="notaprojeto" name="notaprojeto"
               placeholder="Digite aqui a nota no projeto" class="entrada" />

Nota regimental :

        <input type="text" id="notaregimental" name="notaregimental"
               placeholder="Digite aqui a nota regimental" class="entrada" />

        <input type="button" id="btncalcular" value="Calcular" class="botao" />
        <input type="button" id="btnlistar" value="Mostrar" class="botao" />

Resultado...

</form>

CSS:
.formcss {
   width: 55%;
   background-color: #865027;
   padding: 20px 30px 20px 30px;
   font-size: 12px;
   font-family: verdana;
   color: #fff;
   text-shadow: 2px 2px 2px #000;
   border-radius: 25px;
   margin: 0 auto;
}
h1 {
   padding: 0px 0px 10px 0px;
   border-bottom: 3px solid #000;
   text-align: center;
}
.titulo {
   font-size: 11px;
}
div {
   margin: 0px 0px 20px;
}
.rotulos {
   float: left;
   width: 20%;
   text-align: right;
   padding-right: 10px;
   margin-top: 10px;
   font-weight: bold;
}
.rotuloretorno {
   float: left;
   width: 75%;
   font-size: 14px;
   font-family: verdana;
   text-align: left;
   padding-left: 200px;
   padding-right: 10px;
   margin-top: 10px;
   font-weight: bold;
}
.entrada {
   border: none;
   color: #525252;
   height: 30px;
   line-height: 15px;
   padding: 5px 0px 5px 5px;
   width: 70%;
   border-radius: 5px;
   box-shadow: 2px 2px 2px #000;
   background-color: #f5deb3;
}
.botao {
   background-color: #2e1707;
   border: none;
   padding: 10px 25px 10px 25px;
   color: #fff;
   border-radius: 4px;
   text-shadow: 1px 1px 1px #FFE477;
   font-weight: bold;
   box-shadow: 2px 2px 2px #3D3D3D;
}
.botao:hover {
   color: #dbd9d9;
   background-color: #030201;
}

JavaScript:
function validar() {
   var nome = $("#nome").val();
   var rgm = $("#rgm").val();
   var parcial = $("#notaparcial").val();
   var exercicios = $("#notaexercicios").val();
   var projeto = $("#notaprojeto").val();
   var regimental = $("#notaregimental").val();

   if (nome == "") {
      alert('Preencha o campo com seu nome');
      form1.nome.focus();
      return false;
   } else if (rgm == "") {
      alert('Preencha o campo com rgm');
      form1.rgm.focus();
      return false;

   } else if (parcial == "") {
      alert('Preencha o campo com a nota da parcial');
      form1.notaparcial.focus();
      return false;

   } else if (exercicios == "") {
      alert('Preencha o campo com a nota dos exe');
      form1.notaexercicios.focus();
      return false;

   } else if (projeto == "") {
      alert('Preencha o campo com a nota projeto');
      form1.notaprojeto.focus();
      return false;

   } else if (regimental == ""){
      alert('Preencha o campo com a nota regimental');
      form1.notaregimental.focus();
      return false;
   }
   return true;
}

function caculoMedia( /* n1, n2, n3, n4, etc */ ) {
   return [].reduce.call(arguments, function(sum, nr) {
      return sum + nr;
   }, 0) / (arguments.length);
}

function situacao(n1, n2, n3, n4) {
   var situacao = "";
   var media = caculoMedia(n1, n2, n3, n4);
   if (media >= 6) situacao += "Aprovado";
   else if (media < 6) situacao += "Exame";
   else situacao += "Reprovado";
   return situacao;
}

var nomes = [];
var indice = [];
var sit = [];
var media = [];

var i = 1;

window.onload = function() {
   var btn = document.getElementById("btncalcular");
   btn.onclick = function() {
      if (validar()) {
         var parcial = parseFloat($("#notaparcial").val());
         var exercicios = parseFloat($("#notaexercicios").val());
         var projeto =parseFloat($("#notaprojeto").val());
         var regimental = parseFloat($("#notaregimental").val());
         console.log(parcial, exercicios, projeto, regimental);
         if (parcial + exercicios + projeto + regimental <= 10) {
            nomes[i] = $("#nome").val();

            var resp = caculoMedia(parcial, exercicios, projeto, regimental);
            media[i] = resp;
            var sit = situacao(parcial, exercicios, projeto, regimental);
            sit[i] = situacao;
         } else {
            alert("A soma das notas não podem ultrapassar 10");
         }
      }
   }
   document.getElementById("btnlistar").onclick = function() {
      listarAlunos();
   }
}

function listarAlunos() {
   var conteudo = "
";
   conteudo += "
";
   conteudo += "";
   conteudo += "

Aluno

";
   conteudo += "	";
   conteudo += "";
   conteudo += "

Media

";
   conteudo += "	";
   conteudo += "";
   conteudo += "

Situacao

";
   conteudo += "	";
   conteudo += "
";
   //pos contator
   for (var pos = 0; pos < nomes.length; pos++) {
      conteudo += "
";

      conteudo += "" + nomes[pos] + "	";
      conteudo += "" + media[pos] + "	";
      conteudo += "" + sit[pos] + "	";

      conteudo += "
";
   }
   conteudo += "
";
   document.getElementById("txtrelatorio").innerHTML = conteudo;
}

Comment: faz uso do html5.. adiciona aos inputs o campo required!

de resto, a resposta a tua pergunta já foi respondida, para chamar uma funcao tens que por os ()
Answer: Seu JavaScript possui muitos problemas que corrigi, como, por exemplo, a chamada da função validar no if, estava faltando os parênteses: if(validar()), entre outros erros que impediam o código funcionar (não vou explicar todos senão isso vai ficar enorme).
Segue o código corrigido (caso haja mais problemas, favor apontar para que possa ser corrigido):

Outra coisa, nesta linha document.getElementById("txtrelatorio").innerHTML = conteudo;, verifiquei que no seu HTML não existe o elemento com o id="txtrelatorio". Imagino que você queira se referir à div com id="divresultado". Se for isso, basta substituir no script.
Outra sugestão: já que usa jQuery, use-o em todo o código. Por exemplo, document.getElementById("txtrelatorio").innerHTML = conteudo; poderia ser $("#txtrelatorio").html(conteudo);.

function validar() {
   var nome = $("#nome").val();
   var rgm = $("#rgm").val();
   var parcial = $("#notaparcial").val();
   var exercicios = $("#notaexercicios").val();
   var projeto = $("#notaprojeto").val();
   var regimental = $("#notaregimental").val();

   if (nome == "") {
      alert('Preencha o campo com seu nome');
      form1.nome.focus();
      return false;
   } else if (rgm == "") {
      alert('Preencha o campo com rgm');
      form1.rgm.focus();
      return false;

   } else if (parcial == "") {
      alert('Preencha o campo com a nota da parcial');
      form1.notaparcial.focus();
      return false;

   } else if (exercicios == "") {
      alert('Preencha o campo com a nota dos exe');
      form1.notaexercicios.focus();
      return false;

   } else if (projeto == "") {
      alert('Preencha o campo com a nota projeto');
      form1.notaprojeto.focus();
      return false;

   } else if (regimental == ""){
      alert('Preencha o campo com a nota regimental');
      form1.notaregimental.focus();
      return false;
   }
   return true;
}

function caculoMedia( n1, n2, n3, n4, etc ) {
   return [].reduce.call(arguments, function(sum, nr) {
      return sum + nr;
   }, 0) / (arguments.length);
}

function situacao(n1, n2, n3, n4) {
   var situacao = "";
   var media = caculoMedia(n1, n2, n3, n4);
   if (media >= 6) situacao += "Aprovado";
   else if (media < 6) situacao += "Exame";
   else situacao += "Reprovado";
   return situacao;
}

var nomes = [];
var indice = [];
var sit = [];
var media = [];

var i = 0;

window.onload = function() {
   var btn = $("#btncalcular");
   btn.click(function() {
      if (validar()) {
         var parcial = parseFloat($("#notaparcial").val());
         var exercicios = parseFloat($("#notaexercicios").val());
         var projeto =parseFloat($("#notaprojeto").val());
         var regimental = parseFloat($("#notaregimental").val());
         console.log(parcial, exercicios, projeto, regimental);
         if (parcial + exercicios + projeto + regimental <= 10) {
            nomes[i] = $("#nome").val();

            var resp = caculoMedia(parcial, exercicios, projeto, regimental);
            media[i] = resp;
            var situa = situacao(parcial, exercicios, projeto, regimental);
            sit[i] = situa;
         } else {
            alert("A soma das notas não podem ultrapassar 10");
         }
      }
   });
   $("#btnlistar").click(listarAlunos);
}

function listarAlunos() {
   var conteudo = "
";
   conteudo += "
";
   conteudo += "";
   conteudo += "

Aluno

";
   conteudo += "	";
   conteudo += "";
   conteudo += "

Media

";
   conteudo += "	";
   conteudo += "";
   conteudo += "

Situacao

";
   conteudo += "	";
   conteudo += "
";
   //pos contator
   for (var pos = 0; pos < nomes.length; pos++) {
      conteudo += "
";

      conteudo += "" + nomes[pos] + "	";
      conteudo += "" + media[pos] + "	";
      conteudo += "" + sit[0] + "	";

      conteudo += "
";
   }
   conteudo += "
";
   $("#divresultado").html(conteudo);
}
.formcss {
   width: 55%;
   background-color: #865027;
   padding: 20px 30px 20px 30px;
   font-size: 12px;
   font-family: verdana;
   color: #fff;
   text-shadow: 2px 2px 2px #000;
   border-radius: 25px;
   margin: 0 auto;
}
h1 {
   padding: 0px 0px 10px 0px;
   border-bottom: 3px solid #000;
   text-align: center;
}
.titulo {
   font-size: 11px;
}
div {
   margin: 0px 0px 20px;
}
.rotulos {
   float: left;
   width: 20%;
   text-align: right;
   padding-right: 10px;
   margin-top: 10px;
   font-weight: bold;
}
.rotuloretorno {
   float: left;
   width: 75%;
   font-size: 14px;
   font-family: verdana;
   text-align: left;
   padding-left: 200px;
   padding-right: 10px;
   margin-top: 10px;
   font-weight: bold;
}
.entrada {
   border: none;
   color: #525252;
   height: 30px;
   line-height: 15px;
   padding: 5px 0px 5px 5px;
   width: 70%;
   border-radius: 5px;
   box-shadow: 2px 2px 2px #000;
   background-color: #f5deb3;
}
.botao {
   background-color: #2e1707;
   border: none;
   padding: 10px 25px 10px 25px;
   color: #fff;
   border-radius: 4px;
   text-shadow: 1px 1px 1px #FFE477;
   font-weight: bold;
   box-shadow: 2px 2px 2px #3D3D3D;
}
.botao:hover {
   color: #dbd9d9;
   background-color: #030201;
}

<form action="" method="post" class="formcss" name="form1"  >

Dados do Aluno

RGM :

        <input id="rgm" type="text" name="rgm" placeholder="Digite seu RGM" class="entrada" />

Nome :

        <input id="nome" type="text" name="nome" placeholder="Nome completo" class="entrada" />

Nota parcial :

        <input type="text" id="notaparcial" name="notaparcial"
               placeholder="Digite aqui a nota parcial" class="entrada" />

Nota exercícios :

        <input type="text" id="notaexercicios" name="notaexercicios"
               placeholder="Digite aqui a nota dos exercícios" class="entrada" />

Nota projeto :

        <input type="text" id="notaprojeto" name="notaprojeto"
               placeholder="Digite aqui a nota no projeto" class="entrada" />

Nota regimental :

        <input type="text" id="notaregimental" name="notaregimental"
               placeholder="Digite aqui a nota regimental" class="entrada" />

        <input type="button" id="btncalcular" value="Calcular" class="botao" />
        <input type="button" id="btnlistar" value="Mostrar" class="botao" />

Resultado...

</form>
Comment: Dvd agora funcionou, mas agora ao cadastrar o aluno com a média ele não mostra a situação na table , em que era pra mostrar se o aluno esta aprovado,reprovado ou exame
Comment: @User1999 Dá uma olhada no texto no final da resposta.
Comment: @User1999 Não está funcionando o lance do resultado. Vou ver aqui.
Comment: blz vou dar uma olhada
Comment: @User1999 Pronto. Coloquei o código todo corrigido. Tinha ainda muitos erros.


Is it always necessary to include the root in a slash chord?

Question: Is it always necessary to include the root in a slash chord?
I see slash chords sometimes that do not contain the root note.  Is it conventional to do that in certain contexts?  Here is an example.

As you can see, the Em7/A has no E.  Is this okay because the previous chord is Em7 and does contains the note E?  Does that make it sound like an Em7/A chord despite containing no E?  Is this sort of pattern common?
How about this one?

The Bm7/E has no B.  Unlike the first example, the previous chord also has no B.  Is this chord still likely to be perceived by the listener as Bm7/E?  If so, is there an explanation for it?  Is this sort of pattern common?
(The piano is the only instrument here, so the root isn't played by another instrument.)
Comment: The top one seems more like A7sus2, sus4 (sort of A11) to me - and the sequence would indicate that - rising 4ths. Seems about the same idea for the 2nd also - E11(no 3rd).
Comment: All of these look like accompaniment parts. Are you *really* sure a different instrument isn't playing the root in both cases? So we can check more easily, what pieces are the examples from (or are they just examples you made up, possibly in simulation of other sheet music)?
Comment: It's never neccessary to include the root in *any* chord, it can be implied.
Answer: Yes, this is often done.
Should it be?   Maybe.  If you want THAT voicing - a G major triad over first an E then an A bass note - you could convey more useful information by calling them G/E and G/A.   (And you could convey even MORE useful information by using notation.)
Some will say that chord symbols SHOULDN'T try to include voicing information.  Others consider them merely a guide for improvisation. But if they are intended as assistance in playing THAT arrangement, and if you hear the different flavour of including E in the upper chord (I certainly do), I think using G/E and G/A adds value.
Comment: Strongly agree. A different "root" creates interesting complications/ambiguities that I think have no other convenient standard notation. Vaguely akin to "sus" chords, but perhaps opposite... :)
Answer: Chord symbols are open to interpretation regardless of how specific one tries to be about naming them. It is fairly common for players and arrangers to take liberties like omitting a root or 5th, adding a 9th, etc.
Both chords in your examples are essentially V9sus4 chords. I think that will be the perception in either case, regardless of the notes in the previous chord. Some people like writing them like this, as a ii7 with V in the bass. There may be an expectation by the composer or arranger that it will be played literally, Em7/A = A E G B D, and some may do exactly that but that won't always be the case.
Bottom line, what is written doesn't exactly match the chord symbols like you say but does capture the basic intention. You can't count on something being played exactly the way you write it as a chord symbol so if you want something very specific write out the voicing instead.
Comment: No, the OP means that he sees cases where the slash chord he sees has no notes that match the root of the top chord in the notation. For example, he sees a D/Eb chord made of only Eb, F#, and A.
Comment: @Dekkadeci Oh, I guess I misread the question, it is more of a voicing issue. I'll withdraw my answer for now and maybe take another crack at it after my first cup of coffee :)
Comment: @Dekkadeci I overhauled my answer after having my coffee…
Answer: My assumption is - like Dekkadeci says in her comment - that these chords are accompaniments and the root tone will be in the melody.
That's why your first example is Em/A and not G/A. I can't see another explanation.
Thus, normally the root note should be contained in the slash chord, otherwise it doesn't make sense to me.
Comment: As a small correction, I'm female.
Answer: Ideally you want to root somewhere. Even with rootless chord voicings it's generally assumed somewhere in an ensemble the root will be played.

As you can see, the Em7/A has no E. Is this okay because the previous chord is Em7 and does contains the note E?

Yes, this is what I hear, a continuation of the Em7, because all the right hand tones are held through the second measure.
But, if you are relying on that effect, and if you already have notation, what is the purpose of the jazz chord symbols?
That isn't a rhetorical question. From the chord symbols about the only thing you might count on is the bass tones will be E then A. What happens above is a mixed bag. If a guitarist or pianist play from those symbols you could get very different results. Is that OK?
I imagine an important question is: do you specifically not want a full close voiced Em7 in both bars? If so, G/E and G/A closer to what you want played, even if it isn't necessarily the right harmonic analysis.
When I see piano score with jazz chord symbols, or guitar chord diagrams, above staff, I think Hal Leonard arrangements of pop/rock songs. Usually, I find those arrangements unsatisfying, often loosing the importance of the original arrangements. Are arrangement and voicing particulars essential for your music?
I think the question isn't whether it's necessary to include the root in a slash chord, but whether something like "omit the root in RH" or "play the same voicing for two measures" is what you really want.


How we can get custom field type which will bring custom data from custom table to use as a drop down

Question: I need to use my custom table data as a drop down.
for eg. i have created one custom table which is getting list of cities and i want that list to be shown in my form as a drop down.
Thanks in advance
Answer: You might want to look at http://materializecss.com/badges.html#dropdown The have a pretty straight forward way of creating a dropdown menu, including code examples.
If it's for a certain Form ID you can use hook_form_FORM_ID_alter to specify which ID and alter it's HTML inside $form_state. If you don't know it's structure you can var_dump($form_state); first instead so you know what to alter.
P.S. also add the CSS of course: drupal_add_css(drupal_get_path('theme', 'custom') .'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.css', 'theme', 'screen,projection', FALSE);
Answer: To Create Custom field type you need to follow following steps

Create a custom module (myfield)
In myfield.install file add this
/**
* Implements hook_field_schema().
*/

function myfield_field_schema($field) {
return array(
'columns' => array(
    'code' => array(
        'type' => 'varchar',
        'length' => 2,
        'not null' => FALSE,
    ),

),
'indexes' => array(
    'code' => array('code'),
),
);
}

In  myfield.module file add the following code
/**
  * Implements hook_field_info().
  */
 function myfield_field_info() {
return array(
    'myfield' => array(
        'label' => t('My Field'),
        'description' => t('This field stores a Field data in the database.'),
        'default_widget' => 'myfield_field',
        'default_formatter' => 'myfield_default',
    ),
   );
}

 /**
 * Implements hook_field_widget_info().
  */
    function myfield_field_widget_info() {
return array(
    'myfield_field' => array(
        'label' => t('Select list'),
        'field types' => array('myfield'),
    ),
      );
   }

    /**
    * Implements hook_field_settings_form().
    */
 function myfield_field_settings_form($field, $instance, $has_data) {
$settings = $field['settings'];
// Add your global settings fields here
$form = array();
return $form;
  }

   /**
   * Implements hook_field_instance_settings_form().
    */
 function myfield_field_instance_settings_form($field, $instance) {
$settings = $instance['settings'];
// Add your instance settings fields here.
$form = array();
return $form;
 }

  /**
     * Implements hook_field_widget_form().
   */
   function myfield_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
//Getting the select list.

$options = get_all_nodes();

switch ($instance['widget']['type']) {
    case 'myfield_field' :
        $cc = "IN";

        $element['myfield'] = array(
            '#type' => 'fieldset',
            '#title' => $element['#title'],
            '#tree' => TRUE,
            '#prefix' => '
',
            '#suffix' => '
',
        );
        $element['myfield']['code'] = array(
            '#type' => 'select',
            '#title' => t('Node'),
            '#default_value' => isset($items[$delta]['code']) ? $items[$delta]['code'] : '',
            '#options' => $options,
            '#required' => $element['#required'],

        );

        break;
    }
    return $element;
   }

  /**
   * Implements hook_field_presave().
     */
  function myfield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
foreach ($items as $delta => $item) {
    if (isset($item['myfield']['code'])) {
        $items[$delta]['code'] = $item['myfield']['code'];

    }
        }
 }

 /**
    * Implements hook_field_is_empty().
  */
  function myfield_field_is_empty($item, $field) {
if (empty($item['myfield']['code'])) {
    return TRUE;
    }
    return FALSE;
    }

    /**
    * Implements hook_field_validate().
     */
   function myfield_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
// Loop through field items in the case of multiple values.
foreach ($items as $delta => $item) {
    if (isset($item['code']) && $item['code'] != '') {
        if (!valid_myfield($item['code'])) {
            $errors[$field['field_name']][$langcode][$delta][] = array(
                'error' => t('Field.'),
            );
        }
       }
     }
     }

   /**
    * Implements hook_field_formatter_info().
     */
   function myfield_field_formatter_info() {
return array(
    'myfield_default' => array(
        'label' => t('Default'),
        'field types' => array('myfield'),
    ),
    );
   }

     /**
         * Implements hook_field_formatter_view().
       */
      function myfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
//Getting the select list values
$options = get_all_nodes();
$element = array();
switch ($display['type']) {
    case 'myfield_default' :
        foreach ($items as $delta => $item) {
            if (isset($item['code'])) {
                $element[$delta]['#markup'] = $options[$item['code']];
            }
        }
        break;
       }
       return $element;
      }

  //To list out all functions
   function get_all_nodes() {
     $cflags = db_select('node', 'cf')
        ->fields('cf', array('nid', 'title'))
        ->condition('cf.status', 1, '=')
     ->condition('cf.type', 'books', '=')
        ->execute();

    foreach ($cflags as $row) {
        $options[$row->nid] = $row->title;
      }
          return $options;
  }

Hope this will help you
Comment: Followed same solution ? and is working ?