How to disable application update options in intellij

Question: I am trying to deploy a Spring application with Intellij. While I was working with the server and using  button, I did marked the "do not show this again" option as checked and instead of choosing redeploy, the "restart server" option was checked. I did read Intellij's documentation but I did not find anything. I did add a new server, but apparently the previous setting is valid for the new server as well. Please advise.
Comment: Which application server do you use for your deployment?
Comment: I am using tomcat 8
Answer: I believe you clicked on 'Don't ask again' here:

If you wish for that dialog to appear again, then edit your Run Configuration and check 'Show Dialog':

after which on clicking 'Refresh' as in the first snapshot the dialog should appear again.
Furthermore, note that clicking on 'Don't ask again' will only affect the configuration of the specific Run Configuration. For instance, in the snapshots above, the only Run Configuration affected is RunOnTomcat.
The default configuration can be changed and will then affect all future Run Configurations. For instance, if you wished to not have the dialog appear for any future Tomcat Server Run configurations then you would uncheck the 'Show Dialog' option here:


Android Linkify text in dialog

Question: Hi I've gone through all of the different linkify tutorials I could find but none of them work here is my current code:
final SpannableString s = new SpannableString("Please send any questions to firstname.lastname@example.com");
            Linkify.addLinks(s, Linkify.EMAIL_ADDRESSES);
            AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
            builder.setTitle("Warning!")
                   .setMessage(s)
                   .setCancelable(false)
                   .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {

                       }
                   })
                   .setNegativeButton("Decline", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            Activity.this.finish();
                       }
                   }).show();

However when I actually run the app it shows the text like blue and underlined as if it were linked but selecting the text doesn't prompt to open the email app. I've also tried with urls and the browser doesn't work is there something that's missing?
Thanks for any help.
Answer: In order to have a clickable area on dialog you need to use TextView (View) and set autoLink=all in layout file or invoke setAutoLinkMask() method from within the code.
final SpannableString s = new SpannableString("Please send any questions to email@example.com");

//added a TextView
final TextView tx1=new TextView(this);
tx1.setText(s);
tx1.setAutoLinkMask(RESULT_OK);
tx1.setMovementMethod(LinkMovementMethod.getInstance());

Linkify.addLinks(s, Linkify.EMAIL_ADDRESSES);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Warning!")
  .setCancelable(false)
  .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
       }
      })
  .setNegativeButton("Decline", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
               finish();
      }
     })
  .setView(tx1)
  .show();

Answer: Here's Kotlin in case it's helpful:
val s = SpannableString(getString(R.string.actions_list_info_button_body))
val tx1 = TextView(context!!)
tx1.text = s
tx1.autoLinkMask = RESULT_OK
tx1.movementMethod = LinkMovementMethod.getInstance()

The rest is the same.
The result likely will not look great so you probably will want to add some padding as well:
// Adjust Padding to dp
val scale: Float = resources.displayMetrics.density
val dpAsPixels: Int = (25 * scale + 0.5f).toInt()
text.setPadding(dpAsPixels,20,dpAsPixels,0)

Answer: Alternatively, you can reuse the TextView created.
AlertDialog.Builder builder;

builder.setMessage(R.string.yourMessage);

Dialog dialog = builder.create();
dialog.setOnShowListener(d -> {
    TextView text = dialog.getWindow().findViewById(android.R.id.message);
    text.setAutoLinkMask(Linkify.ALL);
    text.setMovementMethod(LinkMovementMethod.getInstance());
});

Android Linkify text in dialog


Where is it safe to connect drain pipe of RO filtration system?

Question: I'm installing iSpring RCC7AK filtration system in a rental apartment so I'd love to minimize impact on existing equipment.
I'm considering 4 locations to connect:

Drill a hole in the cap. I can't use saddle so I guess I'd have to glue the pipe;
Drill a hole on top of the wide tube;
Drill a hole on the side. Too big to use included saddle;
It's drain tube from washing machine.

Currently I'm tempted to go with option (1) because I can easily replace the cap. I like location (4) as well but I wonder if there is a risk contamination of clean water in RO tank when washing machine is draining water.
Where should I connect it? Is there better option that I haven't mention?
Answer: What do the instructions tell you? Are there any warnings about cross contamination?
If not, I would tap into the top of the stub at #2 using the saddle. I don't like having a stub like that because it tends to collect debris but the clean discharge from the RO drain will actually help clear it.
A bigger issue is that S trap! I don't know your location but that's not code compliant anywhere I know of in the US.
Comment: If their instructions tell you to tap into an under-sink drain, I'm sure it's fine on top of #2.
Comment: Yes, interesting that you mentioned S-trap because I just watched video of Florida man who said exactly that :) I'm temporary in the UK and the trap looks suspect to me too.
Comment: As per cross contamination iSpring instruction is fairly brief. Perhaps I should email them.


Unable to resolve open data reader error (needs closing)

Question: Error: There is already an open DataReader associated with this Command which must be closed first
The idea is for getMaxID() to return the highest value in the field + 1- setting this as a new ReportID (for now). However I keep getting the aforementioned error message. I attempted to pass getMaxID() to a variable, and then assign the variable to @ReportID, but still got the error. I've also tried using conn.close(), but no luck. Any help or suggestions would be appreciated.
I've looked at other answers on here, but still can't get rid of the error.
<code> Private Sub addReport()

            Dim Str As String = _
           <String> INSERT INTO
                        Report(
                            ReportID,
                            ScoutID,
                            FixtureID,
                            PlayerID,
                            ReportDate,
                            Comments)
                    VALUES(
                            @ReportID,
                            '2',
                            '3',
                            '6',
                            '10/15/2014',
                            @comments)
           </String>

            Try
                Using conn As New SqlClient.SqlConnection(DBConnection)
                    conn.Open()
                    Using cmdQuery As New SqlClient.SqlCommand(Str, conn)
                        cmdQuery.Parameters.Add("@ReportID", SqlDbType.Int).Value = getMaxID("ReportID", "Report")
                        cmdQuery.Parameters.Add("@Comments", SqlDbType.VarChar).Value = txtComments.Text
                        cmdQuery.ExecuteNonQuery()
                    End Using
                End Using

                MsgBox("Report Added")

            Catch ex As Exception
                MsgBox("Add Report Exception: " & ex.Message & vbNewLine & Str)
            End Try

        End Sub

            Public Function getMaxID(ByVal fieldName As String, ByVal tableName As String) As Integer

                Dim newID As Integer
                Dim Str = "SELECT MAX(" & fieldName & ") FROM " & tableName & ""

                Try
                    Using conn As New SqlClient.SqlConnection(DBConnection)
                        conn.Open()
                        Using cmdQuery As New SqlClient.SqlCommand(Str, conn)
                            cmdQuery.ExecuteReader()

                            If IsDBNull(cmdQuery.ExecuteScalar()) = True Then
                                newID = 1
                            Else
                                newID = cmdQuery.ExecuteScalar()
                                newID = newID + 1
                            End If

                        End Using
                    End Using

                Catch ex As Exception
                    MsgBox("Generate Max ID Exception: " & ex.Message & vbNewLine & Str)
                End Try

                Return newID

            End Function
</code>
Comment: In getMaxID, you are doing a ExecuteScalar right after a ExecuteReader. The ExecuteReader is pointless, close the reader or remove the ExecuteReader.
Comment: In addition to above your code will ExecuteScalar twice if its not null.  store the result of the call in a local variable and test that rather than call twice.
Answer: You are executing ExecuteScalar after a ExecuteReader. The ExecuteReader returns a reader that needs to be closed before. I would suggest you use the IsNull function in sql to simplify your function.
<code>        Public Function getMaxID(ByVal fieldName As String, ByVal tableName As String) As Integer

            Dim newID As Integer
            Dim Str = "SELECT IsNull(MAX(" & fieldName & "), 0)+1 FROM " & tableName & ""

            Try
                Using conn As New SqlClient.SqlConnection(DBConnection)
                    conn.Open()
                    Using cmdQuery As New SqlClient.SqlCommand(Str, conn)
                        newID = cmdQuery.ExecuteScalar()
                    End Using
                End Using

            Catch ex As Exception
                MsgBox("Generate Max ID Exception: " & ex.Message & vbNewLine & Str)
            End Try

            Return newID

        End Function
</code>
I would strongly suggest you do not concatenate strings for the sql and also, if possible, use the auto increment properties that already exists in sql server.


scp + Avoid copy if the same file name located on remote machine?

Question: Is there any option to tell scp command - not copy file from current machine in case file exists on remote machine
For example
On my machine I have the file -
/etc/secret-pw.txt

On Remote machine I have also the file -
/etc/secret-pw.txt

So
scp /etc/secret-pw.txt $remote_machine:/etc

Will destroy the secret-pw.txt, and scp will not ask questions about: overwrite the target file
Is there any option to avoid copy if file exist on target machine by scp?
Update: I can't install rsync or any other program.
Comment: in my bash script + expect script  I use the scp command - to copy files between  one machine to a nothers
Comment: Do you have GNU tar on both sides?
Comment: about the tar command I guess yes ,
Answer: You should be using rsync instead of scp. It will give you what you need.
If you can't install rsync (as you mentioned in the comments) you need to run a script beforehand to check if file exists and run it with ssh.
Comment: I don't have rsync installed on my Linux box , And I cant to installed that command ( because some internal issues )
Comment: Are you able to use Unison?
Answer: SCP does not offer any option, unfortunately.
But you can resort standard tools, like this:
ssh $remote_machine -- cp --no-clobber /dev/stdin /etc/secret-pw.txt < /etc/secret-pw.txt

Note that with this trick you gain all the functionalities of cp.
Comment: or: `ssh $remote_machine -- cp --no-clobber /dev/stdin /etc/secret-pw.txt < /etc/secret-pw.txt`


Why can't we divide set?

Question: We can multiply sets , add and subtract sets which are called union and intersection. But why can't we divide sets?
Comment: You can *partition* a set into disjoint subsets, whose union exactly matches the original set.  I suppose that if you add the constraint that each subset has the same number of elements, that might be construed as *dividing* the set.
Comment: Intersection doesn't really behave like subtraction, and the set operation that behave more like addition is *disjoint* union, not regular union.
Comment: Re my previous comment, one example that involves a set with an infinite number of elements is: *dividing* the integers into $~\{\cdots, -3, 0, 3, \cdots\}, ~\{\cdots, -2, 1, 4, \cdots\}, ~\{\cdots, -1, 2, 5, \cdots\},~$ where the partitioning is based on the remainder, when the number is divided by $(3)$.
Answer: You can, but you need more structure.  They are called quotient groups and quotient rings.
By multiply sets I assume you mean the Cartesian product.  It is also possible to define lots of other kinds of product.  For some of those, the inverse operation will make sense and you have division.
Comment: Actually, I would argue that a set can be *divided* without the set being associated with any operation on the elements of the set.  See my comment following the question.
Answer: Division is the opposite of multiplication. If you consider set multiplication to be intersection, then we want an operation that, in some sense, 'undoes' intersection. Let this operation be denoted $\oslash$. Then,
$A\cap B=C\implies A=C\oslash B$
Now, perhaps with a Venn diagram, think about what you could do with $C$ and $B$ to recover $A$. Is there such an operation? If there is, it's not very useful, because the answer isn't unique $-$ you could modify $A$ into $A'$ so that it includes more elements that aren't in $B$. Then $A\cap B=A'\cap B$. So what should $C\oslash B$ yield, $A$ or $A'$? We don't know. So $\oslash$ isn't useful to think about.

