Ubuntu 13.10 64 bit live USB created with UNetbootin either not recognised or "Disk Error" on Dell D630 BIOS A17

Question: I know, I know, this question has been asked so many times but I have searched and searched and tried and tried but I can't get it to work.
I'm running Windows XP on my Dell D630. I downloaded the 64 bit Ubuntu 13.10 iso from the download page and "burnt" it to a FAT32 formatted 2GB USB drive with UNetbootin. I set up my BIOS so that USB devices are first in the boot sequence and even pressed F12 at the splash screen to make absolutely sure it was trying to boot from the USB drive. I removed all other USB devices, even my wireless USB mouse, but I get the dreaded "Disk Error" message. I have followed all the answers to similar questions on setting up the BIOS correctly, so enabling USB devices in the POST menu, enabling USB emulation etc. I have read about the difference between USB-HDD and USB-ZIP but I can't find any option relating to this in the BIOS so if this is the issue then I'd like to know how else to fix it.
No worries, I tried again with another USB flash drive I had spare, this time 1GB, I did everything specified above except this time there is no disk error but instead the flash drive appears to be unrecognised. This is only my assumption: when I select USB device from the boot menu, the screen goes black with a blinking cursor ("_") for barely a second then the laptop boots as normal. I even tried removing the HDD but then I am informed that there are no bookable devices.
I can boot from a 32 bit Ubuntu 12.10 DVD if it's any help. The laptop is a Dell D630 with an Intel T7100 processor, DT781 P/N motherboard (Intel graphics version), 1GB memory in each slot (so 2GB overall) and BIOS version A17.
Help would be much appreciated
Answer: Try to make your usb bootable using Universal USB Installer
and try again.
Comment: Thank you very much, worked beautifully and quickly, the install worked fine. Sorry for not trying Universal USB Installer before, but all the queries I read suggested UNetbootin was the best one to use.


Logic Error in a matrix roll dice program in Python

Question: I have the following code for a simple game that lets player1 and player2 take turns to roll two six sided dice(die). On reaching 49 (the last number in the matrix) a player will win. Players start at 1 and then move up the number that is rolled (total of both die).
I have three errors (logic errors) in my code that I need some help with.
1)The winner functionality doesn't work. If a player reaches 49 or is close (see output at the end) it doesn't logically allow them to win. (just keep pressing enter to run a test and see the peculiar output pasted below). Player 1 AND Player 2 can reach 49 but it doesn't take them to the "winner()" module. Why? I have used ">=" correctly or have I not?
Having said that, in one test: Player 2 reached 49, and it didn't go to the winner() module:
    Press Enter to continue
Player 2, it's your turn to roll the dice: Press r to roll:>>>
Player2: You rolled a: 4 and a 6 which gives you a: 10
You have moved 10 spaces to position:....... 49

2)On exiting the program completely and starting again, the values of player1position and player2position are reset to 0 and it works. But if I just go to main() to replay the game, these values are not reset. I don't fully understand the usage and declaration of global variables and initialisation. Can anyone shed some light and an explanation/suggestion would help
3)Negative numbers aren't dealt with accurately. If on any turn a player throw TWO of the SAME number, they are meant to go back for the number rolled. e.g. if 2 and 2 rolled, the player goes back 4. However, if the player goes back when they are 5, 10 spaces, to -5, the next turn doesn't add up the total for player1position or player2position and the counting is messed up. I've tried various fixes and I'd be interested in any comments, suggestions and improvements.
The erroneous output is below:
First, this is the matrix:
*************LOADING GAME******************
Welcome: player1 and player2
[43, 44, 45, 46, 47, 48, 49]
[42, 41, 40, 39, 38, 37, 36]
[29, 30, 31, 32, 33, 34, 35]
[28, 27, 26, 25, 24, 23, 22]
[15, 16, 17, 18, 19, 20, 21]
[14, 13, 12, 11, 10, 9, 8]
[1, 2, 3, 4, 5, 6, 7]

The code that is relevant is as follows:
import sys
import csv
import random
def main():
    startscreen()

def loadstartgame(player1,player2):
    with open("messages.txt","r") as f:
        idnumber="1"
        fReader=csv.reader(f)
        for row in fReader:
            for field in row:
                if field==idnumber:
                                       print(row[2])

        start=input("Start?:>>")

        if start=="s" or "S":

            callmatrix(player1,player2,7)

def startscreen():
    print("******************************Welcome to CONQUER THE MATRIX****************************")
    print("You can take on a friend in this game")
    player1=input("Enter name of Player 1: ")
    player2=input("Enter name of Player 2: ")
    print("Welcome ...", player1,"and, ", player2, "...Are you ready?")
    response=input("Yes or No? Player 1 - perhaps you could confirm please: ")
    if response=="yes" or "Yes" or "yEs" or "YeS":
        loadstartgame(player1, player2)
    else:
        sys.exit()

def matrix(n):
    grid = [[1 + i + n * j for i in range(n)] for j in range(n)]
    for row in grid[1::2]:
        row.reverse()
    return grid[::-1][:]

def callmatrix(player1,player2, n):
    print("*************LOADING GAME******************")
    print("Welcome:", player1,"and", player2)
    for i in matrix(n):
            print(i)
    playing = True
    playerturns(player1,player2,playing)

def playerturns(player1,player2,playing):

    print(" - - - - - - - - - - ")
    print("Press Enter to continue")

    while(playing):
        roll=input()
        if roll=="":
            RollTwoDiceP1(player1,player2)

        else:
            break
    RollTwoDiceP2(player1,player2)

global player1position #declare a local variable called player1position
player1position=0 #set the global variable before the start of this sub to 0
def RollTwoDiceP1(player1,player2):
    global player1position

    print("player1position in PLAYER1ROLL", player1position)
    #print("player1position at stat of RollTwoDicep1", player1position) #a test that prints the current value of player 1 position
    turn=input("Player 1, it's your turn to roll the dice: Press r to roll:>>>")
    die1=random.randint(1,6)
    die2=random.randint(1,6)
    #die1=5 #for testing purposes
    #die2=5 #for testing purposes
    roll=die1+die2
    print("Player1: You rolled a:", die1, "and a", die2, "which gives you a:", roll)
    playing = False

    matrixlist=matrix(7)

    if die1==die2:
        gobackspacesP1(roll,player1,player2)
    else:
        print("You have moved", roll, "spaces to position:.......",matrixlist[6][0]+(roll+player1position))
    #print("playerposition plus roll:", player1position+roll) #a test that prints the playerposition+roll - this always comes up to 1 more than it should do on the location, so below substract 1, to make it produce an accurate location on the matrix for a particular roll
    player1position=matrixlist[6][0]+(roll+player1position)
    if player1position>=49:
                winner()
    else:
                playerturns(player1,player2,playing)

#global player1position
#global player2position
def gobackspacesP1(roll,player1,player2):
    global player1position
    if player1position<=1:
        player1position=0
        print("Oh dear - sorry you are now back to square 1 - literally!")
    else:
        print("Oh dear -you are now back on the matrix to position:", (1+player1position)-roll)
        matrixlist=matrix(7)
        #new player1position=the first playerposition minus the roll (rather than add it) and + 1 (as the initial position is always 1)
        player1position=1+(player1position-roll)
        #player1position=matrixlist[6][0]+(roll+player1position)-roll
    playing=False
    print("player1position in goback", player1position)
    playerturns(player1,player2,playing)

def gobackspacesP2(roll,player1,player2):
    global player2position
    if player2position<=1:
        player2position=0
        print("Oh dear - sorry you are now back to square 1 - literally!")
    else:
        print("Oh dear -you are now back on the matrix to position:", (1+player2position)-roll)
        matrixlist=matrix(7)
        #new player1position=the first playerposition minus the roll (rather than add it) and + 1 (as the initial position is always 1)
        player2position=1+(player2position-roll)
        #player1position=matrixlist[6][0]+(roll+player1position)-roll
    playing=True
    print("player2position in goback", player2position)
    playerturns(player1,player2,playing)

global player2position
player2position=0
def RollTwoDiceP2(player1,player2):
    global player2position
#Remember you need to add the functioanlity for a double identical dice roll to this subroutine for Player2 as well.
    turn=input("Player 2, it's your turn to roll the dice: Press r to roll:>>>")
    die1=random.randint(1,6)
    die2=random.randint(1,6)
    roll=die1+die2
    print("Player2: You rolled a:", die1, "and a", die2, "which gives you a:", roll)
    playing = True
    matrixlist=matrix(7)

    if die1==die2:
        gobackspacesP2(roll,player1,player2)
    else:
        print("You have moved", roll, "spaces to position:.......",matrixlist[6][0]+(roll+player2position))
    #print("playerposition plus roll:", player1position+roll) #a test that prints the playerposition+roll - this always comes up to 1 more than it should do on the location, so below substract 1, to make it produce an accurate location on the matrix for a particular roll
    player2position=matrixlist[6][0]+(roll+player2position)
    if player2position>=49:
                winner()
    else:
                playerturns(player1,player2,playing)

def winner():
    print("Ahh, it appears you have won! Congratulations!")
    sys.exit()

def easygrid():
    grid=[[43,44,45,46,47,48,49],[42,41,40,39,38,37,36],[29,30,31,32,33,34,35],[28, 27, 26, 25,24,23,22], [15,16,17, 18, 19, 20, 21], [14, 13, 12, 11, 10, 9, 8], [1, 2, 3,4,5,6,7]]
    for i in grid:
        print(i)
main()

I'd also be interested in any comments about my use of global variables and how best to use/not use them in this context.
I do not want a class based solution, so the answer would have to be a fix to this.
ERRONEOUS OUTPUT 1 (only player 2 wins, even though Player 1 should have won)
LAST FEW ROLLS leading up to the win:
player1position in PLAYER1ROLL 38
Player 1, it's your turn to roll the dice: Press r to roll:>>>
Player1: You rolled a: 3 and a 5 which gives you a: 8
You have moved 8 spaces to position:....... 47
- - - - - - - - - -
Press Enter to continue
Player 2, it's your turn to roll the dice: Press r to roll:>>>
Player2: You rolled a: 6 and a 5 which gives you a: 11
You have moved 11 spaces to position:....... 43
- - - - - - - - - -
Press Enter to continue

player1position in PLAYER1ROLL 46
Player 1, it's your turn to roll the dice: Press r to roll:>>>
Player1: You rolled a: 3 and a 5 which gives you a: 8
You have moved 8 spaces to position:....... 55
- - - - - - - - - -
Press Enter to continue
Player 2, it's your turn to roll the dice: Press r to roll:>>>
Player2: You rolled a: 6 and a 1 which gives you a: 7
You have moved 7 spaces to position:....... 50
You've won! Congratulations!

Comment: @PythonFish This question as asked is too broad, and you haven't given us enough information to troubleshoot all the issues (value resets). Do you ever use the `player1, player2` that you pass to every function?
Comment: If I had to guess as to the issue, you don't declare variables global upon first declaration, only after that, so where you first declare your `player1position`..., it shouldn't have a `global` tag.