Why can't we divide set?


Does equipping the whole set gives any additional bonus?

Question: I recently thought of buying a Cain's Fate set to level up faster. In the game and on Battle.Net website it says:

(2) Set:

Attack Speed Increased by 2%

(3) Set:

10% Better Chance of Finding Magical Items
Increases Bonus Experience by 30%

Does equipping the whole set(4 items) give any more bonuses?
Comment: I would bet the answer is no, but I will make this just a comment since I am not completely sure having stopped playing Diablo III after completing it once on normal. But starting about the time of Burning Crusade in WoW Blizzard started to give all set boni at 4/5 items since this gives you more flexibility by allowing you to swap one of the set items out. They once commented on this being desirable in their opinion.
Answer: Unless the bonus is identified on the items, no. In your example, putting on four pieces of Cain's Fate would not give you an additional bonus over putting on three pieces.
If, for example, you picked up a set that had bonuses for 4 or 5 pieces, then these sets would give additional bonuses as detailed on the items for equipping more pieces of the set.


Android Chrome input onkeydown

Question: I have reduced this to the minimum code to show this problem. The problem is that this works fine on Chrome on my computer, but on Chrome on my Android, it doesn't work properly. First, the highly simplified code:

  <input type='text' id='myinput' value='example'
  onkeydown='return kd(event);'>

On my computer, I put the cursor in the box that says example. I press any key. The word "example" goes away and whatever letter I pressed appears.
Now, on Android/Chrome, I put the cursor in the box that says example. I press any key. The word "example" goes away, but the letter I pressed does not appear. If I press another key, it will show that letter. I can keep typing. It simply refuses to show the first letter I press.
This apparently has to do with the value='' part of the javascript. If I comment out that line, it works fine (but doesn't erase the word "example" when pressing the first key).
Update: I tested this on an iPhone. It shows the letter of the first keypress properly. So, this is limited to either Android or Android's Chrome.
Answer: Clear the text on input focus
$('input').val('');

and its better practice to use keyup event since users tend to drag their fingers on the keyboard you want make sure you get what they intended

Android Chrome input onkeydown


passing variable as JQuery CSS selector not working

Question: Here is my first part of the code:
$('ul li').click(function(){ //when an
 is clicked

    $('ul .clicked').removeClass('clicked'); // remove .clicked class from any other
's inside a

    $(this).addClass('clicked'); // add .clicked class to the clicked
 ($(this))

    screen = $(this).attr('id'); // screen = the clicked elements' id
    screen = "#" + screen; // screen = the clicked elements' id with a # infront of it
    $(screen).screenSlide(); // is basically = $('#elementsID').screenSlide();, correct?
});

It's weird because in a previous function which I wrote, I did the exact same thing except the last step, instead of passing screen as a selector, I pushed screen inside an Array and then I grabbed array[0] (which was #elementsID without any quotations) and used that as a selector and it worked. But moving forward, screenSlide is
function screenSlide(){ // $(this) should = an
 who's id is screen
    var test = $(this).attr('class');
    alert(test);
    $(this).addClass('current'); // add the .current class to $(this), which should be an

    $(this).slideDown();
};

now, alert test didn't alert anything, so I'm guessing that passing screen as a CSS selector didn't work. As you can see, the screenSlide function is supposed to add a class to the $(this)
 and then make it slide up.
Any idea on what's wrong?
Comment: @PSL , perfect, worked! And no I wasn't duplicating ID's, you are right, I could've just down screenSlide(this);
Comment: Do you mean that the alert box shows up with `undefined`, or does it not show up at all?  Also, are there any errors in the console?
Comment: Why don't you just call `screenSlide(this);`?
Comment: @SuperScript , when I do that, the alert box says undefined.
Comment: Are you duplicating ids?
Answer: The way you have defined it, screenSlide is just a function, not attached to jquery object. Inorder to be invoked as a function on jquery object you need to add it as $.fn.screenSlide.
$.fn.screenSlide = function(){
    var test =this.attr('class');
    alert(test);
    this.addClass('current'); // add the .current class to $(this), which should be an

    this.slideDown();
    return this; //return this to enable chaining
}

Inside this function you dont need to redefind the jquery object as $(this) since this will already be a jquery object, and also return this to enable it for chaining.
If you want to invoke it separately then you can use function.call
screenSlide.call($(this));

With this this is again jquery object you dont need to do $(this) inside your function all over again.
By the way it seems like you just need to invoke it as $(this).screenSlide(); unless you are duplicating the ids, in which case it won't behave the way you expect anyways.
Demo
Answer: $(screen).screenSlide(); will throw an error saying there is no such method as screenSlide for object because screenSlide is not a method associated with the jQuery wrapper object. You need to write screenSlide as a plugin for that
$.fn.screenSlide = function(){
    var test = this.attr('class');
    alert(test);
    this.addClass('current'); // add the .current class to $(this), which should be an

    this.slideDown();
}

or invoke screenSlide with a custom context like
screenSlide.call($(screen))

Comment: @user2817200 if you write it as a plugin as given above it will be associated with the jQuery wrapper object
Comment: Hm interesting. So how do I make screenSlide a method associated with the JQuery wrapper object?


Drilling into concrete with a cordless drill

Question: I understand that my brushless cordless 20V (Dewalt) drill—because it has a hammer option—
has what it takes
to drill a 16 mm hole into concrete.
I also understand (from the same answer just linked) that I shouldn't just drill directly with 5/8". I have to first drill with maybe 4 mm, 8 mm, and 12 mm, before using the final bit.
I still have a few brief questions regarding drilling into concrete.

The drill bits sold in my area are imperial, not metric. Will a 16 mm anchor bolt give me a hard time when I hammer it into a 15.9 mm hole?

The bottom two feet of my garage wall (outside wall) look like concrete. I'm setting up a bike lock in it. After I install the lock, I'll tug with all I've got to confirm it's firm, but how do I confirm before starting that it's actually concrete?

Since the other side of the wall is outside the house and since this is away from light switches and any water pipes, I'm expecting there are no electricity and no water pipes. What is the likelihood I'll drill into water or electricity when it's a lower outside wall in a garage? Water pipes are never burried in a concrete wall; are they?
Comment: water pipes can come up frm the ground through a concrete wall, it would be quite normal on a slab-built house.
Comment: water pipes and electric conduits might penetrate the concrete but they are newer buried in it.
Comment: as for drill size, start with pilot hole about 1/3 of the final size (16/3 = 6mm or 1/4 inch drill, then use 2/3 of the final size, then final size
Comment: "Buried" as in "encased in" - sure, you'll get water, electrical, and nearly everything else running in your walls if they're made of concrete and you don't see them on the surface. They have to be somewhere, so if they're not visibly attached on the surface, they'll be within it.
Answer: I do not really understand your use of Imperial and Metric. Can you not get the correct drill bit and the correct anchor bolt ? Anyway, you probably will be able to get your 16mm anchor bolt into the 15.9mm hole as the big masonry bits do tend to move around a bit as you are drilling.
If you want to do the step up size drill bits I guess that is OK. You could also rent the correct size hammer drill and a bit from your local rental store. This way you can drill in one shot the correct size hole and maybe even save some $ by not having to buy a bunch of different size drill bits. Drilling a 5/8" hole without having to pre-drill smaller sizes first is done every day.
As far as pipes and conduits in the wall I wholly disagree with some of the comments above. There are definitely pipes and conduits and gas lines in concrete stem walls. Whether there are pipes where you are planning to drill- no one knows. The only sure way to know is to remove some of the wall covering (drywall I would guess) above the stem wall and look. Chances are there is not anything there right where you want to drill but, if there is something there at the least it will cost you time and money to repair (not an easy repair) and you  could greatly harm or kill yourself and others. I am not meaning to rain on your parade but it needs to be said.
Comment: Not everyone can or wants to rent tools or purchase new toys, er, tools. For some it's a "get the job done with what I've got" process. If an impact driver is all that's available, that's what you work with. 100% agree with checking the wall above the concrete (or possibly in the attic above or crawlspace below) for pipes & wiring in the stud bay above where the drilling will take place. Tearing out & replacing drywall to check will be _MUCH_ less work & expense than repairing plumbing or electrical in concrete.


Object is null when passing a string propery of very long length (Base64 String) to .Net webapi Contoller

Question: I am getting  updateCaseHearingModel= null when its property "StrBase64" has a very long string.
We are passing StrBase64 as base64 of a file. it works for small files but fails when file size exceeds 4MB(it creates very lengthy string).
<code>public HttpResponseMessage UpdateCaseHearing([FromBody]UpdateCaseHearingModel updateCaseHearingModel)
       {
                try
                {
                       //Code here
                }
       }
</code>
Is there any way to pass very long string(of an object) to webapi contoller in .Net.
Comment: I think you could try modify config. maxRequestLength, maxJsonLength
Answer: Your application is working fine but your IIS configuration has an limit of 4MB.
See -> https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx
Optional Int32 attribute.
Specifies the limit for the input stream buffering threshold, in KB. This limit can be used to prevent denial of service attacks that are caused, for example, by users posting large files to the server.
The default is 4096 (4 MB).


I can't absorb Dragon souls

Question: I have all the Skyrim DLCs, and a few mods. I can't do the original quest and I can't do shouts (which is really annoying).
I killed the dragon Dumviir (or something like that) in the quest where the Jarl of Whiterun sends you to kill said dragon. But I can't absorb it's dragon soul.
I killed it and all the guards say "she must be Dragonborn!" and they all look scared, but nothing happens. I have all the unofficial patches (skyrim, dawnguard, hearthfire, dragonborn and high res) and SMPC (aka USKP addon) installed but they didn't fix it.
Has anyone else had similar issues?
Comment: About SMPC, you might want to read this post by Arthmoor (one of the USKP developers) about it: [So You Want to Know What's Wrong with SMPC.esp? (The Skyrim Misc Patches Collection - aka USKP_AddOn)](http://afkmods.iguanadons.net/index.php?/topic/3719-the-skyrim-misc-patches-collection-aka-uskp-addon/)
Comment: Can you edit in your mod load order in the question? [BOSS](http://skyrim.nexusmods.com/mods/6/?) can help you with listing and optimizing your load order. The issue you described could possibly be caused by putting your mods in the wrong load order. See my [answer in this related question, "Why can't I absorb a dragon soul?"](http://gaming.stackexchange.com/a/115650/4797) - for more info.
Comment: Have you confirmed the mods aren't causing the problem, by backing up your save(s) and disabling the plugins?
Comment: @ VaishaliI have it on Xbox as well, it's just i don't have the DLC's on that :).
it's the latest Patch version
@sevensideddie I'm fairly sure they're not the problem, but i'll unistall them all and get back to you :)
Comment: I use boss :). it has to be one of my mods cause I took them all off and i absorbed the soul :/. could it be one of the "patches"?
Comment: But, it won't let me absorb in a save game where I already killed dumvnir
Comment: It's unlikely to be a patch, unless you have out-of-date patches (since they have had bugs in the past). (Though it could be SMPC, since it's not well made.) So, standard procedure to isolate the problem is to install the mods a few at a time until it breaks again, then add & remove until it's narrowed down to one mod.
Comment: You probably can't absorb Dumvir's soul on that save because the problem is already saved, probably because the soul wasn't added to the skeleton and the trigger to add it is past. If you have a save before the battle, that *should* be okay.
Answer: Make sure you put the unofficial dragonborn patch after the unofficial skyrim patch in your load order - I had a problem with absorbing souls after installing dragon born, which required the UDP to be included.
See: Why can't I absorb a dragon soul?

I can't absorb Dragon souls


SQL select across multiple tables with max dates in each joined table

Question: I have an Oracle 11 SQL query where I'm pulling data from 4 tables all joined by an ID. The 3 tables joined to the first each have an ACTIVE_IND value that needs to be 'Y' and an effective date (EFF_DATE) and I need the record with maximum effective date from each.
I've got a query that works here, but would like to know if there is a more optimal/effective/efficient way of writing it as it seems a bit slow.  What I'm currently using looks something like this:
SELECT DISTINCT A.TABLE1_ID,
                A.TABLE1_COL1,
                B.TABLE2_COL2,
                C.TABLE3_COL3,
                D.TABLE4_COL4
FROM TABLE1 A,
     TABLE2 B,
     TABLE3 C,
     TABLE4 D
WHERE B.TABLE2_ID = A.TABLE1_ID
  AND B.TABLE2_ACTIVE_IND = 'Y'
  AND B.TABLE2_EFF_DATE =
    (SELECT MAX (B2.TABLE2_EFF_DATE)
     FROM TABLE2 B2
     WHERE B2.TABLE2_ID = B.TABLE2_ID
       AND B2.TABLE2_ACTIVE_IND = 'Y')
  AND C.TABLE3_ID = A.TABLE1_ID
  AND C.TABLE3_ACTIVE_IND = 'Y'
  AND C.TABLE3_EFF_DATE =
    (SELECT MAX (C2.TABLE3_EFF_DATE)
     FROM TABLE3 C2
     WHERE C2.TABLE3_ID = C.TABLE3_ID
       AND C2.TABLE3_ACTIVE_IND = 'Y')
  AND D.TABLE4_ID = A.TABLE1_ID
  AND D.TABLE4_ACTIVE_IND = 'Y'
  AND D.TABLE4_EFF_DATE =
    (SELECT MAX (D2.TABLE4_EFF_DATE)
     FROM TABLE4 D2
     WHERE D2.TABLE4_ID = D.TABLE4_ID
       AND D2.TABLE4_ACTIVE_IND = 'Y')
ORDER BY A.TABLE1_ID;

Answer: Try:
SELECT DISTINCT A.TABLE1_ID,
                A.TABLE1_COL1,
                B.TABLE2_COL2,
                C.TABLE3_COL3,
                D.TABLE4_COL4
FROM TABLE1 A
JOIN (SELECT T2.*,
             RANK() OVER (PARTITION BY TABLE2_ID ORDER BY TABLE2_EFF_DATE DESC) RN
      FROM TABLE2 T2
      WHERE TABLE2_ACTIVE_IND = 'Y') B ON B.TABLE2_ID = A.TABLE1_ID AND B.RN=1
JOIN (SELECT T3.*,
             RANK() OVER (PARTITION BY TABLE3_ID ORDER BY TABLE3_EFF_DATE DESC) RN
      FROM TABLE3 T3
      WHERE TABLE3_ACTIVE_IND = 'Y') C ON C.TABLE3_ID = A.TABLE1_ID AND C.RN=1
JOIN (SELECT T4.*,
             RANK() OVER (PARTITION BY TABLE4_ID ORDER BY TABLE4_EFF_DATE DESC) RN
      FROM TABLE4 T4
      WHERE TABLE4_ACTIVE_IND = 'Y') D ON D.TABLE4_ID = A.TABLE1_ID AND D.RN=1
ORDER BY A.TABLE1_ID;

Comment: Thanks Mark.  Seems to work once I adjusted the 3 RN labels to be unique. I initial got a `ORA-00918: column ambiguously defined` error.
Comment: Oops, seems I just missed the qualifiers, e.g. "B.RN=1".
Comment: @Brandon: Originally, I forgot to make the RN labels unique - about half an hour later I noticed my oversight and fixed it.


my python code has an error involvinf % calculator and I can't find it

Question: first, I'd like to mention that I'm a total novice in the areas of programming and mathematics. Can somebody please explain me why the result isn't 0?
variable_1 = 360*2305567963945518424753102147331756070
variable_2 = variable_1/1
variable_3 = variable_2 % 360

result => 72.0
Comment: In my terminal the result is `0L`
Comment: in jupyter and python3.6 console, the result was 72.0. However, the answer was 0 in R
Answer: you need  the decimal module for convert scientific no to no
your first output of * is too big so it converts into scientific no
import decimal

variable_1 = 360*2305567963945518424753102147331756070
print variable_1

variable_1 = decimal.Decimal(variable_1)
print variable_1

variable_3 = variable_1 / 360
print variable_3

for % use long
variable_3 = long(variable_1) % 360

Comment: Now it says
variable_3 = variable_1 % 360  ==> print (variable_3) ==>
decimal.InvalidOperation: []
Comment: use long or int over   variable_3 = long(variable_1) %360
Comment: seems like long doesn't exist in 3.6. I found no error while handling large numbers in 2.7... guess I'll have to work with 2.7 instead


Is it possible to destroy the air-ship?

Question: On the final level of Moody Clouds, you find yourself chasing an air-ship on mosquito back. At various points throughout the level, you have an opportunity to shoot at the air-ship, inflicting apparent damage as you shoot off rudders, doors and other various bits of the ship.
At the end of the level, the ship collides with some sort of power core, causing a massive explosion. Is it possible to completely destroy the air-ship before that point, or is the damage incurred by the air-ship merely cosmetic?
Answer: I used an autoclicker so it would fire the bullets as fast as possible, and it only destroys the ship until you kill the enemy that is in the bottom, so I guess it's just cosmetic.
Comment: Enemy in the bottom of what? The ship?

Is it possible to destroy the air-ship?


How do I use magic in multiplayer mode?

Question: In multiplayer mode, the player can choose which magic ability to use, but it's not obvious why it doesn't always work when the player presses R2. What's the secret to using magic in multiplayer mode?
Answer: It may seem counter-intuitive, but you do not start with a full magic bar. To use magic, you must find a blue magic well and walk over it. This will give you 50 magic, which is denoted by the blue bar underneath your health bar.  You can do this again, for a maximum of 100 magic, which makes the magic bar turn a lighter color. At this point, you can't take magic from a well since you are full, but your spell will now work when you press the button.
Note also that some magic spells only require 50 magic, where others require 100.

How do I use magic in multiplayer mode?


Trying to run live usb of 16.04 Intel NUC5PPYU

Question: I already have 14.04 running and would like to try 16.04 as live usb however it only gets part way through and hangs. My system is an Intel NUC5PPYH 64bit. I have already tried running a 14.04 DVD
to make sure it's not the computer and that works as a try before you install.I'm reluctant to try to do a complete install of 16.04
as it would seem to be software related.
Comment: look at this [bug report](https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1512995) . Also, do you have the [latest updates](http://drivers.softpedia.com/blog/Intel-s-NUC5PPYH-and-NUC5CPYH-NUC-Kits-Receive-Drivers-Download-Now-480165.shtml) ?
Comment: I found a solution on this computer . Go to the bios press F2 and set the advanced option to Linux  . Then reboot press F10 and choose the USB device you want to load 16.04  from.
Comment: Great. You should answer your own question in the answer space and accept it. :)
Answer: You need to change some options on the bios setup.
While the nuc is starting, press F2 to enter the BIOS setup. Then follow this path:
<code>BIOS > Boot > Boot Configuration > OS Selection > set Linux
</code>
This fixed it. With older kernels there is no need to do this.
Source: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1521749
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1529353


When does command substitution spawn more subshells than the same commands in isolation?

Question: Yesterday it was suggested to me that using command substitution in bash causes an unnecessary subshell to be spawned. The advice was specific to this use case:
# Extra subshell spawned
foo=$(command; echo $?)

# No extra subshell
command
foo=$?

As best I can figure this appears to be correct for this use case. However, a quick search trying to verify this leads to reams of confusing and contradictory advice. It seems popular wisdom says ALL usage of command substitution will spawn a subshell. For example:

The command substitution expands to the output of commands. These commands are executed in a subshell, and their stdout data is what the substitution syntax expands to. (source)

This seems simple enough unless you keep digging, on which case you'll start finding references to suggestions that this is not the case.

Command substitution does not necessarily invoke a subshell, and in most cases won't. The only thing it guarantees is out-of-order evaluation: it simply evaluates the expressions inside the substitution first, then evaluates the surrounding statement using the results of the substitution. (source)

This seems reasonable, but is it true? This answer to a subshell related question tipped me off that man bash has this to note:

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

This brings me to the main question. What, exactly, will cause command substitution to spawn a subshell that would not have been spawned anyway to execute the same commands in isolation?
Please consider the following cases and explain which ones incur the overhead of an extra subshell:
# Case #1
command1
var=$(command1)

# Case #2
command1 | command2
var=$(command1 | command2)

# Case #3
command1 | command 2 ; var=$?
var=$(command1 | command2 ; echo $?)

Do each of these pairs incur the same number of subshells to execute? Is there a difference in POSIX vs. bash implementations? Are there other cases where using command substitution would spawn a subshell where running the same set of commands in isolation would not?
Comment: I don't think I would take your second quote as any kind of authoritative information about how `bash` is implemented. However, I would note that subshell != process; a subshell (in the sense of a new scope for variables) is not required to spawn a new process to run it. (This is the third point made in the accepted answer to your linked question.)
Comment: @chepner If I had taken that as authoritative I probably wouldn't be asking here. The point here is to get the issue de-mystified a bit in a peer reviewed environment. I realize what a subshell even is is probably something an answer will need to clarify on order to give a sensible explanation as to when "unnecessary" resources are being used.
Comment: The second quote's comment "There aren't any builtins that explicitly mean 'subshell';" is at best misleading and in my view flat-out wrong (and has caused me not to read the rest of the article). The `( ... )` explicitly creates a sub-shell; the commands within the parentheses must be executed in a sub-shell (meaning that any changes made to variables etc must not affect the main shell). That used to be done by forking and letting the child execute the contents of the sub-shell script while the parent waits for it to complete. A shell might avoid that if it has good enough scoping abilities.
Comment: This question has some related info: [Command substitution vs process substitution](http://stackoverflow.com/q/15416570)
Comment: @JonathanLeffler to be fair, if you read the exchange further down he recants, although in a somewhat obtuse way.
Comment: @kojiro: yes, he does, but because the posting leaves an ambiguous message, rather than being rewritten to present the final view unambiguously, or point to where the final view is presented unambiguously, it leaves the posting as 'of dubious merit' as a source of information.
Comment: See http://stackoverflow.com/a/41315367/717267
Answer: Update and caveat:
This answer has a troubled past in that I confidently claimed things that turned out not to be true. I believe it has value in its current form, but please help me eliminate other inaccuracies (or convince me that it should be deleted altogether).
I've substantially revised - and mostly gutted - this answer after @kojiro pointed out that my testing methods were flawed (I originally used ps to look for child processes, but that's too slow to always detect them); a new testing method is described below.
I originally claimed that not all bash subshells run in their own child process, but that turns out not to be true.
As @kojiro states in his answer, some shells - other than bash - DO sometimes avoid creation of child processes for subshells, so, generally speaking in the world of shells, one should not assume that a subshell implies a child process.
As for the OP's cases in bash (assumes that command{n} instances are simple commands):
# Case #1
command1         # NO subshell
var=$(command1)  # 1 subshell (command substitution)

# Case #2
command1 | command2         # 2 subshells (1 for each pipeline segment)
var=$(command1 | command2)  # 3 subshells: + 1 for command subst.

# Case #3
command1 | command2 ; var=$?         # 2 subshells (due to the pipeline)
var=$(command1 | command2 ; echo $?) # 3 subshells: + 1 for command subst.;
                                     #   note that the extra command doesn't add
                                     #   one

It looks like using command substitution ($(...)) always adds an extra subshell in bash - as does enclosing any command in (...).
I believe, but am not certain these results are correct; here's how I tested (bash 3.2.51 on OS X 10.9.1) - please tell me if this approach is flawed:

Made sure only 2 interactive bash shells were running: one to run the commands, the other to monitor.
In the 2nd shell I monitored the fork() calls in the 1st with sudo dtruss -t fork -f -p {pidOfShell1} (the -f is necessary to also trace fork() calls "transitively", i.e. to include those created by subshells themselves).
Used only the builtin : (no-op) in the test commands (to avoid muddling the picture with additional fork() calls for external executables); specifically:

:
$(:)
: | :
$(: | :)
: | :; :
$(: | :; :)

Only counted those dtruss output lines that contained a non-zero PID (as each child process also reports the fork() call that created it, but with PID 0).
Subtracted 1 from the resulting number, as running even just a builtin from an interactive shell apparently involves at least 1 fork().
Finally, assumed that the resulting count represents the number of subshells created.

Below is what I still believe to be correct from my original post: when bash creates subshells.

bash creates subshells in the following situations:

for an expression surrounded by parentheses ( (...) )

except directly inside [[ ... ]], where parentheses are only used for logical grouping.

for every segment of a pipeline (|), including the first one

Note that every subshell involved is a clone of the original shell in terms of content (process-wise, subshells can be forked from other subshells (before commands are executed)).
Thus, modifications of subshells in earlier pipeline segments do not affect later ones.
(By design, commands in a pipeline are launched simultaneously - sequencing only happens through their connected stdin/stdout pipes.)
bash 4.2+ has shell option lastpipe (OFF by default), which causes the last pipeline segment NOT to run in a subshell.

for command substitution ($(...))
for process substitution (<(...))

typically creates 2 subshells; in the case of a simple command, @konsolebox came up with a technique to only create 1: prepend the simple command with exec (<(exec ...)).

background execution (&)

Combining these constructs will result in more than one subshell.
Comment: I don't think your results are valid, because ps isn't fast enough to capture some of those subshells you create above. For example, you say *an expression surrounded by parentheses does not run in a child process for simple commands*, but try continuously outputting `ps` while running `for i in {0..999999}; do ( : ); done`. You won't see every new process, but you'll see some, and the number of PIDs the system goes through increases rapidly.
Comment: How did you test for the creating of a new process?
Comment: @kojiro: Excellent catch, thanks. Not that it matters any longer, but how would you test in the absence of `$BASHPID`? I'll update my answer.
Comment: @mklement0 That's tough. My first attempts were on Mavericks (which still has Bash 3, sigh), and I ended up trying long loops with many tiny subshells in them. On Linux with Bash 3 you may be able to use /proc/self, but since OS X doesn't have /proc, Bash 3 doesn't have BASHPID, and `( sh -c 'echo $$PPID' )` violates some invariants of the question, I don't feel there's a clean solution.
Comment: @kojiro: Thanks; I've come up with something based on `sudo dtruss -t fork -f -p {pid}` on OSX; would you mind taking a look at the updated answer and tell me whether that looks sound?
Answer: In Bash, a subshell always executes in a new process space. You can verify this fairly trivially in Bash 4, which has the $BASHPID and $$ environment variables:

$$ Expands  to  the  process ID of the shell.  In a () subshell, it expands to the process ID of the current  shell,  not  the  subshell.
BASHPID Expands to the process id of the  current  bash  process.   This differs  from  $$ under certain circumstances, such as subshells that do not require bash to be re-initialized

in practice:
$ type echo
echo is a shell builtin
$ echo $$-$BASHPID
4671-4671
$ ( echo $$-$BASHPID )
4671-4929
$ echo $( echo $$-$BASHPID )
4671-4930
$ echo $$-$BASHPID | { read; echo $REPLY:$$-$BASHPID; }
4671-5086:4671-5087
$ var=$(echo $$-$BASHPID ); echo $var
4671-5006

About the only case where the shell can elide an extra subshell is when you pipe to an explicit subshell:
$ echo $$-$BASHPID | ( read; echo $REPLY:$$-$BASHPID; )
4671-5118:4671-5119

Here, the subshell implied by the pipe is explicitly applied, but not duplicated.
This varies from some other shells that try very hard to avoid fork-ing. Therefore, while I feel the argument made in js-shell-parse misleading, it is true that not all shells always fork for all subshells.


Pigtail solution?

Question: I have a celing fan in one room, a light with three 60 watt bulbs in the kitchen. They are both controlled by switches, but one turns off and the other one turns on. Can I pigtail them together on the same switch? I've identified which wires I need to put together.
Comment: @Mike -- can you post photos of the insides of the other switch boxes involved please?
Comment: We'd need to see some pictures of the boxes, switches involved.
Comment: The two wires in question are the blue and yellow wires going through the conduit in the top of the switch box
Comment: Am I seeing right that someone used a yellow wire for ground?!
Comment: The wiring I'm seeing doesn't seem to make sense. I see three wires going up (I assume) to the fixtures. One is coming off one switch and two off the other. I don't see a neutral anywhere unless the right-hand switch is switching the neutral. I don't know who wired this but if this is a representative sample of your house wiring, I'd kill the main breaker and not turn it back on until I got an electrician in to check everything.
Comment: @DoxyLover That wire's behind the grounding bracket... stay safe out there. Possibly in a backstab.
Comment: There is a separate neutral running through the condominium, the main line for power I identified the orange as the incoming voltage from the top. The wires on the bottom lead to another three way switch on the other side of the kitchen
Comment: What is your location in the world?  I am also wondering if the wiring was modified from original.
Answer:
There is a separate neutral running through the condominium,

That's completely illegal.  Nobody is allowed to wire like that.
You can't have a master neutral that everything goes back to!  Right off the bat, it would overload. It would also trip every GFCI and AFCI!
All the related conductors must be grouped together.  So the neutral must come along with the hot(s).
Another way of saying that is that the currents in each of the wires in a cable or conduit must be equal/cancel each other out/etc.
Another way of saying that is current can't flow in a big loop.  It can't go from lamp to switch 1 to switch 2 back to lamp.
Another way of saying that is that cables or conduits must be laid out in a tree topology, i.e. you can have branches but you cannot have pipes looping back to each other.  If wire (or sequence of wires) could exit out one conduit, go through different conduits and reenter the same box from another conduit, that is a loop. You can't have those.
So this whole thing is seriously messed up.
The good news is, this is conduit.  So neutrals or other appropriate wires can simply be added to the pipe as needed.
I find it difficult to believe someone took delivery of a house where a light cannot be turned off.  Are these switch changes your work?
Comment: @Mike OK so the neutrals (which are the real problem) were like this before, and you added 4-ways (which are probably fine).  And you just want to make the light work, and don't care about the code violations since they seem only statutory and not a threat.   The problem is, first they are a threat, and second it's *really hard* to try to fix *only part of* bad work.  I mean, it's unfamiliar territory for anyone competent.  They wouldn't know *how*.  So I suggest a more systematic review.
Comment: No, I added some 4 way switches later on. This is what I had to work with, the neutral wires are behind the light fixtures. I saw that when I installed a remote for a ceiling fan. You can turn the lights off. I just was wondering if two can be on at the same time.
Comment: I'm really not looking forward to ripping out drywall, plus it's a concrete ceiling with conduit buried in it. This was my girlfriend's place, I started to do a little remodeling and found this mess, thanks.
Comment: @Mike fear not the conduit. You won't need to futz with the pipe itself, the scope of the project only includes pulling new wires into the existing pipe.   I had to  fix a whole factory full of bad wire in conduit, was not that bad.
Comment: Maybe it would be easier to run separate wires and a breaker for just the kitchen light.

Pigtail solution?


Are there other uses for the Elder Scroll?

Question: In Skyrim I've finished the main quest but I still have the Elder Scroll. There's a funky visual effect when I try to read it but it doesn't seem to do anything. Is there any point hanging on to it now (maybe there's another special location where something happens if you read it there?) or should I just store it or sell it?
Comment: Since they are indestructible, you could use them as an armor. ☺
Answer: You can donate it to the Orc Librarian in the College Of Winterhold, for about 2000 gold and his eternal gratitude.
Aside from that I don't think there is anything you can do with it.
Answer: The elder scroll you gain from the main quest is now used in the Dawnguard DLC as well. If you sold it to the orc you'll have to buy it back from him for 4000 gold. You also gain two more elder scrolls. The new two can be sold to the Moth Priest for 6000 gold in the Dawnguard DLC if you sided with the Dawnguard. Alternatively you can just give him the scrolls for free (much to his astonishment).
Comment: The item has a stated weight of 20 each but in actuality they weigh nothing and don't contribute to your encumbrance. If you can't find the priest or sided with the vampires, you cannot remove them.
Comment: I have three scrolls and they are using up 60 weight in my pack. I can't stash them. The orc doesn't have a dialog option to take them and the priest isn't in the Dawnguard fortress. How do I get rid of them?


Select with group by and max date

Question: this probably is a duplicate question but I can't seem to figure out how to implement the previous suggestions.
my data looks like this for what matters:
drawing    method       Location        thk_date
314C0010   UT       05.01       2016-05-24
314C0010   UT       05.01       2011-10-26
314C0010   UT       06.01       2016-05-24
314C0010   UT       07.01       2016-05-24

When my select executes for location 05.01 I only want the row with the latest thk_Date
Here is my statement which just gets all the records.
SELECT Distinct
   t.[Id]
  ,t.[SurveyNumber]
  ,t.[TPLATFORM]
  ,t.[DRAWING]
  ,r.[Desc]
  ,t.[METHOD]
  ,t.[LOCATION]
  ,t.[THK_DATE]
  ,t.[THICK]
  ,t.[MEAS_THK]
  ,t.[COMMENTS]
  ,t.[EXCLUDE]
  ,t.[PAINT]
  ,t.[CF1]
  ,t.[CF2]
  ,t.[CF3]
  ,t.[NF1]
  ,t.[NF2]
  ,t.[Year]
  ,t.[Completed]
  ,t.Created
  ,t.CreatedBy
  ,t.ModifiedBy
  ,t.Modified
  ,YEAR(THK_DATE)
  ,t.Inservice

FROM Thk t
left JOIN ref r ON r.[DRAWING] = t.[DRAWING]
left JOIN eng e ON e.[DRAWING] = t.[DRAWING]

WHERE t.SurveyNumber = @SurveyNumber
AND t.[Year] = @Year

ORDER BY t.DRAWING, t.Method, t.[LOCATION], THK_DATE desc

How do I get only the rows with the max(thk_date)? I have tried to group and select top 1 but only get one record.
Answer: You can use ROW_NUMBER() for this.
Since you haven't given other tables' structure, here is an example.
declare @Drawings as
Table(drawing varchar(100),
      method varchar(2),
      Location varchar(10),
      thk_date DateTime)

INSERT INTO @Drawings
VALUES
('314C0010', 'UT','05.01','2016-05-24'),
('314C0010', 'UT','05.01','2011-10-26'),
('314C0010', 'UT','06.01','2016-05-24'),
('314C0010', 'UT','07.01','2016-05-24')

;WITH CTE AS
(
select row_number() over(partition by Location order by thk_date desc) as rn,*
from @Drawings
)

select * from CTE where rn=1

Fiddle here
Comment: ;WITH CTE AS
(
select row_number() over(partition by drawing, location order by thk_date desc) as rn,*
from #Temp
)

Select with group by and max date


Manually scheduled task is moved in time but it shouldn't. Why is that?

Question: I expected that manualy scheduled tasks will not change their dates automatically despite of all other things happened in the project. My Boss says that meeting will be at some fixed date. All previous and later tasks must adjust to that date.
Manipulating the task dates prior to the meeting dates constantly change the fixed dates of the meetings "over and over". I must still remember that the meeting dates might be changed without notice. And what if I have 5 meetings in my project?
That behaviour makes lots of dalay in my work on my project. It takes me as lot as 1 working day of work to prepare 40 task's project.
Help me with this, please. It seems my work is not effective. Why is that?
Chris
Answer: I am guessing that you are using MS Project 2010, which introduces "Manually scheduled tasks" as a separate concept to "Auto-scheduled tasks with inflexible constraints".
Under the Options dialog -> Schedule tab -> Section labelled "Scheduling options for this project", look for a check box that is labelled "Update Manually Scheduled tasks when editing links". If this box is checked, that may result in manually scheduled tasks being moved around as you described, so make sure that it is unchecked.
Hope that helps.
Comment: Like the creator of this thread and probably anybody else I would've expected that a manual set date would never change automatically. What's even worse that it often happens unnoticed... Glad I found your answer, thank you so much!
Answer: This depends on the kind of constraint. There are

Flexible
Semi-Flexible
Inflexible

I'd assume you're using a semi-flexible constraint while you really want to use an inflexible one. Microsoft's online help describes constraints in detail - this should solve your problem.


Autoexec.bat equivalents for Ubuntu that run with root privelidges?

Question: On Ubuntu there must be several "autoexec.bat" equivalents as I can see files like rc.local which seem to do very little because the comments in the file says it doesn't work by default and I tried putting this command in there and it didn't work.
What I need to know is where I place this line.
echo 0 | /usr/bin/tee -a /sys/class/leds/smc::kbd_backlight/brightness

I also saw a rc.local in /etc/init.d as well but where I would place the cmd to make it work is a mystery as there are two functions in there so do I place it at the end of one of those functions or at the last line?
The command needs root permission to run and ideally it should be executed when the computer starts. As the command dims the keyboard of my MacBook Air.
Also, I would also like to know what file I'd need to edit if only a specific user would have this command run. As its an root command and I don't want to give admin or sudo access to that user I would like this command to execute as root when the user logs in and the user cannot stop that command from running.
Additional Discoveries
$HOME/.profile is the login script but doesn't run as root, it works if you sudo the command but thats not want I need.
The /etc/profileis weird, it doesn't execute at boot but when I go into a shell and execute sudo -i" it runs as soon as the sudo goes into interactive mode
A neat short cut
With version 14.04, might have worked in earlier versions, you simply add a line to crontab using sudo crontab -e and add a line "@reboot whatevercommandwithfullpath" and it works. But with this new version I created a upstart script which is closer to how it should be done.
Comment: `/etc/profile` is not supposed to execute at boot. It runs for all Bourne-style login shells, when the shells start. So, it runs together with `.profile` files in users' home directories.
Answer: You can create a daemon witch is the right way to do it. However it's a little harder than rc.local.
see here : https://superuser.com/questions/530071/installing-daemon-on-a-fresh-ubuntu-system
detailed help (you can take example of /etc/init.d/hostname) :
copy the skeleton :
sudo cp /etc/init.d/skeleton /etc/init.d/keyboard_backlight

edit the skeleton :
sudo nano /etc/init.d/keyboard_backlight

search for this
do_start()
{
        # Return
        #   0 if daemon has been started
        #   1 if daemon was already running
        #   2 if daemon could not be started
        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
                || return 1
        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
                $DAEMON_ARGS \
                || return 2
        # Add code here, if necessary, that waits for the process to be ready
        # to handle requests from services started subsequently which depend
        # on this one.  As a last resort, sleep for some time.

}

and change it like this :
do_start()
{
        echo 0 | /usr/bin/tee -a /sys/class/leds/smc::kbd_backlight/brightness
}

Comment out or delete the lines inside the do_stop and the do_reload
do_stop()
{
}
do_reload()
{
}

Save the file.
Give the execution permission to the file :
sudo chmod 755 /etc/init.d/keyboard_backlight

Test your service :
sudo /etc/init.d/keyboard_backlight start

If everything ok, load your service for startup
sudo update-rc.d keyboard_backlight defaults 99

Best regards.
Answer: Maybe, for login shells they run in this order:
1./etc/profile
2./etc/profile.d/ files
3.$HOME/.bash_profile
4.$HOME/.bash_login

However, I'm unsure if the /etc/profile gets executed before any users actually login but it is worth trying just in case I am right.
Answer: Is this still working?

This script will run before the graphical interface appears...

Make the script with desired commands. vi file.sh
Copy the script to /etc/init.d cp file.sh /etc/init.d/file.sh
Change permission to allow execution chmod +x /etc/init.d/file.sh
At /etc/init.d Link it! sudo update-rc.d file.sh start 99 2 . (do not forget the "." at the end of the command)

If you need to disable this script in a near future: sudo update-rc.d
  -f file.sh remove

It seems quite easy this way and you can keep different scripts for different things
Answer: most probably you are looking for /etc/rc.local
if you add any command before exit 0 that should run as root.
Don't forget to change permisson to executable for both /etc/rc.local and /etc/init.d/rc.local unless it won't work, leave as is if they are already executable.
Comment: Did that already, I mentioned that in my original question. Command executes as I redirected output to my home directory so I know it executed. But the command itself didn't dim the keyboard :(
Answer: Let's say that you have a working script (with the right file permissions),  with the name myscript.sh;
cd to to the folder that you have the script in and do:
sudo cp myscript.sh     /etc/profile.d/

This will copy the script to a place that contains scripts that are executed on boot so that the next time you boot it should work.


gradle custom task class makes itself uncompilable

Question: I'm trying to write a custom Gradle task class and use it in another subproject. I'm having problems tying the build together.
In this example, I have named the subprojects "a" (for application) and "p" (for plugin, although I'm not using a plugin object but just providing a task class to the build script).
settings.gradle
include 'p'
include 'a'

p/build.gradle
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'maven-publish'

group 'test'
version '1.0'

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }
}