@PythonFish You can highlight all the code and hit the `{}` button
Comment: I'm not using a matrix to store the player's position? They are both stored player1position and player2position as global variables .....what do you mean use a matrix??
Comment: I'd strongly advise to use a class containing your methods and have the player positions as attributes rather than global variables.
Comment: I've mentioned in the post that i do NOT wish to use classes....but yes, noted.
Comment: @PythonFish add debugging output for `playerXposition` I would suspect it is not the same number you think it is.
Comment: Can you post the complete code. Or atleat add the `matrix` function.
Comment: player1 and player2 are just the usernames that are input at the start at the game and passed to every function (perhaps unnecessarily) @TemporalWolf
Comment: @Gurupad Mamadapur - is there a way to paste the whole code without manually indenting each line to 4 spaces. It'll take ages
Comment: posted the whole code ......can anyone end my torment!
Comment: @PythonFish I mentioned an issue regarding global variables. Also, for your consideration, [repl.it](https://repl.it/F66v/0) with a comparable OO design. There are also lots of little logic errors `if response=="yes" or "Yes" or "yEs" or "YeS":` does not do what you think it does. This will always be True because `"Yes" or "yEs" or "YeS"` evaluates to True, and that `or`'d with anything is still True
Comment: @TemporalWolf - that bits okay - it makes it simpler to test (the Yes and yes etc...as they're not integral or important to the logic of the code. It's the other bits...
Comment: @TemporalWolf - as a newbie to Python and Programming, could you please explain what "add debugging output" means and how to do this in IDLE? Or can I do it in the repl.it website?
Comment: @PythonFish `print("Player 1's position is currently: ", player1position)` type messages to see what the value is at various points
Comment: Ah - just that. I thought you meant there was some sophisticated tool for debugging output that I had missed. Yes, therein lies the problem - I was hoping someone could spot it quicker than I. Solved it now.
Answer: The bug was in this line: (in the RollTwoDice1 and RollTwoDice2 subs)
player1position=matrixlist[6][0]+(roll+player1position)

the matrixlist[6][0] was added an erroneous +1, which when removed sorted the logic error.
Also: (in the gobacktospaces subs)
 player2position=1+(player2position-roll)

It had an extra -1 in it, which kept skewing the results for both the winner functionality and the adding up.


Ping for 60 seconds

Question: I want to ping an IP Address for 60 seconds. Like in Windows, you specify the time with '-t' flag.
ping 192.168.1.1 -t60

Is it possible in Linux?
Comment: Thanks for the prompt reply. I am sending 1000 packets/seconds '-i 0.001'. So -c doesn't work for me.
Comment: How about ping -w timeout?
Comment: You can ping faster than 0.200 if you are superuser
Answer: From man ping
   -w deadline
          Specify  a  timeout, in seconds, before ping exits regardless of
          how many packets have been sent or received. In this  case  ping
          does  not  stop after count packet are sent, it waits either for
          deadline expire or until count probes are answered or  for  some
          error notification from network.

ex.
$ time ping -w60 192.168.1.65 &>/dev/null

real    1m0.001s
user    0m0.008s
sys     0m0.000s

Answer: The timeout command can be used also here. which is from Coreutils package in Linux.
The command would be:
timeout 60 ping google.com

that's it.
Note: here you can run any command with a time limit for execution.

Ping for 60 seconds


Combinatorics : Claude wants to invite 5 people to dinner in a pool of 11 friends, but two of these can't be with each other. How many ways?

Question: So the question has three parts and I'm stuck on the third, that's how it goes :
Claude wants to invite 5 friends to dinner in a pool of 11 friends.
a) How many ways can he do this?
My answer : $\binom{11}{5} = 462$
It's correct
b) 2 of these friends can't be separated from each other, how many ways?
My answer : $\binom{10}{4} = 210$
It's correct
c) 2 of them are mad at each other and can't be invited together, how many ways?
My answer : ''a) - b)'' = $\binom{11}{5} - \binom{10}{4} = 252$
It's false
The answer: 378

I can't seem to understand, plus there is no explanation in my textbook, it's straight the answer, so I'm completely lost. I've tried lots of different things but never got it right.
Thank you for helping me understand. Combinatorics are like hell to me.
Comment: In the future, you can use [MathJax](https://goo.gl/OWv9nr) to format your posts.
Answer: If you invite both, you can only choose $3$ more, from $9$,
so a slight modification of your effort yields $\binom{11}5 - \binom93 = 378$
Answer: Person's $A$ and $B$ cannot both be invited. There are $3$ possibilities.
Person $A$ comes and there $9C4$ ways to choose the other people. ($126$)
Person $B$ comes and there $9C4$ ways to choose the other people. ($126$)
Neither $A$ or  $B$ comes and there $9C5$ ways to choose the other people. ($126$)
So there are $126+126+126=\color{blue}{378}$ ways to choose the people.
Comment: Omg you're a genius. Thank you I'm enlightened !
Answer: Your question can be formulated using boolean algebra.
A:A is invited

B:B is invited

Your case can be formulated as
(A && ~B) || (~A && B) || (~A && ~B)
which is equivalent to
~(A && B)

So if you find number of ways in which both A and B are invited and subtract it from the total number of ways of inviting friends, you will have your answer
Total ways of inviting both A and B is $\binom{9}{3}$.
Total  ways of inviting all $\binom{11}{5}$.
Hence your answer is $\binom{11}{5}$ - $\binom{9}{3}$.


Embedding a finite group into $\operatorname{GL}_n( \mathbb{Z})$

Question: Let $G$ be a finite group. Having a concrete realisation of this finite group as a group of matrices is often helpful for calculations, which motivates the following questions.

Question 1: Is there a good way to obtain the minimal $n$ such that $G$ embedds into $\operatorname{GL}_n(\mathbb{Z})$ (meaning there is an injective homomorphism of G into $\operatorname{GL}_n(\mathbb{Z})$)? Is it possible to obtain such a minimal embedding via GAP?

Question 2: Is there a good way to obtain the minimal $n$ such that $G$ embedds into $\operatorname{GL}_n(\mathbb{Z})$ such that all matrices in the image have only entries 0 or 1 (or entries 0, 1 and -1)? Is it possible to obtain such a minimal embedding via GAP?

Question 3: Is there a canonical such minimal embedding if we impose some further restrictions or nice properties of such maps?
Comment: It is already difficult computationally to find the smallest $n$ for which $G$ embeds into $S_n$, and I would guess that the problem is even more difficult  for ${\rm GL}_n({\mathbb Z})$.  If I was trying to solve that problem for some finite group $G$, then I would start by finding the irreducible rational representations of $G$ (which can all be written over ${\mathbb Z}$). They would typically not all be faithful but they might provide enough information to answer the question.
Comment: Please try to include some form of context in your question, e.g. *why* do you want to do this? And why do you want Gap to do this for you?
Comment: @DerekHolt Thank you for the comment. Can GAP find all irreducible representations over the rationals?
Answer: I have no interest or experience with GAP, but here are some partial answers:

Every finite subgroup of $GL_n(\mathbb{Q})$ can be conjugated into $GL_n(\mathbb{Z})$.  So it is enough to find the minimal dimensional rational representation.

Lemma: An 0-1 matrix with a 0-1 inverse is a permutation matrix.  So this is asking for finding a minimal faithful action of $G$ on a finite set.

Ignoring the faithfulness issue, finding a minimal non-trivial $G$-set is the same as finding a maximal order subgroup of $G$.


Cover up these water heater pipes?

Question: I live in Austin where it's about to get much colder than normal (single digits). Unfortunately the house in question (we're not currently living there) has no power at the moment. We just had the electrical panel replaced and the city won't turn the power back on until they inspect it probably a few weeks/months from now. We are in the process of covering up all the exposed pipes around the house to prevent them from freezing. Fortunately, the water heaters run on gas so we can still have hot water in the house.
Anyhoo, we have a water heater in an outside closet next to the pool. It was recently replaced and the plumbers insulated some of the pipes in there but not all of them (see pics below).
Do any of the exposed pipes need to be insulated? I have some foam tubing I can put around them if necessary. I did notice the the exhaust vent does get fairly warm when the water heater is on. Maybe that's enough to keep everything from freezing up?
I wasn't sure if covering up the hot water lines would be bad for them.
Answer: Defiantly cover all pipes. Several dollars worth of foam may prevent a big ,expensive problem , why even think about it ? I recently had a gas water heater replaced in the attic  and just recovered some pipe that was involved in the work. Although it was short lengths close to the heater ,I did not want to wonder if they were close enough.
Comment: I just wasn't sure which pipes are the hot waters ones or if covering those would be bad.
Comment: Cover all ; the hot are only hot when water hot water is flowing., otherwise they can freeze.
Answer: As long as the water heater is burning fuel in the closet water in the pipes wont freeze. The heat going into the closet from the exhaust gas heating the flue will be sufficient to prevent any freezing.
It might be a good idea to wrap all the cold water pipes with a pipe wrap. Turning the thermostat a notch higher would keep it warmer.
Comment: Which pipes are the cold ones though? Any of the uncovered ones on the pics I posted?
Comment: Most likely they are the uncovered  pipes in the back ground. Touching them should feel cool.

Cover up these water heater pipes?


Questions about arrays in ruby

Question: I have a class called Product, which contains a name, price and count.
In another class called Shop (including the class Product),  I initialize with an empty array. Then a add product to this array using the method push.
The problem happens to the method to_s of in the Shop class :
def to_s
  string = "Products in the shop:\n"
  @list.each do |list|
    #### how can i get access to the attributes of product like @list.name or something like that ?  I have tried loads of different methods but i cant get access to my attributes. (the array doesnt recognize the product class)
    puts @list.name
  end

If I create a Product without using Array, I can access to the attributes - I guess the problem comes because of the Array...
Comment: First show us the class you have created,then ask us the question pointing to the confusions you are having..
Comment: Is the `end` in your code the end of the `each` block or the end of the `def to_s` block?
Comment: Whoever edited it, you may have changed the OP's question. Note my comment above about mismatched `end`s. =)
Answer: So first of all, your blocks don't match up.
You want:
def to_s
  string = "Products in the shop:\n"
  @list.each do |item|
    string << item.name + "\n"     # not @list.name! @list is an Array. item is an element of your list.
  end
  string # you could also say: return string
end

You don't want to use puts because that'll send it to the console -- when you're trying to store it in a String called string. You want to make sure you return that, too.
You don't have to call your block parameter item. You could call it list, but that would be confusing, because you have another variable called @list, and the block parameter is not a list at all -- just an item from the array.
Note that this is not the most efficient way to accomplish this. The preferred way is like so:
def to_s
  products_list = @list.map do |item|
    item.name
  end
  "Products in the shop:\n" + products_list.join("\n")
end

Comment: You could also write John's suggested alternative as: `def to_s() "Products in the shop:\n" + @list.map(&:name).join("\n") end`
Comment: Doesn't that need a colon after the `def to_s()`? Also, the parens are optional. =)
Comment: If you remove the parens you'll need to insert one `;` after `to_s` and another before `end`.  Both work.
Answer: Each element in @list is yielded to the each block as list.
Assuming @list is an Enumerable with Product objects, you should be able to do list.name to get at the name attribute inside the block.
Answer: I'd prefer map and join over each and << (just a preference), and braces ({}) over do end because I like to imply a return value is important by using braces, and a do end block is there for side effects, e.g.
def to_s
  "Products in the shop:\n" << @list.map{|item| item.name}.join("\n")
end

I also wouldn't use puts because to_s should return a string, not output a string.

Questions about arrays in ruby


Electrical question concerning GFCI