dependencies {
    implementation gradleApi()
    implementation localGroovy()
}

p/src/main/groovy/p/MyTask.groovy
package p

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;

class MyTask extends DefaultTask {
    @TaskAction
    void run() {
        System.out.println('yay!');
    }
}

a/build.gradle
buildscript {

    repositories {
        mavenLocal()
    }

    dependencies {
        classpath 'test:p:1.0'
    }

}

group = 'test'
version = '1.0'

apply plugin: 'java'

task myTask(type: p.MyTask) {
}

The "plugin" is built by running, inside the p folder:
../gradlew clean build publishToMavenLocal

Inside the a folder:
../gradlew myTask

prints "yay!"
However, while developing, bugs happen. When I simulate a bug in MyTask:
MyTask() {
    throw new RuntimeException("an error");
}

and build the plugin (in folder p):
../gradlew clean build publishToMavenLocal

it fails as expected.
Now I "fix" the bug by removing the broken constructor again, and rebuild in folder p:
../gradlew clean build publishToMavenLocal

but this command fails with the same error.
As far as I understand, the reason is that:

the broken plugin is in my local maven repo
trying to build the plugin detects the settings.gradle in the parent folder
gradle tries to configure all projects referenced from settings.gradle
this loads the broken plugin
the build fails

To verify, I comment out the include line for a in settings.gradle, and it works again. Reverting settings.gradle, and it still works, because now the "fixed" plugin is in my maven repo, and rebuilding the plugin will just overwrite it again with the working version.
The bottom line is that bugs in my custom task class (or custom plugin, or any other buildscript code) have the potential to make themself un-compilable, with the workaround being to edit or temporarily rename settings.gradle. The more complex the project gets, the more cumbersome this becomes: Renaming does not work if the plugin code itself contains multiple subprojects, and even commenting out becomes "commenting out the right lines".
What is the intended way to fix this problem?
Answer: Complex logic for a single (multi-) project is best organized in buildSrc. You can for the most part regard it as a normal sub-project but just for the build classpath instead. Plugins and tasks that you create here are automatically available for all projects in the multi-project.
If, for some reason, you rather continue to work with a local Maven repository, you could think about publishing stable releases of the plugin with a version number so it is easier to roll back.
Comment: The problem occurs while developing the plugin, not for stable releases. buildSrc has the problem that it is just like a single sub-project, but the plugin itself is complex enough to consist of multiple sub-projects.
Comment: You can have sub-projects in `buildSrc` (though the root has to depend on them). You can also extract the build logic to a stand-alone project and bring it in as an composite (included) build, which is what `buildSrc` is under the hood. I usually do that to dog-food my own plugins. The point is that if you want to publish it to a repository, you should use a version number so you can always roll back in case of failure. If you can't roll back to the latest stable, you can use timestamps on the snapshots. But I still find the first `buildSrc`/composite build more maintainable.
Comment: I suspected that a composite build is what fits my situation best. Your hint that buildSrc does the same in a more ad-hoc way helped me better search for resources on this, so this combination of answer+comment solves my problem.