Question: The electrical circuit for my bathroom has an electrical outlet in the bathroom, the lights and exhaust fan in the bathroom, an outlet in the hallway immediately outside the bathroom, and the light in the hallway.  The outlet in the bathroom is a GFCI outlet.  When I test the GFCI, the GFCI outlet goes dead as it should.  Everything else, the lights, fan, and socket in the hallway stay live.   To me it makes sense that the socket in the hallway stays live because it is not exposed to moisture like the GFCI socket in the bathroom, but I'm not an electrician, so what do I know?
I have two questions:
Question 1: Is it ok that the hallway socket (in a dry area) stays live when the GFCI is triggered?
Assuming that is ok, here's what I would like to do.  I would like to run a new 12-2 wire from the hallway socket up through the wall and install a new socket about a foot below the ceiling so I can plug in a CO detector.
Question 2: Would it be acceptable to run a new wire from the hallway socket to a new socket for a CO detector?   The GFCI in the bathroom should have no effect on the CO detector in the hallway.
Comment: Yes, it's fine that the outlet outside the bathroom stays on.  Only the bathroom receptacle requires GFCI protection.  The bathroom circuit is only supposed to serve the bathroom. So technically, using it to power outlets outside the bathroom is wrong.
Comment: Why the height on the CO detector? Just trying to keep it out of reach/traffic? Or are you operating on the assumption that it has to be high up? (Typically, they can go anywhere, except where manufacturer's instructions specify otherwise.)
Comment: Aloysius Defenestrate: "why the height on the CO detector? Just trying to keep it out of reach/traffic? Or are you operating on the (incorrect) assumption that it has to be high up?"  Both actually.  If the CO detector is higher up it is likely to be out of the way for human traffic, vacuum cleaners, etc and less likely to be damaged or knocked out of the socket.  Also, everything I've read said a CO detector should be on a wall a foot or two below the ceiling or on the ceiling.  One source said to put it at eye level so it can be read easily.  Is that not correct?
Comment: I think the consensus is that CO detectors can go at any height (CO diffuses relatively evenly), unless the manufacturer specifies otherwise. Eye level would be convenient for ones that have a display. If it was me, I'd try it low for a while and see if I really wanted to move it.
Comment: CO is lighter than air, installing the detector higher rather than lower would be best, but follow manufacturer's instructions.
Answer: The power that's intended for your bathroom stays in your bathroom!
First, the answer to #1 is yes, you are alright on that front -- the GFCI only has to protect the bathroom receptacles, not anything else on that circuit, as per 210.8(A)(1):

210.8 Ground-Fault Circuit-Interrupter Protection for
  Personnel. Ground-fault circuit-interrupter protection for
  personnel shall be provided as required in 210.8(A) through
  (C). The ground-fault circuit-interrupter shall be installed in
  a readily accessible location.
Informational Note: See 215.9 for ground-fault circuit-
  interrupter protection for personnel on feeders.
(A) Dwelling Units. All 125-volt, single-phase, 15- and
  20-ampere receptacles installed in the locations specified in
  210.8(A)(1) through (10) shall have ground-fault circuit-interrupter protection for personnel.
(1) Bathrooms

However, the answer to #2 is no -- neither the CO detector nor the hall receptacle belong on the bathroom (technically, bathroom receptacle, but many bathrooms invoke the exception to 210.11(C)(3) that allows the rest of the bathroom's outlets to be on the same circuit as the bathroom's receptacles provided that the circuit only serves one bathroom) branch circuit.  It's a 210.11(C)(3) violation:

(3) Bathroom Branch Circuits. In addition to the number
  of branch circuits required by other parts of this section, at
  least one 120-volt, 20-ampere branch circuit shall be provided to supply a bathroom receptacle outlet(s). Such circuits shall have no other outlets.
Exception: Where the 20-ampere circuit supplies a single
  bathroom, outlets for other equipment within the same
  bathroom shall be permitted to be supplied in accordance
  with 210.23(A)(1) and (A)(2).

So, I'd find another circuit to tap for both the new CO detector circuit and the existing hallway receptacle.
Comment: "So, I'd find another circuit to tap for both the new CO detector circuit and the existing hallway receptacle."  I will probably just get a battery powered CO detector since there isn't another circuit handy to tie into.  The outlet in the hallway was in a perfect location to tap for a wire to a new outlet for a CO detector.

Electrical question concerning GFCI


Get latest and earliest value of different column from same table sql

Question: I have a table with a selection of dates. I want to be able to apply a WHERE statement to return a group of them and then return which date is the earliest from one column and which one is the latest from another column. Here is an example table:
ID  StartDate   EndDate     Person   Subject
1   01/03/2010  03/03/2010   Paul    Math
2   12/05/2010  22/05/2010   Steve   Science
3   04/03/2010  08/03/2010   Paul    English

So I want to return all the records where Person = 'Paul'. But return something like (earliest ) StartDate = 01/03/2010 (from record ID 1) and (latest) EndDate = 08/03/2010 (from record ID 3) and Subject = English  from  latest EndDate (from record 3 ). I need two rows for Paul with the above data and Id.Need all row with person = 'Paul'
Expected Result :
ID  StartDate   EndDate Person  Subject
1   2010-03-01  2010-03-08  Paul    English
3   2010-03-01  2010-03-08  Paul    English

Do you see any problem regarding performance (Millions of records) in below sql query  :
 Select PT3.ID,PT4.EarliestStartDate AS StartDate,PT4.EndDate,PT4.Person,PT4.Subject from Data AS PT3
Join( SELECT Top 1 with ties * FROM Data AS PT
Join( SELECT PT1.Person as Person1, MIN(PT1.StartDate ) as EarliestStartDate FROM Data AS PT1 where Person ='Paul' group by PT1.Person)  AS PT2 ON  PT.Person =PT2.Person1WHERE Person  ='Paul'
  Order By Row_Number() over (Partition By PT.Person Order By PT.EndDate desc)) AS PT4 ON PT3.Person = PT4.Person

Comment: Need all row with person = 'Paul'
Comment: please show your query
Comment: Sounds like `group by ' and min/max.
Comment: So you want to get the earliest start date and the latest end date regardless of subject? Then seperately just get the subject of the latest end date?
Comment: What is the expected result ?
Comment: @avinashkadu I assume the start date `04/03/2101` is a typo? Otherwise the corresponding end date would come before the start date...
Comment: Your latest edit just changed the question entirely... Can you explain why you need 2 rows to avoid any kind of [XY problem](http://xyproblem.info/)? And what are your criteria for the `ID` column in the result? If there was one row with both the smallest start date _and_ the latest end date, would you want to see that row id twice?
Comment: (1) That still does not answer how the `ID` column must be determined... The Id of the minimum start date row, the Id of the maximum end date row, the minimum and maximum of the ids, ... ? What if row 3 also contained the smallest start date? (2) You now changed the question _again_ to a performance related question this time. Please do not mix result questions with performance questions (_first_ make it work, _then_ make it work fast). Ask separate questions for each part.
Comment: For two  ID there will not  the smallest start date and the latest end date
Comment: What is the intention of the `with ties` in your query? This can give you more than 2 output rows with your query: [fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=48c63a7bf9d0e02c893ae8380e29e045).
Comment: @avinashkadu, You might want to include that important fact in your question. Now the `self-join` tag makes sense too. Updated my answer.
Comment: Thanks for the answer!
@Sander What about the performance? Do you have any thoughts on that?
Answer: This could work:

Perform the group by first to get the required dates for each person.
Move the grouping to a common table expression (cte).
Join back with the full data set to fetch all rows.
For each result record, select the corresponding subject with a cross apply.
Optional: filter on the required person (where clause).

Sample data
create table Data
(
  ID int,
  StartDate date,
  EndDate date,
  Person nvarchar(10),
  Subject nvarchar(10)
);

insert into Data (ID, StartDate, EndDate, Person, Subject) values
(1, '2010-03-01', '2010-03-03', 'Paul',  'Math'),
(2, '2010-05-12', '2010-05-22', 'Steve', 'Science'),
(3, '2010-03-04', '2010-03-08', 'Paul',  'English');

Solution
with cte as
(
  select min(d.StartDate) as StartDate,
         max(d.EndDate) as EndDate,
         d.Person
  from Data d
  group by d.Person
)
select d.Id,
       c.StartDate,
       c.EndDate,
       c.Person,
       x.Subject
from cte c
join data d
  on d.Person = c.Person
cross apply ( select top 1 d2.Subject
              from Data d2
              where d2.Person = c.Person
                and d2.EndDate = c.EndDate ) x
where d.Person = 'Paul'
order by d.Person;

Fiddle to see it in action.
Comment: I have added the expected result and my  query
Answer: This should give you the right values.
DECLARE @values TABLE (
    Id INT,
    StartDate DATETIME2,
    EndDate DATETIME2,
    Person NVARCHAR(MAX),
    Subject NVARCHAR(MAX))

INSERT INTO @values VALUES
(1, '2010-03-01', '2010-03-03', 'Paul', 'Math'),
(2, '2010-05-12', '2010-05-22', 'Steve', 'Science'),
(3, '2101-03-04', '2010-03-08', 'Paul', 'English')

;WITH sort AS (
    SELECT
        Person,
        MIN(StartDate) OVER(PARTITION BY Person) StartDate,
        MAX(EndDate) OVER(PARTITION BY Person) EndDate,
        Subject,
        ROW_NUMBER() OVER(PARTITION BY Person ORDER BY EndDate DESC) rownum
    FROM @values v)

SELECT
    Person,
    StartDate,
    EndDate,
    Subject
FROM sort
WHERE rownum = 1

It will give you the following result:
Person  MinStartDate    MaxEndDate   Subject
Paul    2010-03-01      2010-03-08   English
Steve   2010-05-12      2010-05-22   Science

Comment: Your current version does not solve the `Subject` part of the question.
Comment: @Kristofer how can I get all Id of paul as well with the same result set of your query (other column value will be same)?
Answer: This should be sufficient if you only care about selecting Pauls data:
SELECT
   Person,
   MIN(startDate) AS Earliest,
   MAX(EndDate) AS Latest,
   (
      SELECT TOP 1 Subject
      FROM Data
      WHERE Person = 'Paul'
      ORDER BY EndDate DESC
   ) AS Subject
FROM Data WHERE Person = 'Paul'

And this should work if you want to select all persons:
SELECT
   d1.Person,
   MIN(d1.startDate) AS Earliest,
   MAX(d1.EndDate) AS Latest,
   (
      SELECT TOP 1 d2.Subject
      FROM Data d2
      WHERE d2.Person = d1.Person
      ORDER BY EndDate DESC
   ) AS Subject
FROM Data d1
GROUP BY d1.Person

Edit: You seem to want to have results for every row in the table, instead of just one per person, but then always show the earliest and latest dates. Is this what your after?
SELECT
   d1.Id,
   d1.Person,
   (
      SELECT MIN(d1.StartDate) AS Earliest
      FROM Data d2
      WHERE d2.Person = d1.Person
   ) AS Earliest,
   (
      SELECT MAX(d1.EndDate) AS Latest
      FROM Data d2
      WHERE d2.Person = d1.Person
   ) AS Latest,
   (
      SELECT TOP 1 d2.Subject
      FROM Data d2
      WHERE d2.Person = d1.Person
      ORDER BY EndDate DESC
   ) AS Subject
FROM Data d1

Comment: Your answer does not contain valid SQL syntax (hint: the literal string `Paul` needs quotes).
Comment: @Sander I Fixed it and also added the Person column to the result
Comment: @Fuzzy I have updated the question with the expected result


Opening a new GUI window on a main GUI using GUI builder on netbeans

Question: I am playing about with GUI builder and i was wondering if there is an easy way to open the register window through the current main window (in reference to the page below). I am trying to do this through the menu bar.
I've been trying all day, because GUI Builder generates some code, its not possible to edit this code.

Thanks For the help!
Comment: In case ther is any confusion on the matter.. See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556)
Comment: no one is blaming the IDE i was just making a point.
Comment: but thanks for the link and improvements suggested.
Answer: Create a separate class which extends JDialog class and add your GUI components:
public Register extends JDialog {
   //Make GUI
   setModalityType(ModalityType.APPLICATION_MODAL); //Make it modal
}

Add ActionListener to that menu item which is supposed to open a register window:
mnuItmRegisteration.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        Register r = new Register();
        r.setVisible(true);
    }
});

Comment: You are welcome. And, oh...get rid of that GUI builder if you want to learn swing.
Comment: Thanks, but i only use GUI builder because its so easy to position things like buttons and text fields, its really hard to do this from scratch.  :)
Comment: @Marcello No its not! I used to create GUI apps with NetBeans GUI builder...until I realized I have no clue about Java swing. Also..have a look at that question from Andrews comment, because you are going to create a very unfriendly UI.
Comment: Okie dokie, i shall take this challenge.
Answer: Right click on that shortcut button, click Events, click ActionPreformed.
There you should write codes to make your register window appear.
An example:
  private void RegisterationEventActionPerformed(java.awt.event.ActionEvent evt) {
    JFrame Register = new Register();
    Register.setVisible(true);
  }

Remember to make another JFrame called ("Register" assuming u are using the code i gave) at the same package as your current JFrame
Maybe u would probably should use the run button (The button with a Green Triangle or Arrow), run it try to press the menu item, it should appear the register window.
Comment: Oh, you can always right click the same thing, choose Customize Code.


Induction Proof: Proof of Strict Inequality involving Exponents of 3 in the Denominator.

Question: I have been trying to do this problem by using induction but I became stuck halfway through:

Use induction to show that
  $$2\left(1+ \frac{1}{8} + \frac{1}{27} + \cdots + \frac{1}{n^3}\right) \lt 3 - \frac{1}{n^2}$$
  for $n\geq 2$.
  Does the series $$\sum_{n=1}^{\infty}\frac{1}{n^3}$$ converge? Justify your conclusions.

So far I have this:
Base Case of Induction, $n=2$
$$\begin{align*}
\frac{1}{n^3} &\lt 3- \frac{1}{n^2}\\
\frac{1}{8} &\lt 3 - \frac{1}{4}\\
\frac{1}{8} &\lt \frac{11}{4}
\end{align*}$$
Induction Step: Assume true for some $k \geq 2 :$
$$
2\left(1+ \frac{1}{8} + \frac{1}{27} + \cdots + \frac{1}{k^3}\right) \lt 3 - \frac{1}{k^2}$$
Show true with $n= k+1$
$$ 2 + 4 + \frac{2}{27} + \cdots + \frac{2}{k^3} + \frac{2}{(k+1)^3} \lt 3-\frac{1}{(k+1)^2}.$$
From there, I have no idea what to do.
I was planning to have
$$3 - \frac{1}{k^2} + \frac{2}{(k+1)^3} \lt 3 - \frac{1}{(k+1)^2}$$
but I feel like it won't work since
$$2\left(1 + \frac{1}{8} + \frac{1}{27}+\cdots+\frac{1}{k^3}\right)$$
does not equal
$$3 - \frac{1}{k^2}.$$
Answer: Hint $\ $ It is simple to prove by induction that an increasing function remains $\ge$ its initial value, i.e. that  $\rm\ f(n+1) \ge f(n)\:$ for $\rm\:n\ge 2\:$ $\:\Rightarrow\:$ $\rm\:f(n) \ge f(2)\:$ for $\rm n\ge 2$.
Now apply that to $\rm\:f(n) = $ RHS $-$ LHS of your inequality, which is increasing since
$$\rm f(n+1) - f(n)\: =\ \frac{3\:n+1}{n^2 (n+1)^3} > 0\ \ \ for\ \ \ n\ge 2\qquad \bf QED$$
Remark $\ $ It's worth mention that this may be viewed as prototypical example of telescopy. Indeed, viewing $\rm\:f(n)\:$ as the sum of its first differences $\rm\:f(n) = f(2) + \sum_{k=2}^{n-1} (f(k+1)-f(k)),\:$ the proof reduces to a trivial induction that a sum is $> 0\:$ if each summand is. In a similar way one may exploit telescopy to simplify many inductive proofs to trivial inductions (e.g. the trivial induction that $\rm 1^n = 1$). For many examples of this technique see my prior posts on telescopy.
Answer: When you go from
$$2\left(1+ \frac{1}{8} + \frac{1}{27} + \cdots + \frac{1}{k^3}\right) \lt 3 - \frac{1}{k^2}\tag{1}$$
to
$$2\left(1+ \frac{1}{8} + \frac{1}{27} + \cdots + \frac{1}{k^3}+\frac1{(k+1)^3}\right) \lt 3 - \frac{1}{(k+1)^2}\;,\tag{2}$$
the righthand side increases by
$$\left(3-\frac1{(k+1)^2}\right)-\left(3-\frac1{k^2}\right)=\frac1{k^2}-\frac1{(k+1)^2}\;,$$
while the lefthand side increases by $\dfrac2{(k+1)^3}$. If you can show that $$\frac2{(k+1)^3}\le\frac1{k^2}-\frac1{(k+1)^2}\;,\tag{3}$$ you've shown that $(1)$ implies $(2)$, which is your induction step; do you see why?
Now $(3)$ can by multiplied through by $k^2(k+1)^3$ to yield the equivalent inequality $$2k^2\le (k+1)^3-k^2(k+1)\;,$$ which in turn simplifies to $0\le 3k+1$. This is certainly true for $k\ge 2$, and it's equivalent to $(3)$, so $(3)$ is true for $k\ge 2$, and your induction step is done.
For the second part of the question, note that the $n$-th partial sum of the infinite series is $$\sum_{k=1}^n\frac1{k^3}\;,$$ and from the first part of the question you know that $$2\sum_{k=1}^n\frac1{k^3}<3-\frac1{n^2}\;,$$ so $$\sum_{k=1}^n\frac1{k^3}<\frac32-\frac1{2n^2}\;.$$ Thus, the partial sums form an increasing sequence bounded above by ... what? And what can you conclude from that about the convergence of the infinite series?
Answer: It doesn't matter that the sum does not equal $ 3- \frac{1}{k^3}$. What matters is that the sum is less than $3 - \frac{1}{k^3}$.
We have:
$$2\left(1+ \frac{1}{8} + \frac{1}{27} + \cdots + \frac{1}{k^3}\right) \lt 3 - \frac{1}{k^2}.$$
Adding $\frac{2}{(k+1)^3}$ to both sides does not change the inequality, so we have
$$2\left(1+ \frac{1}{8} + \frac{1}{27} + \cdots + \frac{1}{k^3}\right) + \frac{2}{(k+1)^3} \lt 3 - \frac{1}{k^2} + \frac{2}{(k+1)^3}.$$
The left hand side is the quantity you want.
With the right hand side, we have
$$\frac{1}{k^2}\gt \frac{1}{(k+1)^2},$$
so
$$-\frac{1}{k^2} \lt -\frac{1}{(k+1)^2},$$
hence
$$\frac{2}{(k+1)^3} - \frac{1}{k^2} \lt \frac{2}{(k+1)^3} - \frac{1}{(k+1)^2} = \frac{1}{(k+1)^2},$$
so
$$3 - \frac{1}{k^2}+\frac{2}{(k+1)^3} \lt 3 - \frac{1}{(k+1)^2}.$$
And since $a\lt b$ and $b\lt c$ implies $a\lt c$, then...
For the last part of the question, note that the quantity on the left hand side is twice the $n$th partial sum of
$$\sum_{n=2}^{\infty} \frac{1}{n^3}.$$
So you should be able to conclude that the partial sums of
$$\sum_{n=1}^{\infty}\frac{1}{n^3}$$
are bounded above; since all terms are positive, that means that...
Answer: Your sum converges to
$$
\sum_{n=1}^\infty \frac{1}{n^3} = \zeta(3),
$$
because the series $    \sum_{n=1}^\infty \frac1{n^{1+\varepsilon}} $ (cf. Riemann zeta function) converges for every ε > 0, because
$$
    \int_1^M\frac1{x^{1+\varepsilon}}\,dx =-\frac1{\varepsilon x^\varepsilon}\biggr|_1^M= \frac1\varepsilon\Bigl(1-\frac1{M^\varepsilon}\Bigr) \le\frac1\varepsilon \quad\text{for all }M\ge1.
$$
Comment: This really doesn't answer the question.


SP2013 get time difference in minutes

Question: I have a list with a date-time column called "Status Date". What I need to do is display the number of hours and minutes between "Status Date" and Now() in a calculated column.
The CONCATENATE method does not work, because it only updates when the list item is edited. I need the time difference to update each time the page loads. I am using the workaround to leverage javascript in an tag. However, when I try to use the "Status Date" field in a new Date() method it returns as "Wed Dec 31 19:00:43 EST 1969"
here is my code for the calculated column. It returns the number of minutes in the current hour.

Answer: Use JSLink for this requirement.
Similar thread here

SP2013 get time difference in minutes


Reference resources from other module in Android Studio

Question: I have a main app module as well as a few library modules.
How can my Library module reference resources from the Main App module.
For instance:
My base app has a colors.xml which has a color item called "AppPrimary" which is blue.
In my library I want a view in an xml layout to reference @color/AppPrimary color, but that doesn't work.
How can I achieve this?
Edit: I should specify this isn't specifically appCompat resources. Just generic strings/colors/styles/in my main module. How can I reference them in the same project in my library module colors.xml/strings.xml?
Answer: In your library module in the xml layout reference ?attr/colorPrimary instead of @color/AppPrimary
This references the color palette attributes from your app's theme. i.e.;
<item name="colorPrimary">@color/AppPrimary</item>

You can also refer to the other color palette attributes like:
<item name="colorPrimaryDark">...</item> -> ?attr/colorPrimaryDark
<item name="colorAccent">...</item> -> ?attr/colorAccent

and so on.
Please refer to this documentation
CAVEAT:
These examples refer the AppCompat implementation in the theme. i.e. no android: namespace prefix.
-- EDIT --
The short answer is that you simply can't 'get' a defined color from your main module referenced to your libraries colors.xml file.
You can however leverage custom defined attributes in your theme to achieve the same effect.
This works by declaring a generic styleable in your attrs.xml file in the library module, Something like this:
<declare-styleable name="BaseTheme">
    <attr name="someColor" format="reference|color" />
</declare-styleable>

Note: The name of the styleable has no bearing on this implementation so feel free to name it whatever you want.
Then in your main module's theme definition in your 'style.xml' or 'theme.xml' file you'll want to set this attribute to the color you want to share, like this:

Once this is defined, you can reference the attribute in your library module XML code. e.g.;
<TextView
    ...
    android:textColor="?attr/someColor"
    />

Comment: I should specify these aren't nessicarily appcompat resources. Say its just a general color defined in the main app module called "dark_blue". How do get that dark_blue color in my library colors.xml?
Comment: I have updated the answer to better suite your use case.
Comment: Thanks r0adkl I have changed the project structure. Instead I have defined a common core library which all modules (libraries and base app) can reference with app colors/common strings etc.
Comment: It works if external module has executable "thing" but what if I use external module as container for drawables?
Answer: Here's how you can get color attributes while in a library module programmatically.
@ColorInt
public static int getAttributeColor(Context context, @AttrRes int colorAttribute)
{
    int[] attrs = {colorAttribute};
    TypedArray ta = context.obtainStyledAttributes(attrs);
    /*Get the color resourceID that we want (the first index, and only item, in the
    attrs array). Use ContextCompat to get the color according to the theme.
    */
    @ColorInt int color = ContextCompat.getColor(context,
                                                 ta.getResourceId(0, -1));
    // ALWAYS call recycle() on the TypedArray when you're done.
    ta.recycle();
    return color;
}

Ex.
//Get the main applications 'colorAccent' from the app's color palette.
int appAccentColor = Utility.getMarketAttributeColor(context, R.attr.colorAccent);

//Get the color attribute your module made for the client app to define.
int moduleAttrColor = Utility.getMarketAttributeColor(context, R.attr.moduleColorAttr);

Note: This basic attribute retrieval process applies to most attribute types.


definition of foliation in manifold and why foliation is useful?

Question: I am thinking for the simple definition of "foliation" for a manifold. Why foliation is useful in manifold theory?
Comment: Are you asking for the definition? If so, [Wikipedia has the answer](http://en.wikipedia.org/wiki/Foliation).
Comment: I am looking for a simple definition
Answer: Roughly speaking, a codimension $n-q$ foliation $F$ on an $n$-manifold $M$  is partition of $M$ in $q$-manifolds, called leaves, such that locally $M$ is a product $R^{q}\times R^{n-q}$.  Foliations are useful because  they can give information about the topological structure of the manifold. For example a non-singular foliation on a 2-manifold $M$ implies that $M$ is the torus or the Klein bottle. A special case of a foliation is a non-singular flow, which serves as model for some physical systems.
Comment: I assume the $2$-manifold $M$ is compact?
Comment: @JesseMadnick I agree. Otherwise, as it is said on Fantasy Island: "Lookit the plane, boss, lookit the plane!"


Crafting writ not registering as completed

Question: Yesterday I picked up a writ for jewelcrafting. The requirement was 2 pewter necklaces.
I crafted 1 of the most simple type (the least number of resources). The text appeared in the middle of the screen, updating my progress to 1/2 necklaces crafted.
The second necklace I crafted using the highest amount of pewter I could choose, resulting in a necklace my character can't equip yet. The text never appeared,  the quest progress remained 1/2.
I'm positive I crafted the correct item twice. I tried to craft another which didn't register either and even logged in and out and waited a few minutes. I'll need to try again later when I have mined more pewter.
My game installation is standard, no mods or changes. Has anyone encountered this before? Is there a way to fix it?
Answer:
The second necklace I crafted using the highest amount of pewter I could choose

This is the problem. For some reason, items only count toward a writ if you craft them at the minimum level for their type. Make another level 1 pewter necklace and it should work.
Answer: This shouldn't happen. Are you 100% sure both necklaces are identical? They have to be white quality with no traits (the level doesn't matter as long as it's the correct material). Also make sure you don't have any other items of the same quality/level crafted by another character in inventory.
If it still doesn't progress properly, keep the crafted items in your inventory, but abandon the quest and pick it up once again. It should complete straight away as long as the items were crafted by your character.
Comment: Pretty sure. At one moment I had 3 identical pewter necklaces, all 3 without a trait, only of different levels. I'll try your suggestion when I can.
Comment: I abandoned the quest, but I was given the quest to craft 3 rings instead. I'll need to wait for another day when necklaces are the quest objective again.
Comment: craft requests only mark as complete if the item is the most basic they can be - the same applies to armour and weapons (you have to use the minimum amount of materiales (and I think no traits either); Enchanting glyphs are created with Ta only - nothing higher; and jewelry is created at the simplest level requested.
Comment: @MeanGreen - craft them all at the same minimum level for the material - there is no benefit to crafting higher rated items for writs - they don't count at all.


How Do I Use Selenium WebDriver To Click A Non Anchor Tag?

Question: I am using Selenium WebDriver to do automated testing of a website. I have been successful in clicking through numerous menus and links to a point.
At one point the website I am working with generates links that look like this:
Responsibility Code

I am trying to use the .click functionality of the webdriver to click this link with no success.
Using this:
page.find_element_by_xpath("//u[contains(text(),'Responsibility Code')]")

successfully finds the U tag above. but when I add .click() to the end of this xpath, the click is not performed. But it also does not generate an error. So, my question is can Selenium be used to simulate clicks on an HTML tag that is NOT an anchor () tag? If so, how?
I will also say that I do not have control over the page I am working with, so changing the  to  is not possible.
I would appreciate any guidance the Community could provide.
Thank You for you help,
Chris
Comment: It might be worth trying to click the surrounding tags, or nearby tags that are in the same position as this element, just in case one of those is the one that's supposed to receive the click
Answer: Sometimes using JavaScript could solve the "clicking" issue:
element = page.find_element_by_xpath("//u[contains(text(),'Responsibility Code')]")
page.execute_script('arguments[0].click();', element)

Comment: Please mark this answer as `Accepted` if it solved your issue. Thanks
Answer: You can prefer JavaScript in this case.
WebElment  element = page.find_element_by_xpath("//u[contains(text(),'Responsibility Code')]")

JavaScriptExecutor executor = (JavaScriptExecutor)driver;

executor.ExecuteScript("arguments[0].click();", element);


Xamarin Studio 6.3 with mono 4.8.. suddenly debugger not working

Question: I cannot hit breakpoints in Xamarin Studio since yesterday afternoon. Restart, clean, rebuild still no joy. Using Mac OSX. I am aware this issue is in version 5 of mono. But I am on 4.8. Is anyone having the same problem. Very frustrating.
Comment: Same problem here. Have you found any solution?
Comment: I had to remove my local copy of the project and pull a new one from the repo. I suspect I did a copy and paste and I must have introduced a hidden character to my code somewhere. So all I did was to bump the local copy and pull a new one from the dev branch.
Answer: Dump your local copy and pull a new copy from the repo.


C countLetter function

Question: So I have created a function which currently counts all individual lower case letters in a string, and outputs them like:
a : 3
b : 5
and so on...
I am struggling to get the function to add both the uppercase and lowercase letters together, so that there is one output for both values. For example, if there is 3 'a' and 4 'A', then the output for A / a should be 7. At the moment only the lowercase characters are being output.
#include <stdio.h>

void countLetters(char * strings[])
{
int loweralphabet[26] = { 0 };
int upperalphabet[26] = { 0 };
int i, j;

for (i = 0; i <= 2; i++) {
    for (j = 0; strings[i][j] != '\0'; j++) {
        char c = tolower(strings[i][j]);
        if (c >= 'a' && c <= 'z') {
            loweralphabet[c - 'a']++;
        if (c >= 'A' && c <= 'Z') {
            upperalphabet[c - 'A']++;
        }
        }
    }
}
printf("\n");

for (i = 0; i < 26; i++) {
    printf("%c / %c: %d\n", ('a' + i), ('A' + i), loweralphabet[i],
upperalphabet[i]);
}
printf("\n");

return 0;
}

int main()
{
char * strings[] = { "Is laid back living your thing, ",
                     "or are you an adrenaline junkie always seeking
                      adventure ?",
                     "Are you a culture lover looking to learn new things or
                      do you live for the night ?",
                     "Do your friends see you as a sports fanatic, ",
                     "or are you a frequent gig goer obsessed with music ?
                     ",
                     "Whichever of these you identify with, x is the
                      place where you can follow your interests ",
                     "as well as explore new passions.",
                     "" };
countLetters(strings);
}

If I just add the two counts together in the print function, when outputting the program this shows:
Comment: Not sure if it's a copy/paste mistake but there is probably an error with your curly parentheses in the section where two if statements are.
Comment: The output you showed us almost certainly didn't come from the code you showed us. if you want us to fix the bug in some code, you need to show us the code with the bug -- not some other code that works.
Comment: In the `printf` just add the two counts together with a `+` sign.
Comment: I said that the displayed output is shown when I try to add the two count functions together in the printf function. My goal is for the program to count each letter of the alphabet in the strings listed below, with it being case insensitive. Currently the program is either counting only lower case characters, or only some. I updated my post to display all the code in the program @DavidSchwartz
Comment: for a start this code doesnt compile. Its missing ctype.h and your printf has 3 '%' but 4 args passed in. YOu return 0 from a function declared void
Answer:         char c = tolower(strings[i][j]);
        if (c >= 'a' && c <= 'z') {
            loweralphabet[c - 'a']++;
        if (c >= 'A' && c <= 'Z') {

After line #1, condition in line #4 will never be satisfied. Moreover, it will never be satisfied due to the fact that it is placed inside the then-block of condition in line #2 (i.e. you have made sure that c is lowercase, and now you check if it is uppercase; of course it's not).
In fact, it is not quite clear what are you struggling with. As your program is written now, it should count letters case-insensitive.
Comment: Only lowercase letters are being counted right now, which is why I too am confused.
Comment: @JoshB Can you be more precise about what you mean by 'only lowercase letters are being counted'? Are uppercase letters being ignored? Are you talking about what the code you showed in the question or some other code?
Answer: Figured it out. The program currently is only counting the first 3 strings:
    for (i = 0; i <= 2; i++)

After asking it to count all 7, the program functioned as intended.
Answer: here is the corrected counting loop
for (i = 0; i <= 2; i++) {
    for (j = 0; strings[i][j] != '\0'; j++) {
        char c = strings[i][j];
        if (c >= 'a' && c <= 'z')
            loweralphabet[c - 'a']++;
        if (c >= 'A' && c <= 'Z')
            upperalphabet[c - 'A']++;

    }
}

you were setting c to lowercase and then trying to test if it was upper case, but your test nesting was wroing too
YOur code actually says this once the indentation is fixed.
for (i = 0; i <= 2; i++) {
    for (j = 0; strings[i][j] != '\0'; j++) {
        char c = tolower(strings[i][j]);
        if (c >= 'a' && c <= 'z') {
            loweralphabet[c - 'a']++; <<<< missing } here
            if (c >= 'A' && c <= 'Z') { <<< can never be true c is always lower case , even if you got here
                upperalphabet[c - 'A']++;
            }
        }
    }
}

so you were never doing the second test

C countLetter function


How do I figure out the time in Robert Goodman's memories?

Question: In Episode 1: The Hangman, I need to work through Robert Goodman's memories of his wife. I have figured out things like the dress color, the date, the station, etc. However, I have no clue how to figure out the time.
When I ask Robert about it directly, he says he doesn't remember the time. I've listened to the evidence tape and he says that he "looked down at my cell phone and said it was our time", then admits it was an inside joke. Unfortunately, I don't have the ability to ask Robert about that. I thought it might be something like them sharing the same birthday, but the people database shows that this isn't the case.
How can I figure out the time that Robert Goodman last remembers his wife?
I would appreciate an answer that contains hints, with the solution in a spoiler tag.
Answer: Figured out the answer myself, but answering for the benefit of anybody else.
You're on the right track. Robert did say on the tape that "it was our time" and that is a likely candidate for how to figure it out.
Hint 1:

 Robert might be a bit unnerved if you were to ask him out of the blue what "our time" means.

Hint 2:

 You'll need to find some way to prompt him for the information.

Hint 3:

 It wasn't your new powers that led you to think of "our time". What was it?

Solution:

 Show Robert the tape recorder. Once he hears the phrase, he will explain what "our time" means.


finally found the smell but don't know how it got there

Question: So a few months ago I asked a question about a strange smell I would have described them as slightly related to Tuepentine. My house is 2 floors with 2 tenants. The top Tennant owns fish and aquariums and the bottom tenant works with wood. Randomly, there was a smell of this chemical in the house and they had to evacuate for 24 hours. When they came back the smell was gone.
Everyone said it was the bottom tenant and the chemicals he uses but he used non VOC chemicals.
After that I just went on the assumption that it was that until last week when I had some repairs done to a drain pipe.
The plumber brought some PVC glue and it was the exact same "turpentine" smell we smelled a while back.
So I now know what the smell exactly was but not sure exactly how the smell happened. My plumber said someone could have left a small bottle of it in the walls and it may have been knocked over time but I think it could have been something else.
To prevent the smell from coming again I think it could have been caused by something else but I am not sure.
Any ideas on how the smell could have happened? The plumbing work was done 3 years ago besides the pipe last week
Comment: A PVC cement container open for 3 years would have turned to stone 2 years ago.
Comment: Just so we are clear, low VOC does not mean that it won't smell. I've sprayed some nasty primers (Rodda - Prime Solutions Speed Prime) that stink like you wouldn't believe. They can clear a building with a quickness.
Comment: I have no idea of the chemical smells associated with aquariums. Wood work, however, uses all sorts of solvents. I'd be looking at the wood worker with suspicious eyes.
Comment: Everyone keeps pointing to the wood guy but he showed me the chemicals he uses or at least the ones he isn't hiding and none of them smells like the PVC cement or glue. The actual smell was exactly like the PVC glue or cement
Comment: Those who care for aquariums have been known to use solvent-rich sealers or adhesives.
Answer: The main solvent in PVC cement is tetrahydrofuran (THF).
This solvent is used in some varnishes that woodworkers use. It is also used in cleaning and maintenance of 3D printers. (It un-clogs a clogged print head.)
Tetrahydrofuran is unusual in that although it is a strong solvent, it mixes easily with water. It is conceivable that someone in the house disposed of THF down their sink or toilet and ran water to flush it out. This could have spread fumes throughout the household plumbing drains, where water in the traps under the sinks could have absorbed the highly volatile THF vapors and released them into the living space.
So you might question the woodworker, ask if their varnishes contain any tetrahydrofuran, and ask how they dispose of excess varnish. Also ask if either tenant has a 3D printer.
The good news is that although THF is toxic in high concentrations, it has about the same toxicity as acetone, which is in some nail polish removers. In other words, toxic but not plutonium, as one member here says.


Water damage? Is this mold? What should we do next?

Question: Thoughts on what may have caused this?  Not sure how long it's been a issue.  Noticed the moisture under the ledge today that led to the discovery of what's in the picture…. advice on what to do next? In South Carolina
Comment: Looks like water damage and mold
Answer: It's water damage, but the source isn't clear. Could be:

A leak at the window frame
A leak at the head of the window or higher up the wall
A leak at the window sash
Condensation on the inside

You'll want to track that down with some observation. The fix is basic drywall work:

Scrape away the loose material. Try not to damage the metal corner bead, if present.

Use a setting type joint compound for best future moisture resistance (as opposed to premix) to fill and skim.

Sand, prime, paint.

I don't worry much about mold. Unless you're overly sensitive or there's a huge amount of it, that's just life. Mold is already everywhere.


flexiquote rotator custom tweak

Question: I'm using flexiquoterotator for word press I tweaked it to show the next and previous button following is my code
function ($) {
    var callquote;
    quoteRotator = {
    i: 1,
quotes: [";

    $i=0;

    foreach($results as $result){

    echo "\"$openquote$result->quote$closequote";

    if($result->author != '')

echo " $result->author";

    echo "\",\n";
        $i++;

        }

],

        numQuotes: ".$i.",

    fadeDuration: ".$fade.",
                    fadeoutDuration: ".$fadeout.",

                    delay: ".$delay.",

                    quotesInit: function(){

                        if (this.numQuotes < 1){

                            document.getElementById('quoterotator').innerHTML=\"No Quotes Found\";

                        } else {
                            this.navQuote();
                            this.quoteRotate();
                            this.quotehover();
                        }
                    },
                    navQuote: function() {
                        $('

').insertAfter('#quotearea');
                        for (n=1; n <= this.numQuotes ; n++) {

        }

$('#quotenav').append('Next');

for (k= -3; k <= this.numQuotes ; k++) {

        }

                        $('#quotenav').append('Prev');

                        // insert style
                        $('head').append('');
                    },
                    quoteRotate: function(i){
                        if(!i) {
                            i = this.i;
                        }
                        $('#quotenav span').each(function () {
                            $(this).removeClass('active');
                        });
                        $('#quotenav span:nth-child('+i+')').addClass('active');

                        jQuery('#quoterotator').hide().html(this.quotes[i - 1]).fadeIn(this.fadeDuration * 1000).css('filter','');

                        this.i = i % (this.numQuotes) + 1;

                        callquote = setTimeout('quoteRotator.quoteRotate()', (this.delay + this.fadeDuration) * 1000);

                    },
                    callQuote: function(e,n) {
                        clearTimeout(callquote);
                        this.quoteRotate(n);
                    },
                    quotehover: function() {
                        jQuery('#quotearea').mouseenter(function () {
                            clearTimeout(callquote);
                          }).mouseleave(function(){
                                setTimeout('quoteRotator.quoteRotate()', 500);
                          });
                    }
                }
        })(jQuery);

The above code doesn't shows the next and prev buttons instead it works for dot base navigation.
Comment: Please format your code before posting the question. It is not readable at all.
Comment: You can format that if you like to
Answer: I Changed the location for buttons and it worked.

flexiquote rotator custom tweak


How to generate random points inside a rectangle with Gaussian distribution

Question: How to generate $N$ random points inside a rectangle of side $L\times L$ with a Gaussian distribution.
Comment: Isn't the support of a Gaussian measure the entire plane?
Comment: Yep. (Hey NCMathSadist---NCSSM '86 right here)
Answer: Strictly speaking, your requirements are contradictory. A Gaussian distribution has infinite extent, so once you limit yourself to an $L\times L$ rectangle, it can no longer be a Gaussian distribution.
However, one thing you can do is generate points using a raw Gaussian distribution and simply discard those that fall outside of the $L\times L$ rectangle. The points that remain will be distributed according to a truncated Gaussian distribution.
If you wish to edit your question to provide more specifics on what you're looking to do, I will edit my answer to suit.
EDIT: Here is some example MATLAB code to generate $N$ points with mean 0 and standard deviation $\sigma$ inside a rectangle of size $L\times L$. No error checking is performed!
<code>function ans = randn_rect( N, sigma, L )
ans = zeros(0,2);
while size(ans,1) < N,
   pts = sigma * randn( ceil(1.25*(N-size(ans,1))), 2 );
   pts = pts(all(abs(pts)<L/2,2),:);
   ans = [ ans ; pts ];
end
ans = ans(1:N,:);
</code>
Comment: I just have a rectangle and N points, and I want to deploy those points inside a rectangles with a Gaussian distribution, is this not sufficient?
Comment: If the points have a true Gaussian distribution, then they cannot be contained within a rectangle. The Gaussian distribution has infinite extent. Now, they could have a *truncated* Gaussian distribution, which is what I have described in my answer here. Are you asking how to write the code? In what language?
Comment: You mean that if I use truncated Gaussian distribution, I will have no guarantee that all points will be included inside a rectangle?
Comment: If you use a *truncated* Gaussian distribution, sure. But you have to do the truncation yourself, which is my point. A *true* Gaussian distribution can make no such guarantees.
Comment: In this case which form will include all the points, circle?
Comment: I am using python language
Comment: "In this case which form will include all the points, circle?" I do not know what this means. Again: if you want a *true* Gaussian distribution, there is *no rectangle or circle or any other volume* that is guaranteed to contain them all. You must deliberately discard the points that fall outside of your desired extent. And once you commit to doing that, you can pick whatever extent you want: a rectangle, circle, whatever.
Comment: Thank you, I understand now.
Comment: I'm sorry my Python is too rusty to just bang out an equivalent NumPy implementation above.
Comment: Is it possible to get only the algorithm of how to generate the $X,Y$ coordinates of each point?
Comment: I have never worked with Matlab, if you could give me a python code I will be grateful.
Comment: @sys: if you want code examples, try asking on [Stack Overflow](http://stackoverflow.com). They have quite a few Python experts there.
Comment: Sorry, I'm done programming here. I'd take Ilmari's suggestion.


Product rule in an Inner product Space

Question: I have been working in the book "Differential Geometry
Connections, Curvature, and Characteristic
Classes" to Loring W. Tu.
My question is regarded excercise which yields:

An inner product space $(V,\langle \ , \ \rangle)$ is automatically a normed vector space, with norm $\lVert v \rVert = \sqrt{\langle v , v \rangle}$. The derivative of function $f : \mathbb{R} \to V $ is defined to be
$$
f^{\prime}(t) = \lim_{h \to 0}\frac{f(t+h) - f(t)}{h},
$$
provided that the limit exists, where the limit is taken with respect to the norm $\lVert \ \rVert$. If $f,g : \mathbb{R} \to V$ are differentiable functions, show that $\langle f,g\rangle : \mathbb{R} \to \mathbb{R}$ is differentiable and
$$
\langle f,g\rangle^{\prime} = \langle f^{\prime},g\rangle + \langle f,g^{\prime}\rangle.
$$

The way to prove it is similar to the product rule in $\mathbb{R}^{n}$. But I am stuck with taking the deriviative with resp. to the norm an later in proving the product rule. Can someone explain the steps or proof?
Comment: Use the fact that the definition with the limit is equivalent with the formulation $f(t+h) = f(t) + hf'(t) + o(h)$.
Answer: You could do something like this:
$$\frac{\langle f,g\rangle(t+h)-\langle f,g\rangle(t)}{h} = \frac{\langle f(t+h),g(t+h)\rangle-\langle f(t),g(t)\rangle}{h} = \frac{\langle f(t+h),g(t+h)\rangle-\langle f(t),g(t+h)\rangle+\langle f(t),g(t+h)\rangle-\langle f(t),g(t)\rangle}{h} = \frac{\langle f(t+h)-f(t),g(t+h)\rangle+\langle f(t),g(t+h)-g(t)\rangle}{h} = \left\langle\frac{f(t+h)-f(t)}{h},g(t+h)\right\rangle + \left\langle f(t),\frac{g(t+h)-g(t)}{h}\right\rangle$$
Now you can show that $$\lim_{h\to0}\left\langle\frac{f(t+h)-f(t)}{h},g(t+h)\right\rangle=\langle f'(t),g(t)\rangle$$ and $$\lim_{h\to0}\left\langle f(t),\frac{g(t+h)-g(t)}{h}\right\rangle=\langle f(t),g'(t)\rangle$$ because both $f$ and $g$ are differentiable, and $\langle\cdot,\cdot\rangle$ is continuous. Then it follows that the limit $$\lim_{h\to0}\frac{\langle f,g\rangle(t+h)-\langle f,g\rangle(t)}{h}$$ exists and is equal to $\langle f'(t),g(t)\rangle+\langle f(t),g'(t)\rangle$.
Comment: Thanks alot for the help!

Product rule in an Inner product Space


How do I defeat the cyclops in Dark Messiah?

Question: I'm getting my ass kicked by the Cyclops in Chapter 5.  I can wait for him to attack and hit him in the eye when he's bent down but it's sucking up all my health potions. There's GOT to be a better way!
Comment: *POTENTIAL SPOLER* It's been quite a long time since I've played the game, so just to be clear, just which chapter is chapter 5? Are you talking about the cyclops you fight in the cave/ruins (the one that busts through the wall) or the one you fight in some city later on? (or perhaps it's a different one I don't remember altogether).
Answer: One thing that makes this easier is to drop the statue on the other end of the room on him. Kicking it into him after it's fallen is also a lot more effective than it should be.
I've also found that stabbing (forward and backward strong attack with a sword) is more effective, and sometimes results in a one-hit kill (with a fairly weak sword, without adrenaline).
Of course, this cyclops is completely optional. You can also come back after you place the Shantiri crystal -- if you visited a certain secret area earlier, you can smelt a very powerful sword later in the chapter.
Comment: Very nicely written.
Answer: If you find the Endless Quiver earlier on in the level, you can just stick arrows in his eye from the corridor the goblins came from.


Mount ecryptfs automatically after ftp login

Question: How can I get my ubuntu server 12.04 to automatically mount the encrypted home partition after an ftp login? It will automatically mount after an ssh login and I can then access the encrypted information over ftp but I don't want to have to log into ssh every time I want to use ftp.
Comment: How is SSH mounting it?
Answer: When you login into your system, either directly or via ssh, it is usually the pam_ecryptfs module that takes care of automatically mounting your encrypted home.
This module will use your password to decrypt a better key (referred to as passphrase in the docs) and make your encrypted home directory available.
Setting up pam_ecryptfs for FTP logins seems like a really bad idea, though. FTP sends passwords (and data) in clear text. This means that anyone on your network will be able to steal your password and be able to decrypt your data.
I would either:

Not use FTP. Use sftp, scp, putty, winscp, whatever, based on ssh.
If you have to use FTP, I would not encrypt the data at all. Assume that once you do the first transfer, anyone will be able to access it anyway. Or create a subdirectory where you keep data available via FTP.

If you really really want to enable mounting encrypted directories automatically with ftp, you can add a line like:
auth    required        pam_ecryptfs.so unwrap
in /etc/pam.d/proftpd, assuming your FTP server is proftp.
If you use this and it works, please tell us you are using a VPN or a socks proxy over an SSL tunnel or ssh. Lie if you have to.


How to read a custom path of a file in c++?

Question: My file is located in C:\\Input\\pStep.p21 . i want to open that file in my cpp program. How can i do it? I am using char* inputPath="C:\\Input\\pStep.p21"; but its not finding my file in program. How to get current working directory in VC++?. Its working if try to save p21 file but failing if i read it.
my code in CAA:
#include<CATSDM_Services>
#include<SdaiModel.h>
#include<CATIUniCodeString>
---
---

main()
{
CATIUniCodeString inputPath("C:\\Input\\pStep.p21");
HRESULT hr=S_OK;
SdaiModel edxModel=Null;
//this method reads express schema name, input p21 file and sdaimodel
 hr=CreateModelFromFile(inputPath,"parts",edxModel);
if(FAILED(hr))
{
cout<<"Model created succesfully";
}
else
{
cout<<"Failed";
}
}

Comment: It's not located in `C:\\Input\\input.txt` (although that's how you need to use it in C/C++. How are you trying to open it? What does "not finding my file in program" mean? Please edit your question and add more specifics, including the code you are using to try and open it and what "not findinng my file in program" means. Thanks.
Comment: Not even that only method , all the methods that related to importing a p21 file to sdaimodel are generating the same error. Am i missing something..Creating a fresh model working file with the same schema(parts) what i used above. But when it comes to importing an existing data(p21 file) its bugging me a lot.
Answer: Sorry for not seeing the question earlier.
From what I am seeing in your code, the test is wrong. The FAILED() macro denotes incorrect execution. Thus from you code, if you see "Failed" on the console, it actually means the execution of the method ran OK.
Change your code to something like:
if ( SUCCEEDED(hr) )
{
    cout<<"Model created succesfully";
}
else
{
    cout<<"Failed";
}


Get two 2 randomly selected words from 2 separate lists

Question: I am trying to put a little js on a webpage to randomly select a word from one list and another word from another list when you click on the random button. At the moment I am using the following code to get a single word returned from one list but I can not work out how to make it work with multiple lists of words.

Random

Thanks for the help
-Samuel
Answer: Try doing this:

This will select a random string from 2 different lists (randomStrings1 and randomStrings2), and concatenate them.
Comment: Thank you very much, I feel very simple now haha.


How can I grep and sort text files using Perl?

Question: I have a simple log file which is very messy and I need it to be neat. The file contains log headers, but they are all jumbled up together. Therefore I need to sort the log files according to the log headers. There are no static number of lines - that means that there is no fixed number of lines for the each header of the text file. And I am using perl grep to sort out the headers.
The Log files goes something like this:
Car LogFile Header
<text>
<text>
<text>
Car LogFile Header
<text>
Car LogFile Header
<and so forth>

I have done up/searched a simple algorithm but it does not seem to be working. Can someone please guide me? Thanks!
#!/usr/bin/perl

#use 5.010; # must be present to import the new 5.10 functions, notice
#that it is 5.010 not 5.10

my $srce = "./root/Desktop/logs/Default.log";
my $string1 = "Car LogFile Header";
open(FH, $srce);
my @buf = <FH>;
close(FH);
my @lines = grep (/$string1/, @buffer);

After executing the code, there is no result shown at the terminal. Any ideas?
Comment: Well, if you want to show results, you have to output something.
Comment: You use `@buf` first but then refer to it as `@buffer`.
Answer: I think you want something like:
 my $srce = "./root/Desktop/logs/Default.log";
 my $string1 = "Car LogFile Header";

 open my $fh, '<',  $srce or die "Could not open $srce: $!";

 my @lines = sort grep /\Q$string1/, <$fh>;
 print @lines;

Make sure you have the right file path and that the file has lines that match your test pattern.
It seems like you are missing a lot of very basic concepts and maybe cutting and paste code you see elsewhere. If you're just starting out, pick up a Perl tutorial such as Learning Perl. There are other books and references listed in perlfaq2.
Comment: @JavaNoob: because "$scre" is not spelled the same as "$srce".
Comment: I don't get why is the "my" at $fh cause the system's giving this error now "Global symbol "$scre" requires explicit package name" as the $srce should have no problem.
Comment: Oops.....Didnt notice that thanks.. But It seems that the codes only print out the header and not the paragraph. I guess must be the question being asked wrong. Anyway its the right answer.
Comment: Provide a short sample file, then show us exactly what you want the output to be. Don't accept this answer if it's not giving you what you need.
Answer: Always use:
use strict;
use warnings;

This would have told you that @buffer is not defined.
#!/usr/bin/perl

use strict;
use warnings;

my $srce = "./root/Desktop/logs/Default.log";
my $string1 = "Car LogFile Header";
open(my $FH, $srce) or die "Failed to open file $srce ($!)";
my @buf = <$FH>;
close($FH);
my @lines = grep (/$string1/, @buf);
print @lines;

Perl is tricky for experts, so experts use the warnings it provides to protect them from making mistakes.  Beginners need to use the warnings so they don't make mistakes they don't even know they can make.
(Because you didn't get a chance to chomp the input lines, you still have newlines at the end so the print prints the headings one per line.)
Comment: If you'd checked the return value of the open(), you'd catch that sort of thing.
Comment: error appears "readline() on closed filehandle $FH at ./rgex.pl line 9.". Any thoughts on that?
Comment: What version of Perl are you using?  It worked OK for me, cut'n'paste from the answer, with 5.13.4, 5.10.1, 5.8.8.  It failed with 5.6.2 - couldn't locate strict, which is slightly puzzling...OTOH, it was a PowerPC build of Perl running on my (Intel) Mac running Snow Leopard (10.6.4) and I've not used it in a long time.
Answer: I don't think grep is what you want really.
As you pointed out in brian's answer, the grep will only give you the headers and not the subsequent lines.
I think you need an array where each element is the header and the subsequent lines up to the next header.
Something like: -
#!/usr/bin/perl

use strict;
use warnings;

my $srce = "./default.log";
my $string1 = "Car LogFile Header";
my @logs;
my $log_entry;
open(my $FH, $srce) or die "Failed to open file $srce ($!)";

my $found = 0;
while(my $buf = <$FH>)
{
    if($buf =~ /$string1/)
    {
        if($found)
        {
            push @logs, $log_entry;
        }

        $found = 1;
        $log_entry = $buf;
    }
    else
    {
        $log_entry = $log_entry . $buf;
    }
}

if($found)
{
    push @logs, $log_entry;
}

close($FH);

print sort @logs;

i think it's what is being asked for.
Answer: Perl grep is not same as Unix grep command in that it does not print anything on the screen.
The general syntax is: grep Expr, LIST
Evaluates Expr for each element of LIST and returns a list consisting of those elements for which the expression evaluated to true.
In your case all the @buffer elements which have the vale of $string1 will be returned.
You can then print the @buffer array to actually see them.
Comment: He means you can't just define an array and expect a screen output from it. To get a screen output you have to `print` the array.
Answer: You just stored everything in an array instead of printing it out. It's also not necessary to keep the whole file in memory. You can read and print the match results line by line, like this:
my $srce = "./root/Desktop/logs/Default.log";
my $string1 = "Car LogFile Header";
open(FH, $srce);
while(my $line = <FH>) {
  if($line =~ m/$string1/) {
    print $line;
  }
}
close FH;

Comment: Still no result shown. It just skips to a blank line in the terminal.
Comment: No, try it with the logfile text you gave above. It will output all the "Car Logfile Header" lines it can find.
Answer: Hello I found a way to extract links from html file
!/usr/bin/perl -w
  2
  3 # Links graber 1.0
  2
  3 # Links graber 1.0
  4 #Author : peacengell
  5 #28.02.13
  6
  7 ####
  8
  9 my $file_links = "links.txt";
 10 my @line;
 11 my $line;
 12
 13
 14 open( FILE, $file_links ) or die "Can't find File";
 15
 16 while (<FILE>) {
 17 chomp;
 18 $line = $_ ;
 19
 20 @word = split (/\s+/, $line);
 21 @word  = grep(/href/, @word);
 22 foreach  $x (@word) {
 23
 24 if ( $x =~ m /ul.to/ ){
 25 $x=~ s/href="//g;
 26 $x=~s/"//g;
 27 print  "$x \n";
 28
 29
 30                         }
 31
 32                 }
 33
 34         }

you can use it and modify it please let me know if you modify it.


Booting into a Windows10 Virtual Machine using physical disc from Ubuntu Virtualbox host

Question: I've Ubuntu 14.04 Host machine with Virtualbox installed.
I've a SATA hard disc with windows 10 installed. I want to boot into the windows OS via a virtual machine created in my Ubuntu server.
parted -l output is as below:
Model: ATA ST1000LM024 HN-M (scsi)
Disk /dev/sdc: 1000GB
Sector size (logical/physical): 512B/4096B
Partition Table: gpt

Number  Start   End     Size    File system  Name                          Flags
 1      2097kB  1050MB  1048MB  ntfs         Basic data partition          hidden, diag
 2      1050MB  1322MB  273MB   fat32        EFI system partition          boot, hidden
 3      1322MB  2371MB  1049MB  fat32        Basic data partition          hidden
 4      2371MB  2505MB  134MB                Microsoft reserved partition  msftres
 5      2505MB  959GB   956GB   ntfs         Basic data partition          msftdata
 6      959GB   959GB   523MB   ntfs                                       hidden, diag
 7      959GB   986GB   26.8GB  ntfs         Basic data partition          msftdata
 8      986GB   1000GB  14.3GB  ntfs         Basic data partition          hidden, diag

I've created the rawvmdk file using the following:
VBoxManage internalcommands createrawvmdk -filename "/media/wde/VirtualBox VMs/Lenovo_Org_Win10.vmdk" -rawdisk /dev/sdc -partitions 2,4,5,7

As per the askubuntu question, I mounted the EFI partition and created the ISO image as follows
mount -t vfat /dev/sdc2 /media/winhd/
grub-mkrescue -o boot.iso winhd/*

EFI drive has following things:
root@p:/media/winhd# ls
BOOT  BOOTSECT.BAK  EFI  snapshots
root@p:/media/winhd# ls BOOT
boot.sdi
root@p:/media/winhd# ls EFI/
Boot  Microsoft  ubuntu
root@p:/media/winhd# ls EFI/Boot/
bkpbootx64.efi  bootx64.efi
root@p:/media/winhd# ls EFI/Boot/b
bkpbootx64.efi  bootx64.efi
root@p:/media/winhd# ls EFI/Microsoft/
Boot  Recovery
root@p:/media/winhd# ls snapshots/
control_{00000000-0000-0000-0000-000000000000}.dat  layout_{00000000-0000-0000-0000-000000000000}.dat  snapshot_{00000000-0000-0000-0000-000000000000}.dat
root@phanuis1:/media/winhd#

I added the ISO image in CD of the VM, added vmdk file as the harddisc, and when tried to boot, I am getting a screen with following message:"Minimal Bash like line editing supported..." and grub command prompt is displayed!
Answer: I don't know why that happens, but you should be able to boot Windows by running these commands in order:
        chainloader (hd0,2)/efi/Microsoft/Boot/bootmgfw.efi
        boot

(hd0,2) here is the refferer to the EFI partition
Also make sure to enable EFI boot, but from your Question I can see, that you probably do.
Comment: NOTE: this won't work, if you have the efi partition not on the same logical device in the vm the boot WILL fail.


How to share protocols between Clojure & ClojureScript

Question: I have a protocol in a crossover namespace:
(ns xxx.shared.interfaces)

(defprotocol ITimer
  (seconds [timer] "Return time in seconds since timer began"))

I have an implementation for Clojure:
(ns xxx.time
  (:require [xxx.shared.interfaces :refer [ITimer]]))

(defrecord Timer [start-nanos]
  ITimer
  (seconds [timer] (double (/ (- (System/nanoTime) (:start-nanos timer))
                              1000000000))))

The problem is that when I use this code in some Clojure code, having required the xxx.time namespace with :refer :all it complains it can't find seconds:
Unable to resolve symbol: seconds in this context

First of all, is it possible to share protocols in this way?
Secondly, any idea how I can make this work?
Thirdly, is this actually a good way to go about this kind of code sharing?  Ideally I'd like to share the record too, but it relies on Java code, so I'd need to break that out into a function.  Would that be a better way to go about this?
Thanks!
Answer: seconds is defined in xxx.shared.interfaces, so that's what you need to :require / :use to be able to call it:
(ns foo
  (:require [xxx.shared.interfaces :refer [seconds]]))

;; (seconds ...) will now work

To elaborate, a defprotocol expression creates a Var holding the protocol, an underlying JVM interfaces on the JVM side (no counterpart to this on the ClojureScript side) and a Var for each of the protocol methods. The protocol methods can then be called through those Vars just like any other Clojure function.
When you implement a protocol for a record / type, as you do in your xxx.time namespace, you don't even need to pull in those Vars if you don't actually call the methods (a separate issue from providing implementations). Similarly, a namespace which needs to call the protocol methods, but doesn't much care about the particular types of objects it calls them on, would only need to pull in the protocol-defining namespace and use the relevant Vars and would not need to :require any implementing namespaces.
Comment: As for the code sharing questions, I'd say it's fine to share whatever works as shared code and factoring out platform-specific implementations of protocol methods is certainly a valid approach to making more code shareable. Whether it's worth it would probably depend on how much repetition is actually avoided. In any case, as explained above, the original problem is unrelated to sharing.


debugging javascript error in ie7?

Question: All I get is this:
An error has occurred in the script on this page
line: 31
char: 5
error: expected identifier, string or number
code: 0
url: http://example.com

It's difficult to find that line since I have several external and internal scripts.
How can I debug this? (By the way, the scripts have no errors in chrome or firefox or ie8+)
Comment: Probably a dangling comma.  It's always a dangling comma.
Comment: Add line 31 into your answer from the page itself. Doesn't sound as though its coming from an external file as IE normally tells you it's a problem with an external file.
Answer: You can download IETester which lets you use various versions of IE (6-8) and has built-in developer tools.  They're not spectacular, but they're better than the nothing that old versions of IE provide.
Comment: His question is "How do I debug this?"  My answer is a suggestion for a tool to use to debug it.  I think it should be an answer, not a comment.
Answer: If it says it's on the page, then it means the page itself. If it was in an external file, it would indicate that the error occured in something.js.
Open up your webpage, right click on the page and select "View Source". Go to line 31 and try and see what's wrong with it.
Answer: Try debugging it with IE8's Developer Tools (press F12). You should be able to step through the JS code (from all your scripts) to find out what is wrong with line 31 / char 5.
Answer: You can also enable debugging for IE at
(Tools -> Options -> (uncheck) Disable script debugging (Internet Explorer).

After you disable it, IE will prompt you to debug when error occurs. Then you can debug with VS or MS script Editor.
Answer: Use Firefox with Firebug. Look at every external script around the line number mentioned in the error dialog. Trailing commas every time!
Answer: I got the same issue when try to to figure out what 's wrong with the code on IE7, after spending hours research and trying many different solutions, finally, the following two bars are great tools for me:
1) http://www.debugbar.com/
provide a convenience UI to with feature like source, style, DOM, Script, HTML check.
2) http://www.my-debugbar.com/wiki/CompanionJS/Installing
The main advantage of this is providing a console for IE6 or IE7, so you can see what are the error (in the console log)

Note:
they are both free
screen shot of both two toolbars

debugging javascript error in ie7?


How to edit /etc/hosts file

Question: How to you edit the /etc/hosts file? My father put every video site on the internet on and he won't tell me how to get rid of it. I need an answer because tinypic and youtube are on it!
Answer: You need open the file as root:
Open the terminal CTRL + ALT + T.
sudo nano /etc/hosts (You need enter your user password)
after, it will open the file to edit, use CTRL + X to close and save the file.
Good luck!
Answer: Open the terminal by pressing CTRL + ALT + T.
Get the  info you need your going to want to copy the commands output.
neil@ASUS:~$ sudo cat /etc/hosts | grep 127.0.0.1

Copy the outputted code.
127.0.0.1   localhost
127.0.0.1   ASUS

Then type in terminal
sudo rm /etc/hosts

then type in
sudo nano /etc/hosts

Press CTRL  + shift + V
Then your hosts file shoud look like this.
127.0.0.1       localhost
127.0.0.1       ASUS

and then press Ctrl + X to save
That should restore what your father did. unless he deleted 127.0.0.1 from the host file.
Comment: Yes, that makes sense. Copying things from a file and then inserting it in the same file is really useful...
Comment: @wie5Ooma   I edited my post. just released my mistake.

How to edit /etc/hosts file


Meteor helper of template not firing when data changes?

Question: I have the following on my client side:
Template.cellular.helpers({
    getCells: function() {
        console.log("getting cell list");
        things = cellItems.find({owner: Meteor.userId(), FileId: "someId"});
        console.log(things);
        return things;
    }
});

<template name="cellular">

            {{#each getCells}}

                            {{description}}

                            {{vals}}

                            {{formula}}

            {{/each}}

</template>

When I insert the following, it does not seem to fire the helper showing the console statement but I see flicker of the template being updated and then removed. What is happening? How can i correct it?
{owner: Meteor.userId(), FileId: "someId", description: "something", vals: "0", formula: "something else"}

Answer: You are adding a document with FileId: "someId" but your helper is doing a find() on dynaFileId: "someId" therefore the document you just inserted is not included in the cursor.
Comment: If that's not the problem then please include your *publish* and *subscribe* code. It's likely that your publication excludes the document you are inserting.
Comment: Are you still using autopublish?
Comment: Yes, you need to publish the *cellItems* collection on the server and subscribe to it on the client. To verify first, do `meteor add autopublish` and see if your code behaves as expected.
Comment: oops. i just edited my code and forgot to change the dynaFileId to FileId before posting here. i will edit my question...
Comment: `cellItems.allow({'insert': function (userId,doc) { return true; }, 'update': function (userId,doc) {return true; }});` is the server code. `cellItems = new Mongo.Collection("cells");` is the common code in lib. I am a newbie and not sure i am doing it right.
Comment: When i use `meteor remove autopublish` it says autopublish is not in this project. Do i have to use pub-sub to get data from server? Cant i query the common Collection cellItems to insert() and then find() data?


Add more value to dictionary python 3

Question: how do you add value to a key without overwriting the first value? Here is an example of my code:
def course_rolls(records):
    """Maps course code to the student ID"""
    course_to_id_dict = {}
    for record in records:
        course = record[0][0]
        student_id = record[1][0]
        course_to_id_dict[course] = {student_id}
    print(course_to_id_dict)
    return course_to_id_dict
records = [(('MTH001', 'Mathematics 1'),
            (2763358, 'Cooper', 'Porter')),
           (('EMT003', 'Mathematical Modelling and Computation'),
            (2788579, 'Mandi', 'Stachowiak'))]
rolls = course_rolls(records)
expected = {'MTH001': {2763358}, 'EMT003': {2788579}}
print(rolls==expected)

The output is True
Let's say if a student ID maps with the same key and I wanted the output to be the expected:
rolls = course_rolls(records)
records = [(('MTH001', 'Mathematics 1'),
            (2763358, 'Cooper', 'Porter')),
           (('EMT003', 'Mathematical Modelling and Computation'),
            (2788579, 'Mandi', 'Stachowiak')),
           (('MTH001', 'Mathematics 1'),
            (2763567, 'New', 'Value'))]
rolls = course_rolls(records)
expected = {'MTH001': {2763358,2763567}, 'EMT003': {2788579}}
print(rolls==expected)

Answer: You need to either detect that the key is already present in course_to_dict_id and add to that set, or use dict.setdefault() to give you an empty set whenever you try to retrieve a key that isn't set yet.
The latter is more concise:
for record in records:
    course = record[0][0]
    student_id = record[1][0]
    course_to_id_dict.setdefault(course, set()).add(student_id)

This produces {'MTH001': {2763358, 2763567}, 'EMT003': {2788579}} as the output (each value in the dictionary a set with 1 or more integers).
Comment: but how come if I wrote course_to_id_dict[course].append({student_id}) would not work
Comment: @AsyrawiAbdullahZawawi: `course_to_id_dict[course]` is not a list, it is a set object (provided the object exists). `course_to_id_dict[course].add(student_id)` would work, provided you first test if `course` is an existing key.

Add more value to dictionary python 3