How can I access Glassfish v2 Admin Console from Apache httpd?

Question: We have a Glassfish running behind an Apache Webserver. Direct requests to the application server are blocked by the firewall. So we have the webserver forwarding requests to the app server via mod_jk. This all works fine for the web apps deployed on x80 ports of Glassfish. But am now left wondering, how do I access the Admin Console GUI? I can do most of the Admin Console things using asadmin, but it'd be good to have the GUI as well.
Thanks!
Nirav
Answer: Why not create a new VirtualHost or an Alias which will map to the Glassfish admin console?


how to retrieve row value using php mysql

Question: source code:
$display = 1004;
$result1 = mysql_query("SELECT id, username FROM users where parentid=$diplay");
$resrow = mysql_fetch_row($result1);
$g = $resrow[0];
$g1 = $resrow[1];
$g2 = $resrow[3]; -error not display
$g3 = $resrow[4];
$g4 = $resrow[5];

echo "ID: $g";
echo "ID: $g2";
echo "ID: $g3";
echo "ID: $g4";

i have to show 1005, 1007, 1008 but i can retrieve $g value only:
ans: 1004 daniel
how i can show other values 1007,1008
Table
id           ----name  -----    parentid
-----------------------------------
1004            daniel         1003
1005            peter          1004
1007            michael        1004
1008            sam            1004

ans:
        $g
        1004
     /        \
    g2         g3
   1005       1007

Comment: life saving ---[**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained and the [deprecation process](http://j.mp/Rj2iVR) has begun on it. See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ).
Comment: could you show the table structure
Comment: i think even i am sure that 0,1,4,4,5 are not the colon name ... you need to use the colon name in `$resrow['colon name here']`
Comment: where are these values coming from? `1005, 1007, 1008`?
Comment: id name parentid  1004 daniel 1003,   1005  peter  1004,  1007 michael 1004, 1008 sam  1004
Comment: but you have only projected two columns: `id, username`. you can't fetch for parentID in this case.
Comment: i want to fetch these values 1005, 1007, 1008.
Answer: From your mysql query, you can only get column id and username. You need to modify your sql to include more columns.
Comment: i need to show id number only, like 1005, 1007, 1008 based on parentid
Answer: You only select id and username in your query, which might have returned array like this
array(
    'id'=> 1005
    'username'=> 'name'
)

if 1005,1007,1008 are child of 1004. you might want to do
while($resrow = mysql_fetch_array( $result1 )){
    echo "ID:". $resrow['id'];
    echo "Name:". $resrow['username'];
}

Comment: @user1799052 noop he is right .. you need to use the loop if you want to get the multiple row as you wanted
Comment: Hi, i have to show individual value like $resrow[0], $resrow[1], $resrow[2], only first 3 values only i need to show. thanks,
Comment: then why do you want to echo ID? to show only the ID, just run the loop and echo only `$resrow['id']`.
Comment: just echo a separator to see if it is correct. `echo $resrow['id'].':';`. The result will be `1005,1007,1008,`.
Answer: You are confusing rows with columns.  On this database:
users
id    | name    |  parentid
------+---------+----------
1004  | daniel  |  1003
1005  | peter   |  1004
1007  | michael |  1004
1008  | sam     |  1004

The query  SELECT id, name FROM users where parentid=1004 will return rows 1005, 1007, and 1008.
mysql_fetch_row() only fetches one row at a time.
That's across (the id and name), not down (several ids).
To get a list of all of the ID values that match, you need to loop through all the rows:
$parentid = 1004;
$result = mysql_query( "SELECT `id` FROM `users` WHERE `parentid`=$parentid" );
while( $row = mysql_fetch_row( $result ) ){ $IDs[] = $row[0]; }
// $IDs is now an array holding each id from the resultset.
// It will look something like:
/*
array(3) {
 [0]=>
    int(1005)
 [1]=>
    int(1007)
 [2]=>
    int(1008)
}
*/

As mentioned above, don't use ext/mysql for new work.  I'm using it here only because that's how you asked your original question.  You need to update your code and use ext/mysqli or PDO instead.
Comment: Hi, echo "$IDs[0]";  echo "$IDs[1]"; this is correct way to print the value?. thanks


C++ RTTI Viable Examples

Question: I am familiar with C++ RTTI, and find the concept interesting.
Still there exist a lot of more ways to abuse it than to use it correctly (the RTTI-switch dread comes to mind). As a developer, I found (and used) only two viable uses for it (more exactly, one and a half).
Could you share some of the ways RTTI is a viable solution to a problem, with example code/pseudo-code included?
Note: The aim is to have a repository of viable examples a junior developer can consult, criticize and learn from.
Edit: You'll find below code using C++ RTTI
// A has a virtual destructor (i.e. is polymorphic)
// B has a virtual destructor (i.e. is polymorphic)
// B does (or does not ... pick your poison) inherits from A

void doSomething(A * a)
{
   // typeid()::name() returns the "name" of the object (not portable)
   std::cout << "a is [" << typeid(*a).name() << "]"<< std::endl ;

   // the dynamic_cast of a pointer to another will return NULL is
   // the conversion is not possible
   if(B * b = dynamic_cast(a))
   {
      std::cout << "a is b" << std::endl ;
   }
   else
   {
      std::cout << "a is NOT b" << std::endl ;
   }
}

Comment: You could start by posting your 1.5 examples.
Comment: The problem is that if I post them, and they are the easiest examples (as I guess they are), then most people won't even try sharing their own. Of course, I'll post them if no one thought about them.
Comment: :-D ... No, I'm not. Ok, the first is contract programming, where you ask an object if he implements some interface. If yes, you then use the inferface. The second is used when you have complex class hierarchy, and don't want your base Object class to implement the method draw from Shape...
Comment: 1 I can agree with. 2 sounds like a broken hierarchy.
Comment: The "2" is the .5 part... :-D ... It's not as much broken as it is extended. If you have a large framework of very different objects, the last thing you want is to have all objects have the same 3000 methods. So you set "divergence points". Object could derive into Container and Shape, and [...]
Comment: [...] So, Object::toString exists, Container::getSize() exist, too, as well as Shape::draw(). But not Object::draw(), nor Object::getSize(). But every time deriving from Shape would have draw, and every type deriving from Container would have getSize. In C++, because of templates [...]
Comment: [...] This case won't appear often, but it could... This example, while similar to Java, I read first in B. Stroustrup's C++ Programming Language. I implemented it on a primitive XML GUI code that was never finished (but was quite cool anyway... :-p ...)
Comment: Hey, the "contract" part appeared in the http://stackoverflow.com/questions/238452/c-rtti-viable-examples#238515 from keysersoze! I was right... :-p
Answer: Acyclic Visitor (pdf) is a great use of it.
Comment: I agree. This again what I called above the "contract" programming. +1
Comment: Link is not longer valid. Wayback Machine to the rescue: https://web.archive.org/web/20060313131550/http://www.objectmentor.com/resources/articles/acv.pdf
Answer: How about the boost::any object!
This basically uses the RTTI info to store any object and the retrieve that object use boost::any_cast<>.
Comment: While boost:any does not use dynamic cast, it uses the typeid operator which works even for non-polymorphic types, to be sure the cast is correct. +1
Answer: You can use RTTI with dynamic_cast to get a pointer to a derived class in order to use it to call a fast, type specialized algorithm.  And instead of using the virtual methods through the base class, it will make direct and inlined calls.
This sped things up for me a lot using GCC.  Visual Studio didn't seem to do as well, it may have a slower dynamic_cast lookup.
Example:
D* obj = dynamic_cast<D*>(base);
if (obj) {
    for(unsigned i=0; i<1000; ++i)
        f(obj->D::key(i));
    }
} else {
    for(unsigned i=0; i<1000; ++i)
        f(base->key(i));
    }
}

Comment: I would be interested by "why this goes faster on gcc". The work avoided in `obj->D::key` is being done by the dynamic_cast. And will this scale well for, say, multiple types D, E, F, etc., meaning multiple if(D)/else if(E)/else if(F)/else ?
Comment: @paercebal: It worked because the compiler was able to inline the direct call to D::key(i) and over 1000 iterations the savings of not doing indirect pointer calls adds up.
Comment: @Zan Lynx: Now, as MSalters did put it, what if the class is DD, which is derived from D, and overrides `key`? This means that this piece of code needs to know the exact class hierarchy to work. Still, it is an interesting piece of code. +1.
Comment: Probably D* d = dynamic_cast(base); for (i=0;i!=1000;++i) { d->Foo(); }.

Wrong idea, since this doesn't call MoreDerived::Foo
Comment: Use the d->D::Foo() syntax.  I put it in the example I added.
Comment: Interesting micro optimization, I'll have to remember this.
Comment: @Zan Lynx: Oops... I was so puzzled by the thing I didn't see the loop. Of course, you're right!
Answer: I cant say I've ever found a use for in in real life but RTTI is mentioned in Effective C++ as a possible solution to multi-methods in C++. This is because method dispatch is done on the dynamic type of the this parameter but the static type of the arguments.
class base
{
  void foo(base *b) = 0; // dynamic on the parameter type as well
};

class B : public base {...}
class B1 : public B {...}
class B2 : public B {...}

class A : public base
{
  void foo(base *b)
  {
    if (B1 *b1=dynamic_cast<B1*>(b))
      doFoo(b1);
    else if (B2 *b2=dynamic_cast<B2*>(b))
      doFoo(b2);
  }
};

Comment: As a side-note, there's also a mention of multimethod impl in Alexandrescu's "Modern C++ Design"
Answer: I worked on an aircraft simulation once, that had what they (somewhat confusingly) referred to as a "Simulation Database".  You could register variables like floats or ints or strings in it, and people could search for them by name, and pull out a reference to them.  You could also register a model (an object of a class descended from "SimModel").  The way I used RTTI, was to make it so you could search for models that implement a given interface:
SimModel* SimDatabase::FindModel<type*>(char* name="")
{
   foreach(SimModel* mo in ModelList)
   if(name == "" || mo->name eq name)
   {
       if(dynamic_cast<type*>mo != NULL)
       {
           return dynamic_cast<type*>mo;
       }
   }
   return NULL;
}

The SimModel base class:
class public SimModel
{
    public:
        void RunModel()=0;
};

An example interface might be "EngineModel":
class EngineModelInterface : public SimModel
{
    public:
        float RPM()=0;
        float FuelFlow()=0;
        void SetThrottle(float setting)=0;
};

Now, to make a Lycoming and Continental engine:
class LycomingIO540 : public EngineModelInterface
{
    public:
        float RPM()
        {
            return rpm;
        }
        float FuelFlow()
        {
            return throttleSetting * 10.0;
        }
        void SetThrottle(float setting)
        {
            throttleSetting = setting
        }
        void RunModel() // from SimModel base class
        {
            if(throttleSetting > 0.5)
                rpm += 1;
            else
                rpm -= 1;
        }
    private:
        float rpm, throttleSetting;
};
class Continental350: public EngineModelInterface
{
    public:
        float RPM()
        {
            return rand();
        }
        float FuelFlow()
        {
            return rand;
        }
        void SetThrottle(float setting)
        {
        }
        void RunModel() // from SimModel base class
        {
        }
};

Now, here's some code where somebody wants an engine:
.
.
EngineModelInterface * eng = simDB.FindModel<EngineModelInterface *>();
.
.
fuel = fuel - deltaTime * eng->FuelFlow();
.
.
.

Code is pretty pseudo, but I hope it gets the idea across.  One developer can write code that depends on having an Engine, but as long as it has something that implements the engine interface, it doesn't care what it is.  So the code that updates the amount of fuel in the tanks is completely decoupled from everything except the FindModel<>() function, and the pure virtual EngineModel interface that he's interested in using.  Somebody a year later can make a new engine model, register it with the SimulationDatabase, and the guy above who updates fuel will start using it automatically.  I actually made it so you could load new models as plugins (DLLs) at runtime, and once they are registered in the SimulationDatabase, they could be found with FindModel<>(), even though the code that was looking for them was compiled and built into a DLL months before the new DLL existed.  You could also add new Interfaces that derive from SimModel, with something that implements them in one DLL, something that searches for them in another DLL, and once you load both DLLs, one can do a FindModel<>() to get the model in the other.  Even though the Interface itself didn't even exist when the main app was built.
Parenthetically, RTTI doesn't always work across DLL boundaries.  Since I was using Qt anyway, I used qobject_cast instead of dynamic_cast.  Every class had to inherit from QObject (and get moc'd), but the qobject meta-data was always available.  If you don't care about DLLs, or you are using a toolchain where RTTI does work across DLL boundaries (type comparisons based on string comparisons instead of hashes or whatever), then all of the above with dynamic_cast will work just fine.
Comment: Effectively, I tried, too, the decoupling of interfaces and implementations, and code using defined interfaces worked quite well with implementation types coded time after, without needing recompilation... +1
Comment: After reading the first lines of Your post, I wondered why I could not remember posting some details about my aircraft simulation. :-D

This should proove, that there are some examples of useful RTTI.
Answer: I use it in a class tree which serializes to a XML file. On the de-serialization, the parser class returns a pointer to the base class which has a enumeration for the type of the subclass (because you don't know which type it is until you parse it). If the code using the object needs to reference subclass specific elements, it switches on the enum value and dynamic_cast's to the subclass (which was created by the parser). This way the code can check to ensure that the parser didn't have an error and a mismatch between the enum value and the class instance type returned. Virtual functions are also not sufficient because you might have subclass specific data you need to get to.
This is just one example of where RTTI could be useful; it's perhaps not the most elegant way to solve the problem, but using RTTI makes the application more robust when using this pattern.
Comment: You're right: This is an awful switch/RTTI combination, but then, you are using XML, and this is a *good* solution to strong-type again what was a string XML  into a full fledged object. +1.
Comment: +1 because this is the exact thing I'm looking to do, this was the best idea I could come up with too, and I appreciate the knowledge that I wasn't missing something.
Answer: Sometimes static_cast and C-style casts just aren't enough and you need dynamic_cast, an example of this is when you have the dreaded diamond shaped hierarchy (image from Wikipedia).

struct top {
};

struct left : top {
    int i;
    left() : i(42) {}
};

struct right : top {
    std::string name;
    right() : name("plonk") { }
};

struct bottom : left, right {
};

bottom b;
left* p = &b;

//right* r = static_cast<right*>(p); // Compilation error!
//right* r = (right*)p;              // Gives bad pointer silently
right* r = dynamic_cast<right*>(p);  // OK

Comment: you don't need the "diamond shaped hierarchy" to have that...
Answer: Use cases I have in my projects (if you know any better solution for specific cases, please comment):

The same thing as 1800 INFORMATION has already mentioned:
You'll need a dynamic_cast for the operator== or operator< implementation for derived classes. Or at least I don't know any other way.

If you want to implement something like boost::any or some other variant container.

In one game in a Client class which had a std::set<Player*> (possible instances are NetPlayer and LocalPlayer) (which could have at most one LocalPlayer), I needed a function LocalPlayer* Client::localPlayer(). This function is very rarely used so I wanted to avoid to clutter Client with an additional local member variable and all the additional code to handle this.

I have some Variable abstract class with several implementations. All registered Variables are in some std::set<Variable*> vars. And there are several builtin vars of the type BuiltinVar which are saved in a std::vector<BuiltinVar> builtins. In some cases, I have a Variable* and need to check if it is a BuiltinVar* and inside builtins. I could either do this via some memory-range check or via dynamic_cast (I can be sure in any case that all instances of BuiltinVar are in this vector).

I have a gridded collection of GameObjects and I need to check if there is a Player object (a specialized GameObject) inside one grid. I could have a function bool GameObject::isPlayer() which always returns false except for Player or I could use RTTI. There are many more examples like this where people often are implementing functions like Object::isOfTypeXY() and the base class gets very cluttered because of this.
This is also sometimes the case for other very special functions like Object::checkScore_doThisActionOnlyIfIAmAPlayer(). There is some common sense needed to decide when it actually make sense to have such a function in the base class and when not.

Sometimes I use it for assertions or runtime security checks.

Sometimes I need to store a pointer of some data in some data field of some C library (for example SDL or what not) and I get it somewhere else later on or as a callback. I do a dynamic_cast here just to be sure I get what I expect.

I have some TaskManager class which executes some queue of Tasks. For some Tasks, when I am adding them to the list, I want to delete other Tasks of the same type from the queue.
Answer: I used RTTI when doing some canvas-based work with Qt several years ago.  It was darn convenient when doing hit-tests on objects to employ RTTI to determine what I was going to do with the shape I'd 'hit'.  But I haven't used it otherwise in production code.
Answer: I'm using it with Dynamic Double Dispatch and Templates. Basically, it gives the ability to observe/listen to only the interesting parts of an object.

C++ RTTI Viable Examples


Rotate a model or a view with mouse input to produce intuitive results

Question: I am writing 3D graphics software in Java using the LibGDX framework (which is a front-end for OpenGL), and am baffled by a transformation problem.  How do I rotate the orientation of the camera or models being displayed by the dx and dy inputs from a mouse?
Click here to view the full source code of a concise demo in github.com
But, here is the method where I'm certain the problem and solution will be found:
@Override public boolean touchDragged( int screenX, int screenY, int pointer )
{
    lastX = screenX-lastX;
    lastY = screenY-lastY;

    // distance of mouse movement
    screenAng = (float) Math.sqrt( lastX*lastX + lastY*lastY );
    // direction vector of the AOR
    screenAOR.set( lastY/screenAng, lastX/screenAng, 0f );
    if ( touchedButton == 0 )
    {
        cubes[ selectedCube ].modelInstance.transform.rotate( screenAOR, screenAng );
    }
    else
    {
        camera.rotateAround( Vector3.Zero, screenAOR, -screenAng/5.5f );
        camera.update();
    }

    lastX = screenX;
    lastY = screenY;
    Gdx.graphics.requestRendering();
    return true;
}

EDIT: Thanks to Andrew Wilson for his comment below.  I edited the camera section and it works properly now.  Still working on the model section...
    {

        // transform the screen AOR to a world AOR

        // get the camera transformation matrix
        tempMat = new Matrix4( camera.view );
        tempMat.translate( camera.position );
        tempMat.inv();

        // transform the screen AOR to a world AOR
        worldAOR = transformThings( tempMat, screenAOR, new Vector3() ).nor();

        // apply the rotation of the angle about the world AOR to the camera
        camera.rotateAround( Vector3.Zero, worldAOR, screenAng/5.5f );
        camera.update();
    }

EDIT: I edited the model section and it still is giving me some grief - it looks like it's orbiting the world origin instead of rotating around the model origin.  Here's what it looks like so far:
    {

        // transform the screen AOR to a model AOR

        // get inverse of the camera transformation matrix
        tempMat.set( camera.view );
        tempMat.translate( camera.position );
        tempMat.inv();

        // get inverse of the model transformation matrix
        Vector3 tempPos = cubes[ selectedCube ].position;
        cubes[ selectedCube ].modelInstance.transform.translate( tempPos.cpy().scl( -1 ) );
        tempMat2.set( cubes[ selectedCube ].modelInstance.transform );
        tempMat2.inv();

        // multiply the camera and model matrices together
        tempMat.mul( tempMat2 );

        // transform the screen AOR to a model AOR
        modelAOR = transformThings( tempMat, screenAOR, modelAOR ).nor();

        // apply the rotation of the angle about the model AOR to the model
        cubes[ selectedCube ].modelInstance.transform.rotate( modelAOR, -screenAng );
        cubes[ selectedCube ].modelInstance.transform.translate( tempPos );
    }

Here is an image that the demonstrates the problem:

I want the object to rotate in the direction it is dragged by the mouse, no matter which direction it happens to be orientated at the time. As it is now, when I first drag the mouse to the right, the object rotates to the right about the screen Y axis as expected; but then when I drag the mouse upward I want the object to rotate upward about the screen X axis, but instead it spins to the left about the screen Z axis. Think of it like a floating ball in a bowl of water - whichever way you swipe at it, it ought to rotate in that direction.
It seems to me that the mouse movement is transforming the objects directly in their local coordinate system; but instead I think I need to transform the axis of rotation itself from the Screen Coordinate System into the Object Coordinate System before applying it to the object. I just can't figure out how to do it.
I would really appreciate any insight or help to resolve this; I'm running out of hair to pull out... Thanks in advance.
Comment: An intuitive rotation depends on the view direction. Multiply your change in transformation by the inverse view matrix. Then apply the change in transformation to the overall transformation of the object. Think of it like undoing whatever rotation you did with the view. If you have a translation in your camera you'll have to deal with that also.
Comment: Ok. Now I'm making progress.  I got the camera rotation working properly:  I created a temporary matrix from the camera, translated the position out of it, inverted it, then rotated the screenAOR about it, and Boom!  It worked! Yahoo.
Comment: I added the working code above as an EDIT.
Comment: I'm still having trouble getting the model to rotate properly.  I translate and invert the camera into a temporary matrix (as in the view rotation section), then I translate the invert the model instance (in a similar manner) into another temporary matrix, then I multiply them together and transform the screen AOR into a model AOR, then rotate the model instance, and lastly translate the model back to it's position.
Comment: The model seems to be rotating properly, except that it is as though it didn't get translated to the origin to be rotated, because as it rotates it is also orbiting the origin. Dang! @Andrew can you see anything I'm missing? I'll add the code in another EDIT above.
Answer: Here's a more complete answer from my comment. The end product we want is:
Projection * ViewTranslate * Model * ViewRotate

All are 4x4 matrices. Where model is your models transformations. To implement you can just separate out the view's translate and rotate during your draw.
If you're using an abstraction that requires you to use Proj * View * Model. Or you just really don't want to ruin your own abstraction that follows that pattern. You'll need to modify model to cancel out views rotational part and put it on the right side:
Model = ModelTranslate * View^-1 * ViewTranslate * ModelRotate * ViewRotate
      = ModelTranslate * ViewRotate^-1 * ModelRotate * ViewRotate

Here's some of my code that does the above. It does not matter if model or view is translated, objects will still rotate around their local origins:
glm::vec2 diff = (prevMousePos - mousePos) * rotSpeed;
glm::mat4 rotX = MathHelp::matrixRotateY(diff.x);
glm::mat4 rotY = MathHelp::matrixRotateX(diff.y);

// Decompose the translate and rotate part of view
glm::mat4 viewT, viewR;
Decompose(cam->view, viewT, viewR);

// Decompose the translate and rotate part of model
glm::mat4 modelT, modelR;
Decompose(exampleObj->model, modelT, modelR);

exampleObj->model = modelT * glm::inverse(viewR) * rotX * rotY * viewR * modelR;

This preserves the existing rotation and translation in exampleObj->model as the function gets called continually applying small rotations. And assumes you'll be using Proj * View * Model.
Lastly decompose just separates out the 3x3 rotation/scaling from the translational part:
void Decompose(glm::mat4 m, glm::mat4& t, glm::mat4& r)
{
    glm::mat4 I4 = glm::mat4(1.0f); // Identity
    for (unsigned int i = 0; i < 4; i++)
    {
        for (unsigned int j = 0; j < 4; j++)
        {
            if (i == 3 || j == 3)
            {
                r[i][j] = I4[i][j];
                t[i][j] = m[i][j];
            }
            else
            {
                r[i][j] = m[i][j];
                t[i][j] = I4[i][j];
            }
        }
    }
}

Comment: Wahoo!  That did it!  It took a little trial-and-error to get the Java translation correct, but it works perfectly.  Thanks a million!!!  I've added the working code as another answer below.  it won't let me up-vote your answer, but this is it.
Answer: Here is the change to the code that made the whole thing work correctly:
@Override public boolean touchDragged( int screenX, int screenY, int pointer )
{
    lastX -= screenX;
    lastY -= screenY;

    // distance of mouse movement
    screenAng = Vector3.len( lastX, lastY, 0f );
    // direction vector of the AOR
    screenAOR.set( lastY/screenAng, lastX/screenAng, 0f );

    if ( touchedButton == 0 )
    {   // rotate the part

        // transform the screen AOR to a model rotation

        Matrix4 camT, camR, camRi, modT, modR;
        camT = new Matrix4();
        camR = new Matrix4();
        modT = new Matrix4();
        modR = new Matrix4();

        decompose( camera.view, camT, camR );
        camRi = camR.cpy().inv();

        decompose( cubes[ selectedCube ].modelInstance.transform, modT, modR );

        tempMat.idt()
                .mul( modT )
                .mul( camRi )
                .rotate( screenAOR, -screenAng )
                .mul( camR )
                .mul( modR );

        cubes[ selectedCube ].modelInstance.transform.set( tempMat );
    }
    else if ( touchedButton == 1 )
    {   // rotate the camera

        // transform the AOR from screen CS to camera CS

        // get the camera transformation matrix
        tempMat.set( camera.view );
        tempMat.translate( camera.position );
        tempMat.inv();

        // transform the screen AOR to a world AOR
        worldAOR = transform( tempMat, screenAOR, worldAOR ).nor();

        // apply the rotation of the angle about the world AOR to the camera
        camera.rotateAround( Vector3.Zero, worldAOR, screenAng/5.5f );
        camera.update();
    }

    lastX = screenX;
    lastY = screenY;
    Gdx.graphics.requestRendering();
    return true;
}

// --------------------------------------------------------------------- //
Vector3 transform( Matrix4 mat, Vector3 from, Vector3 to )
{
    // transform a vector according to a transformation matrix

    to.x = from.dot( mat.val[ Matrix4.M00 ], mat.val[ Matrix4.M01 ],
            mat.val[ Matrix4.M02 ] )+mat.val[ Matrix4.M03 ];
    to.y = from.dot( mat.val[ Matrix4.M10 ], mat.val[ Matrix4.M11 ],
            mat.val[ Matrix4.M12 ] )+mat.val[ Matrix4.M13 ];
    to.z = from.dot( mat.val[ Matrix4.M20 ], mat.val[ Matrix4.M21 ],
            mat.val[ Matrix4.M22 ] )+mat.val[ Matrix4.M23 ];
    return to;
}

// --------------------------------------------------------------------- //
void decompose( Matrix4 m, Matrix4 t, Matrix4 r )
{
    Matrix4 I4 = new Matrix4(); // Identity
    for ( int i = 0; i < 4; i++ )
    {
        for ( int j = 0; j < 4; j++ )
        {
            if (i == 3 || j == 3)
            {
                r.val[ i*4+j ] = I4.val[ i*4+j ];
                t.val[ i*4+j ] = m.val[ i*4+j ];
            }
            else
            {
                r.val[ i*4+j ] = m.val[ i*4+j ];
                t.val[ i*4+j ] = I4.val[ i*4+j ];
            }
        }
    }
}


yield(:title) in Ruby on Rails is never equal to false for some reason

Question: #layouts/application.html.haml
    %title
     = yield(:title) || "Default page title"
     = " | DefaultSite.com"

#application_helper.rb
 def title(page_title)
    content_for(:title) { page_title }
  end

Even if I don't set a title (helper method) for a page, "Default page title" never shows. Instead of it, "" (the value of yield(:title)) appears for some reason.
Why is this happening?
Answer: This is just part of the design of Rails. You can't change this behaviour.
You should instead check if yield(:title).empty? is true or false in order to see if the content_for(:title) was called.
For example, instead of:
yield(:title) || "Default page title"

you want:
(yield(:title).empty? ? "Default page title" : yield(:title))

This just checks whether it is empty, and applies the default if it is empty, or else uses the title.
Comment: is this case I would use `present?` instead of `empty?`
Comment: You could also shorten this to `yield(:title).presence || "Default page title"`
Comment: I think you can use either. Just depends on which way round the arguments between the colons are placed.


python: input variable of function append changes while changing host-variable

Question: I'm facing (for me at least) some kind of strange behavior while using the function append in python. In the following example the variable growing is appended with value of the variable static. Then a value in growing is changed which influences also the variable static. Why is this happening? I thought static should not change until I assign a new value e.g. with 'static = ...'.
Tested with Python 3.7.4 (default, Jul 16 2019, 07:12:58) [GCC 9.1.0] on linux
Code:
static = {"a": 100, "b": 200}
growing = []
print("static", static)
print("growing", growing)
growing.append(static)
growing[0]["a"] = 999
print('after append and change in growing:')
print("static", static)
print("growing", growing)

This is the output I get:
static {'a': 100, 'b': 200}
growing []
after append and change in growing:
static {'a': 999, 'b': 200}
growing [{'a': 999, 'b': 200}]

Comment: `growing[0]` and `static` point to the same underlying object
Comment: Because `growing[0] is static`; you appended a *reference* to that dictionary to the list. You might find https://nedbatchelder.com/text/names.html useful reading.
Answer: static = {"a": 100, "b": 200}

Above statement creates a dict object in memory and the variable "static" points to that.
growing.append(static)

When you append static to growing , the first element of the list points to same dict object in memory. No new object is created , just 2 variables static and growing[0] are pointing to same object in memory. Thus when this dict is changed by
growing[0]["a"] = 999

you see the change in both the variables
Comment: Thanks for all the answers and comments. As an old Matlab user, this was totally new to me. Thanks :)


minimal polynomial of $1+\alpha^2$ where $\alpha$ is a root of $x^3-x-1$

Question: Suppose $\alpha$ is a root of $x^3-x-1$, and $\gamma=1+\alpha^2$.
What is the minimal polynomial of $\gamma$ over $\mathbb Q$?
Comment: What have you done so far? If you show your working then people are more willing and able to help on the parts you are stuck on
Comment: Hint: first find the minimum polynomial of $\alpha^2$ by writing $\alpha^3 - \alpha = 1$ and squaring both sides.
Answer: Write the matrix of the map $x \mapsto \gamma x$ in the basis $1,\alpha,\alpha^2$.
The minimal polynomial of this matrix is the minimal polynomial of $\gamma$.
Answer: A bit of linear algebra makes this very straightforward. To expand on the answer by lhf, the minimal polynomial over$\def\Q{\Bbb Q}~\Q$ of an element $\beta$ is also the minimal polynomial of the $\Q$-linear map of mulitpliciation by$~\beta$. The (sub)field $\Q[\alpha]$ is isomorphic to $\Q[X]/(X^3-X-1)$, and in that $\Q$-vector space the matrix, on the basis $[1,\alpha,\alpha^2]$ of images of $1,X,X^2$ is the companion matrix of $X^3-X-1$, which is
$$ M=\pmatrix{0&0&1\\1&0&1\\0&1&0}.
$$
The minimal polynomial of $\gamma=\alpha^2+1$ is of degree$~3$ (the only other possibility of an element of $\Q[\alpha]$ is degree$~1$, but that clearly is not the case here since $X^2+1$ is not divisible by $X^3-X-1$), so it will also be the characteristic polynomial of multiplication by$~\gamma$, which has matrix $$ M^2+I=\pmatrix{1&1&0\\0&2&1\\1&0&2}.$$
The characteristic polynomial of that matrix is easily computed to be $X^3-5X^2+8X-5$.
Answer: Hints:
Observe that $\;\alpha^3=\alpha+1\;$ , and from here
$$\gamma^2=1+2\alpha^2+\alpha^2+\alpha=\gamma+3(\gamma-1)\;\ldots$$
Answer: Hint:
Find the minimal polynomial $p(x)$ of $\alpha^2$, using Vieta's relations between the roots of $x^3-x-1$.
The minimal polynomial of $1+\alpha^2$ will be $q(x)=p(x-1)$.
Some details:
Explicitely, denotin $\beta$ and $\gamma$ the other roots of $x^3-x-1$, you  have to calculate $$S=\alpha^2+\beta^2+\gamma^2,\quad S_2=\alpha^2\beta^2+\beta^2\gamma^2+\gamma^2\alpha^2,\quad P=\alpha^2\beta^2\gamma^2,$$ knowing
$$s=\alpha+\beta+\gamma,\quad s_2=\alpha\beta+\beta\gamma+\gamma\alpha,\quad p=\alpha\beta\gamma.$$
This is possible by Newton's theorem, since $S, S_2$ and $P$ are symmetric functions in $\alpha,\beta,\gamma$.
Example:
$$S=(\alpha+\beta+\gamma)^2-2(\alpha\beta+\beta\gamma+\gamma\alpha)=s^2-2s_2$$
Comment: I try it this way. But it is still hard. Can you give me more hints?
Comment: @Lehostal: I've added some details.