问:
Print the cards that I used after I typed yes to play again
I want this game to start each hand with the cards left over from the previous hand.  Instead, it begins with a complete, newly-shuffled deck.  How can I fix it to just continue?
I updated the code based in your advice but it doesnt display my show card thanks a lot</p>

```<code>import random, sys

suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}

class Card:

    def __init__(self, suit, pip):
        self.suit = suit
        self.pip = pip
        self.value = pipValues.get(pip)

    def __str__(self):
        thisCard = ""
        thisCard += str(self.pip)
        thisCard += str(self.suit)
        return (thisCard)

    def __repr__(self):
        thisCard = ""
        thisCard += str(self.pip)
        thisCard += str(self.suit)
        return (thisCard)

class Player:

    def __init__(self):
        self.hand = []
        self.handTotal = 0

    def __str__(self):
        printHand = ""
        for i in self.hand:
            printHand += str(i) + " "
        return (printHand)

    def __repr__(self):
        printHand = ""
        for i in self.hand:
            printHand += str(i) + " "
        return (printHand)

class Deck:

    def __init__(self):
        self.cardList = []
        #for each suit take every card
        for i in range(len(suits)):
            for j in range(len(pip)):
                self.cardList.append(Card(suits[i], pip[j]))

    def shuffle(self):
        random. shuffle (self.cardList)

    def dealOne(self, player):
        (player.hand).append(self.cardList[0])

        player.handTotal += self.cardList[0].value

        del self.cardList[0]
        print self.cardList
        return self.cardList

    def __str__(self):
        printString = ""
        for i in range(len(self.cardList)):
            if i % 13 == 0:
                printString += "\n \t"
                printString += str(self.cardList[i]) + " "
            else:
                printString += str(self.cardList[i]) + " "
        printString += "\n"

        return printString

def showHands(player, opponent):
    print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
    print ('You show ' + str(player.hand[0]) +str(player.hand[0] ))

def playerTurn(deck, player, other):
    #First, check scores to see if either player has a blackjack:

    if player.handTotal == 21 or other.handTotal == 21:
        if other.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Dealer has " + str(other) + "for a total of 21")
            print ("Dealer has a Blackjack! Dealer wins!")
            print ("Thanks for playing. Come back again soon! ")
            message()
        else:
            print ("You hold " + str(player) + "for a total of 21")
            print ("You have a Blackjack! You win!")

            print ("Thanks for playing. Come back again soon! ")
            message()

    hitOrStand = 0
    aces = False

    #IF TWO ACES
    if player.hand[0].pip == "A" and player.hand[1].pip == "A":
        player.hand[0].pipValue = 1

    if player.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Blackjack! You win!")
            print ("Thanks for playing. Come back soon!")
            print()
            message()
    while hitOrStand != 2:
        #check for aces
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True

        print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
        print()
        hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
        while hitOrStand != 1 and hitOrStand != 2:
            try:
                hitOrStand = int(hitOrStand)
                break
            except ValueError:
                print ("Enter a valid integer \n")
            hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
        print()

        if hitOrStand == 1:
            print('Card dealt:  ' + str(deck.cardList[0]))
            print()
            deck.dealOne(player)
            #check if an ace was drawn
            for i in player.hand:
                if i.pip == "A" and i.value == 11:
                    aces = True

        if player.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Blackjack!! You Win!")
            print()
            print ("Thanks for playing. Come back soon!")
            message()

        if player.handTotal > 21:
            #check for aces
            if aces:
                print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Over 21. Value of ace changed to 1")
                #chanlge value of ace and hand
                player.handTotal = player.handTotal - 10
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        i.value = 1
                #check for other standard aces
                aces = False
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        aces = True
            else:
                print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("You Bust! Dealer Wins!")
                #exit, since you're a loser
                print ("Thanks for Playing! Come Back Soon!")
                print()
                raise SystemExit

        if hitOrStand == 2:
            print ('You stand at: ' + str(player.handTotal))
            print()

    print ("Now Dealer's Turn")
    print ()
def message():
        again = raw_input("Do you want to play again? (Y/N) : ")
        if(again == "Y" or again == "y"):
            main()
        else:
            print "\n\n-------Thank you for playing!--------\n\n"
            exit()

def opponentTurn(deck, player, other):
    if other.handTotal == 21:
        raise SystemExit
    aces = False
    hitOrStand = 0

    #IF TWO ACES
    if player.hand[0].pip == "A" and player.hand[1].pip == "A":
        player.hand[0].pipValue = 1

    while hitOrStand != 2:
        #check for aces
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True

        print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
        print()
        #if blackjack
        if player.handTotal == 21:
            print ("Dealer has a BlackJack! Dealer Wins!")
            break
        if player.handTotal <21 and other.handTotal == 21:
            print ("Dealer's hand is " + str(player.handTotal) + ". You have a Blackjack! Congratulations! You win! ")
            break

        if player.handTotal < other.handTotal:
            hitOrStand = 1
        if player.handTotal >= other.handTotal:
            hitOrStand = 2

        if hitOrStand == 1:
            print("Dealer hits. " + 'Card dealt:  ' + str(deck.cardList[0]))
            deck.dealOne(player)
            #check if an ace was drawn
            for i in player.hand:
                if i.pip == "A" and i.value == 11:
                    aces = True

        if player.handTotal > 21:
            #check for aces
            if aces:
                print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Over 21. Value of ace changed to 1")
                #chanlge value of ace and hand
                player.handTotal = player.handTotal - 10
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        i.value = 1

                #check for other standard aces
                aces = False
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        aces = True
            else:
                print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Dealer Busts! You Win!")
                message()

        if hitOrStand == 2:
            print ("Dealer stands at " + str(player.handTotal))
            print ("Your score is " + str(other.handTotal))
            print ("Dealer Wins!")
            message()
#who won
def main():
    cardDeck = Deck()
    print ('Initial Deck: ')
    print(cardDeck)

    cardDeck.shuffle()
    print ('Shuffled Deck: ')
    print(cardDeck)

    keep_playing = True
    while keep_playing:

        player = Player()
        opponent = Player()

        #give each player 2 cards, alternating
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)

        print ('Deck after giving 2 cards each')
        print (cardDeck)

        #show 1 faceup card for each player
        showHands(player,opponent)

        #start playing
        playerTurn(cardDeck,player, opponent)
        opponentTurn(cardDeck, opponent, player)

        again = raw_input("Do you want to play again? (Y/N) : ")
        keep_playing = again in "Yy"

    # Reach here after dropping out of the while loop
    print "\n\n-------Thank you for playing!--------\n\n"
main()
</code>```

答:
See the repl.it for a complete solution:

There are a lot of issues, here are a few of overarching themes:

If you're having to repeat yourself, you're doing it wrong:

```<code>aces = False
#IF TWO ACES
if player.hand[0].pip == "A" and player.hand[1].pip == "A":
    player.hand[0].pipValue = 1
</code>```

```<code>#check for aces
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            aces = True
</code>```

```<code>#check if an ace was drawn
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True
</code>```

```<code>#check for aces
if aces:
    print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
    print ("Over 21. Value of ace changed to 1")
    #chanlge value of ace and hand
    player.handTotal = player.handTotal - 10
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            i.value = 1
    #check for other standard aces
    aces = False
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            aces = True
</code>```

Each of those is used twice... I replaced it by letting my players hand decide it's own value:

```<code>@property
def handTotal(self):
  while sum(card.value for card in self.hand) > 21 and \
        any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
    for card in self.hand:
      if card.pip == 'Ace' and card.value == 11:
        card.value = 1
        break
  return sum(card.value for card in self.hand)
</code>```

The @property decorator forces it to recalculate every time someone asks for the handTotal.

Telling main you want to keep playing

You need to return a value all the way back to main, in some way. Because you already have some global state variables, I added playing = True, then:

```<code>def message():
    global playing
    again = input("Do you want to play again? (Y/N) : ")
    if again.lower() == "n":
        print("\n\n-------Thank you for playing!--------\n\n")
        playing = False
    return True # Tells `turn()` the game is over
</code>```

Body:
I want this game to start each hand with the cards left over from the previous hand.  Instead, it begins with a complete, newly-shuffled deck.  How can I fix it to just continue?
I updated the code based in your advice but it doesnt display my show card thanks a lot

import random, sys

suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}

class Card:

    def __init__(self, suit, pip):
        self.suit = suit
        self.pip = pip
        self.value = pipValues.get(pip)

    def __str__(self):
        thisCard = ""
        thisCard += str(self.pip)
        thisCard += str(self.suit)
        return (thisCard)

    def __repr__(self):
        thisCard = ""
        thisCard += str(self.pip)
        thisCard += str(self.suit)
        return (thisCard)

class Player:

    def __init__(self):
        self.hand = []
        self.handTotal = 0

    def __str__(self):
        printHand = ""
        for i in self.hand:
            printHand += str(i) + " "
        return (printHand)

    def __repr__(self):
        printHand = ""
        for i in self.hand:
            printHand += str(i) + " "
        return (printHand)

class Deck:

    def __init__(self):
        self.cardList = []
        #for each suit take every card
        for i in range(len(suits)):
            for j in range(len(pip)):
                self.cardList.append(Card(suits[i], pip[j]))

    def shuffle(self):
        random. shuffle (self.cardList)

    def dealOne(self, player):
        (player.hand).append(self.cardList[0])

        player.handTotal += self.cardList[0].value

        del self.cardList[0]
        print self.cardList
        return self.cardList

    def __str__(self):
        printString = ""
        for i in range(len(self.cardList)):
            if i % 13 == 0:
                printString += "\n \t"
                printString += str(self.cardList[i]) + " "
            else:
                printString += str(self.cardList[i]) + " "
        printString += "\n"

        return printString

def showHands(player, opponent):
    print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
    print ('You show ' + str(player.hand[0]) +str(player.hand[0] ))

def playerTurn(deck, player, other):
    #First, check scores to see if either player has a blackjack:

    if player.handTotal == 21 or other.handTotal == 21:
        if other.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Dealer has " + str(other) + "for a total of 21")
            print ("Dealer has a Blackjack! Dealer wins!")
            print ("Thanks for playing. Come back again soon! ")
            message()
        else:
            print ("You hold " + str(player) + "for a total of 21")
            print ("You have a Blackjack! You win!")

            print ("Thanks for playing. Come back again soon! ")
            message()

    hitOrStand = 0
    aces = False

    #IF TWO ACES
    if player.hand[0].pip == "A" and player.hand[1].pip == "A":
        player.hand[0].pipValue = 1

    if player.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Blackjack! You win!")
            print ("Thanks for playing. Come back soon!")
            print()
            message()
    while hitOrStand != 2:
        #check for aces
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True

        print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
        print()
        hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
        while hitOrStand != 1 and hitOrStand != 2:
            try:
                hitOrStand = int(hitOrStand)
                break
            except ValueError:
                print ("Enter a valid integer \n")
            hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
        print()

        if hitOrStand == 1:
            print('Card dealt:  ' + str(deck.cardList[0]))
            print()
            deck.dealOne(player)
            #check if an ace was drawn
            for i in player.hand:
                if i.pip == "A" and i.value == 11:
                    aces = True

        if player.handTotal == 21:
            print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
            print ("Blackjack!! You Win!")
            print()
            print ("Thanks for playing. Come back soon!")
            message()

        if player.handTotal > 21:
            #check for aces
            if aces:
                print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Over 21. Value of ace changed to 1")
                #chanlge value of ace and hand
                player.handTotal = player.handTotal - 10
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        i.value = 1
                #check for other standard aces
                aces = False
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        aces = True
            else:
                print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("You Bust! Dealer Wins!")
                #exit, since you're a loser
                print ("Thanks for Playing! Come Back Soon!")
                print()
                raise SystemExit

        if hitOrStand == 2:
            print ('You stand at: ' + str(player.handTotal))
            print()

    print ("Now Dealer's Turn")
    print ()
def message():
        again = raw_input("Do you want to play again? (Y/N) : ")
        if(again == "Y" or again == "y"):
            main()
        else:
            print "\n\n-------Thank you for playing!--------\n\n"
            exit()

def opponentTurn(deck, player, other):
    if other.handTotal == 21:
        raise SystemExit
    aces = False
    hitOrStand = 0

    #IF TWO ACES
    if player.hand[0].pip == "A" and player.hand[1].pip == "A":
        player.hand[0].pipValue = 1

    while hitOrStand != 2:
        #check for aces
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True

        print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
        print()
        #if blackjack
        if player.handTotal == 21:
            print ("Dealer has a BlackJack! Dealer Wins!")
            break
        if player.handTotal <21 and other.handTotal == 21:
            print ("Dealer's hand is " + str(player.handTotal) + ". You have a Blackjack! Congratulations! You win! ")
            break

        if player.handTotal < other.handTotal:
            hitOrStand = 1
        if player.handTotal >= other.handTotal:
            hitOrStand = 2

        if hitOrStand == 1:
            print("Dealer hits. " + 'Card dealt:  ' + str(deck.cardList[0]))
            deck.dealOne(player)
            #check if an ace was drawn
            for i in player.hand:
                if i.pip == "A" and i.value == 11:
                    aces = True

        if player.handTotal > 21:
            #check for aces
            if aces:
                print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Over 21. Value of ace changed to 1")
                #chanlge value of ace and hand
                player.handTotal = player.handTotal - 10
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        i.value = 1

                #check for other standard aces
                aces = False
                for i in player.hand:
                    if i.pip == "A" and i.value == 11:
                        aces = True
            else:
                print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
                print ("Dealer Busts! You Win!")
                message()

        if hitOrStand == 2:
            print ("Dealer stands at " + str(player.handTotal))
            print ("Your score is " + str(other.handTotal))
            print ("Dealer Wins!")
            message()
#who won
def main():
    cardDeck = Deck()
    print ('Initial Deck: ')
    print(cardDeck)

    cardDeck.shuffle()
    print ('Shuffled Deck: ')
    print(cardDeck)

    keep_playing = True
    while keep_playing:

        player = Player()
        opponent = Player()

        #give each player 2 cards, alternating
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)
        cardDeck.dealOne(player)
        cardDeck.dealOne(opponent)

        print ('Deck after giving 2 cards each')
        print (cardDeck)

        #show 1 faceup card for each player
        showHands(player,opponent)

        #start playing
        playerTurn(cardDeck,player, opponent)
        opponentTurn(cardDeck, opponent, player)

        again = raw_input("Do you want to play again? (Y/N) : ")
        keep_playing = again in "Yy"

    # Reach here after dropping out of the while loop
    print "\n\n-------Thank you for playing!--------\n\n"
main()

Body:
See the repl.it for a complete solution:

There are a lot of issues, here are a few of overarching themes:

If you're having to repeat yourself, you're doing it wrong:

aces = False
#IF TWO ACES
if player.hand[0].pip == "A" and player.hand[1].pip == "A":
    player.hand[0].pipValue = 1

#check for aces
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            aces = True

#check if an ace was drawn
        for i in player.hand:
            if i.pip == "A" and i.value == 11:
                aces = True

#check for aces
if aces:
    print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
    print ("Over 21. Value of ace changed to 1")
    #chanlge value of ace and hand
    player.handTotal = player.handTotal - 10
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            i.value = 1
    #check for other standard aces
    aces = False
    for i in player.hand:
        if i.pip == "A" and i.value == 11:
            aces = True

Each of those is used twice... I replaced it by letting my players hand decide it's own value:

@property
def handTotal(self):
  while sum(card.value for card in self.hand) > 21 and \
        any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
    for card in self.hand:
      if card.pip == 'Ace' and card.value == 11:
        card.value = 1
        break
  return sum(card.value for card in self.hand)

The @property decorator forces it to recalculate every time someone asks for the handTotal.

Telling main you want to keep playing

You need to return a value all the way back to main, in some way. Because you already have some global state variables, I added playing = True, then:

def message():
    global playing
    again = input("Do you want to play again? (Y/N) : ")
    if again.lower() == "n":
        print("\n\n-------Thank you for playing!--------\n\n")
        playing = False
    return True # Tells `turn()` the game is over


来源: stackexchange

问:
Stored procedure times out when ran from code, but not from query tool
I am trying to figure out why a stored procedure call takes seconds in a SQL server express query window, but when I run call the stored procedure in code the query TIMES OUT.  We are using sql server 2008.  I know it is hard to say exactly what is going on without seeing the stored procedure.  I'm just hoping this is a known issue.  Any guidance is much appreciated.

SQL query that calls "STORED_PROCEDURE_X" and runs in 2 seconds in SQL server express query window:

```<code>EXEC STORED_PROCEDURE_X '07/01/2010', '07/31/2010', 0, '', 'true','', 'Top 20'
</code>```

Code that calls "STORED_PROCEDURE_X" and TIMES OUT:

```<code>SqlConnection connSQL = null;
SqlCommand sqlCmd = null;
SqlDataAdapter sqlDataAdpater = null;
DataTable returnData = null;

try
{
    returnData = new DataTable();
    connSQL = new SqlConnection(sqlConnection);
    sqlCmd = new SqlCommand("STORED_PROC_X", connSQL);
    if (connSQL.State == ConnectionState.Closed)
    {
        connSQL.Open();
    }
    sqlCmd.CommandType = CommandType.StoredProcedure;
    sqlCmd.CommandTimeout = 600;
    sqlCmd.Parameters.Add("@StartDate", SqlDbType.NVarChar).Value = "07/01/2010";
    sqlCmd.Parameters.Add("@EndDate", SqlDbType.NVarChar).Value = "07/31/2010";

    sqlCmd.Parameters.Add("@AuditType", SqlDbType.Int).Value = "0";

    sqlCmd.Parameters.Add("@SortBy", SqlDbType.NVarChar).Value = "";

    sqlCmd.Parameters.Add("@IsClaimDepartment", SqlDbType.NVarChar).Value = "true";
    sqlCmd.Parameters.Add("@IdsList", SqlDbType.NVarChar).Value = "";
    sqlCmd.Parameters.Add("@ReportType", SqlDbType.NVarChar).Value = "Top 20";
    sqlDataAdpater = new SqlDataAdapter(sqlCmd);
    sqlDataAdpater.Fill(returnData);
    if (connSQL.State == ConnectionState.Open)
    {
        connSQL.Close();
    }
    return returnData;
}
catch (Exception ex)
{
    LogErrorMessages("ExecuteStoredProcedure", ex.Message);
    throw ex;
}
</code>```

Exception Received:

```<code>System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
</code>```

答:
I had a similar issue with stored procedures running slower than the same query in the query window.
I had tried everything from coding for parameter sniffing (local variables), removing clustered indexes and using only non-clustered, etc. It still took 22 seconds minuimum to retrieve a varchar field, using a nvarchar parameter.

I originally thought it was just the difference between nvarchar and varchar and changed the database field to nvarchar. I lost another full day, moving 50 million records to a new table and re-indexing. Still took over 22 seconds.

Finally, I changed any key fields in the tables from nvarchar to varchar, plus all the parameters and wow; back dowen to less than 1 second.

I strongly believe this is a bug in SQL Server, that has never got corrected. How can you run a query directly in the query window, or call sql from vb.net or c# code and get results in less than 1 second; then run the same query, using parameters, in a stored procedure and get such horrendus results?

Short answer: Stay away from nvarchar data types at all costs.

Also, learn to use the merge statement to move data into large tables to avoid timeouts.
Set recovery mode to simple, while running a large merge query; then put back to full recovery.

Boy, did I learn alot this week. Over 80 hours of education that I did not need.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to figure out why a stored procedure call takes seconds in a SQL server express query window, but when I run call the stored procedure in code the query TIMES OUT.  We are using sql server 2008.  I know it is hard to say exactly what is going on without seeing the stored procedure.  I'm just hoping this is a known issue.  Any guidance is much appreciated.

SQL query that calls "STORED_PROCEDURE_X" and runs in 2 seconds in SQL server express query window:

EXEC STORED_PROCEDURE_X '07/01/2010', '07/31/2010', 0, '', 'true','', 'Top 20'

Code that calls "STORED_PROCEDURE_X" and TIMES OUT:

SqlConnection connSQL = null;
SqlCommand sqlCmd = null;
SqlDataAdapter sqlDataAdpater = null;
DataTable returnData = null;

try
{
    returnData = new DataTable();
    connSQL = new SqlConnection(sqlConnection);
    sqlCmd = new SqlCommand("STORED_PROC_X", connSQL);
    if (connSQL.State == ConnectionState.Closed)
    {
        connSQL.Open();
    }
    sqlCmd.CommandType = CommandType.StoredProcedure;
    sqlCmd.CommandTimeout = 600;
    sqlCmd.Parameters.Add("@StartDate", SqlDbType.NVarChar).Value = "07/01/2010";
    sqlCmd.Parameters.Add("@EndDate", SqlDbType.NVarChar).Value = "07/31/2010";

    sqlCmd.Parameters.Add("@AuditType", SqlDbType.Int).Value = "0";

    sqlCmd.Parameters.Add("@SortBy", SqlDbType.NVarChar).Value = "";

    sqlCmd.Parameters.Add("@IsClaimDepartment", SqlDbType.NVarChar).Value = "true";
    sqlCmd.Parameters.Add("@IdsList", SqlDbType.NVarChar).Value = "";
    sqlCmd.Parameters.Add("@ReportType", SqlDbType.NVarChar).Value = "Top 20";
    sqlDataAdpater = new SqlDataAdapter(sqlCmd);
    sqlDataAdpater.Fill(returnData);
    if (connSQL.State == ConnectionState.Open)
    {
        connSQL.Close();
    }
    return returnData;
}
catch (Exception ex)
{
    LogErrorMessages("ExecuteStoredProcedure", ex.Message);
    throw ex;
}

Exception Received:

System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

ContentLicense: CC BY-SA 4.0


问:
Docker forever in "Docker is starting.." at Windows task
I have installed a Docker stable version, and it took forever to start.
Until now I have not seen the notification showing Docker is running.
I can only see the Docker icon at the taskbar, showing Docker is starting.

I am running on Windows 10 Pro, Intel Core 2 Duo E8500, supporting virtualization.

答:
UPDATE

Looks like in Docker for Windows version: 17.09.0-ce-win33 (13620) they fixed the problem

This is an annoying problem that docker for Windows has. The latests versions have minimized it a lot but it still happens.

Check if docker for Windows will start when windows starts (this is the default behavior) if not check it.

Shutdown the machine. No restart. Shutdown.

Everytime you find this problem just shutdown the machine. The next time Windows boot docker will start very fast.

I know it looks esoteric but it works.


问:
Function with more choices
I created a simple key stroke counter code that prints number of entered letters. However I am trying to figure out how to make a function so it recognizes 1 letter from 2 letters (singular and plural). I would like to add also 'stroke' in my code, and when the keyboard key is entered only once Id like it to print "You entered 1 stroke" instead of "You entered 1 strokes.".

I tried something but cant really move forward:

```<code>print('Start typing: ')
count = raw_input()
print('You entered:'), len(count), ('strokes')
</code>```

答:
Instead of using multiple arguments to print, you can also use string formatting:

```<code>print "You entered {} stroke{}".format(len(count), "s"*(len(count)!=1))
</code>```

Admittedly, the last part is a bit exotic, but you can of course also do

```<code>print "You entered {} stroke{}".format(len(count), "s" if len(count) != 1 else "")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Function with more choices

Body:
I created a simple key stroke counter code that prints number of entered letters. However I am trying to figure out how to make a function so it recognizes 1 letter from 2 letters (singular and plural). I would like to add also 'stroke' in my code, and when the keyboard key is entered only once Id like it to print "You entered 1 stroke" instead of "You entered 1 strokes.".

I tried something but cant really move forward:

print('Start typing: ')
count = raw_input()
print('You entered:'), len(count), ('strokes')

Body:
Instead of using multiple arguments to print, you can also use string formatting:

print "You entered {} stroke{}".format(len(count), "s"*(len(count)!=1))

Admittedly, the last part is a bit exotic, but you can of course also do

print "You entered {} stroke{}".format(len(count), "s" if len(count) != 1 else "")


问:
CIDetector and UIImagePickerController
I'm trying to implement the built-in iOS 5 face detection API. I'm using an instance of UIImagePickerController to allow the user to take a photo and then I'm trying to use CIDetector to detect facial features. Unfortunately, featuresInImage always returns an array of size 0.

Here's the code:

```<code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage* picture = [info objectForKey:UIImagePickerControllerOriginalImage];

NSNumber *orientation = [NSNumber numberWithInt:
                         [picture imageOrientation]];
NSDictionary *imageOptions =
[NSDictionary dictionaryWithObject:orientation
                            forKey:CIDetectorImageOrientation];

CIImage *ciimage = [CIImage imageWithCGImage:[picture CGImage]
                                     options:imageOptions];

NSDictionary *detectorOptions =
[NSDictionary dictionaryWithObject:CIDetectorAccuracyLow
                            forKey:CIDetectorAccuracy];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                          context:nil
                                          options:detectorOptions];

NSArray *features = [detector featuresInImage:ciimage];
NSLog(@"Feature size: %d", features.count);
}
</code>```

This always returns 0 features. However, if I use a UIImage from a file built-in to the application, the face detection works great.

I'm using code from this Pragmatic Bookshelf article.

For what it's worth, I think the error is when I convert the UIImage from the camera to a CIImage, but it could be anything.

答:
Swift 3 Version

```<code>var exifOrientation : Int
switch (inputImage.imageOrientation)
{
case UIImageOrientation.up:
    exifOrientation = 1;
case UIImageOrientation.down:
    exifOrientation = 3;
case UIImageOrientation.left:
    exifOrientation = 8;
case UIImageOrientation.right:
    exifOrientation = 6;
case UIImageOrientation.upMirrored:
    exifOrientation = 2;
case UIImageOrientation.downMirrored:
    exifOrientation = 4;
case UIImageOrientation.leftMirrored:
    exifOrientation = 5;
case UIImageOrientation.rightMirrored:
    exifOrientation = 7;
}

let ciImage = CIImage(cgImage: inputImage.cgImage!)
let options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: options)!
let faces = faceDetector.features(in: ciImage, options:["CIDetectorImageOrientation":exifOrientation])
</code>```

Title: CIDetector and UIImagePickerController

Body:
I'm trying to implement the built-in iOS 5 face detection API. I'm using an instance of UIImagePickerController to allow the user to take a photo and then I'm trying to use CIDetector to detect facial features. Unfortunately, featuresInImage always returns an array of size 0.

Here's the code:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage* picture = [info objectForKey:UIImagePickerControllerOriginalImage];

NSNumber *orientation = [NSNumber numberWithInt:
                         [picture imageOrientation]];
NSDictionary *imageOptions =
[NSDictionary dictionaryWithObject:orientation
                            forKey:CIDetectorImageOrientation];

CIImage *ciimage = [CIImage imageWithCGImage:[picture CGImage]
                                     options:imageOptions];

NSDictionary *detectorOptions =
[NSDictionary dictionaryWithObject:CIDetectorAccuracyLow
                            forKey:CIDetectorAccuracy];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                          context:nil
                                          options:detectorOptions];

NSArray *features = [detector featuresInImage:ciimage];
NSLog(@"Feature size: %d", features.count);
}

This always returns 0 features. However, if I use a UIImage from a file built-in to the application, the face detection works great.

I'm using code from this Pragmatic Bookshelf article.

For what it's worth, I think the error is when I convert the UIImage from the camera to a CIImage, but it could be anything.

Body:
Swift 3 Version

var exifOrientation : Int
switch (inputImage.imageOrientation)
{
case UIImageOrientation.up:
    exifOrientation = 1;
case UIImageOrientation.down:
    exifOrientation = 3;
case UIImageOrientation.left:
    exifOrientation = 8;
case UIImageOrientation.right:
    exifOrientation = 6;
case UIImageOrientation.upMirrored:
    exifOrientation = 2;
case UIImageOrientation.downMirrored:
    exifOrientation = 4;
case UIImageOrientation.leftMirrored:
    exifOrientation = 5;
case UIImageOrientation.rightMirrored:
    exifOrientation = 7;
}

let ciImage = CIImage(cgImage: inputImage.cgImage!)
let options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: options)!
let faces = faceDetector.features(in: ciImage, options:["CIDetectorImageOrientation":exifOrientation])


问:
how do i get this cookie to expire after 14 days from today(which will be whenever the user generates)
```<code> function myCookieCreator(){
 document.cookie="myCoookie=isTrueSet; expires=Thu, 30 Mar 2017
 12:00:00 UTC";
 }
</code>```

Can I make it expire 14 days from the date of creation within the same line of code? This is how I am creating it.

答:
```<code>By Default, the cookie deleted when the browser is closed but its expiry date can be set to some other date like-:
</code>```

steps

Get the current date.
Add 14 days.
and place new varible in place of expire.

```<code>var newDate = new Date();
var dateAdd = newDate.setDate(today.getUTCDate()+14);
document.cookie = "expires=+dateAdd+";
</code>```

Body:
 function myCookieCreator(){
 document.cookie="myCoookie=isTrueSet; expires=Thu, 30 Mar 2017
 12:00:00 UTC";
 }

Can I make it expire 14 days from the date of creation within the same line of code? This is how I am creating it.

Body:
By Default, the cookie deleted when the browser is closed but its expiry date can be set to some other date like-:

steps

Get the current date.
Add 14 days.
and place new varible in place of expire.

var newDate = new Date();
var dateAdd = newDate.setDate(today.getUTCDate()+14);
document.cookie = "expires=+dateAdd+";


问:
Redirect unauthorized users asp net
I'm working on a simple website in asp.net.
I would like to restric access to the side, so that only users in a specific AD group is allowed. I have done that and it is working fine. But when a user that's not in the AD group tries to access the site, they are getting a login prompt. How do I redirect the unauthorized user to a custom page, instead of they getting the login prompt?

Below is my web.config. The lowest part of the code, is something i tried but did not work.

```<code><configuration>
<system.web>
  <compilation debug="true" targetFramework="4.0" />
  <authentication mode="Windows"/>
  <authorization>
    <allow roles="DOMAIN\GROUP"/>
    <deny users="*"/>
  </authorization>
</system.web>

<location path="AccessDenied.aspx">
<system.web>
<authorization>
  <allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>
</code>```

I have added this to the Global.asax.cs:

```<code>protected void Application_EndRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.Response.Status.StartsWith("401"))
            {
                HttpContext.Current.Response.ClearContent();
                Server.Execute("AccessDenied.aspx");
            }
}
</code>```

Any ideas ?

EDIT:
I tried some of the posted solutions, but they did not work.
But I got it working with this code:

```<code>void Application_EndRequest(object sender, System.EventArgs e)
    {
        if (((Response.StatusCode == 401)
        && (Request.IsAuthenticated == true)))
        {
            Response.ClearContent();
            Response.Redirect("~/AccessDenied.aspx");
        }
    }
}
</code>```

答:
I had more success with this:</p>

```<code>      // This is a workaround for the fact that we are not using MVC and its attributes
      // This is the situation where a user is logged in - but not authorized for this page
      void Application_EndRequest (object sender, System.EventArgs e)
      {
         if (((Response.StatusCode == 302) && (Request.IsAuthenticated == true)))
         {
            try
            {
               string sLoc = Response.Headers ["Location"];
               if (sLoc.Contains ("Login"))
               {
                  Response.ClearContent ();
                  Response.Redirect ("~/AccessDenied.aspx");
               }
            }
            catch
            {
            }
         }
      }
</code>```

Title: Redirect unauthorized users asp net

Body:
I'm working on a simple website in asp.net.
I would like to restric access to the side, so that only users in a specific AD group is allowed. I have done that and it is working fine. But when a user that's not in the AD group tries to access the site, they are getting a login prompt. How do I redirect the unauthorized user to a custom page, instead of they getting the login prompt?

Below is my web.config. The lowest part of the code, is something i tried but did not work.

<configuration>
<system.web>
  <compilation debug="true" targetFramework="4.0" />
  <authentication mode="Windows"/>
  <authorization>
    <allow roles="DOMAIN\GROUP"/>
    <deny users="*"/>
  </authorization>
</system.web>

<location path="AccessDenied.aspx">
<system.web>
<authorization>
  <allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>

I have added this to the Global.asax.cs:

protected void Application_EndRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.Response.Status.StartsWith("401"))
            {
                HttpContext.Current.Response.ClearContent();
                Server.Execute("AccessDenied.aspx");
            }
}

Any ideas ?

EDIT:
I tried some of the posted solutions, but they did not work.
But I got it working with this code:

void Application_EndRequest(object sender, System.EventArgs e)
    {
        if (((Response.StatusCode == 401)
        && (Request.IsAuthenticated == true)))
        {
            Response.ClearContent();
            Response.Redirect("~/AccessDenied.aspx");
        }
    }
}

Body:
I had more success with this:

      // This is a workaround for the fact that we are not using MVC and its attributes
      // This is the situation where a user is logged in - but not authorized for this page
      void Application_EndRequest (object sender, System.EventArgs e)
      {
         if (((Response.StatusCode == 302) && (Request.IsAuthenticated == true)))
         {
            try
            {
               string sLoc = Response.Headers ["Location"];
               if (sLoc.Contains ("Login"))
               {
                  Response.ClearContent ();
                  Response.Redirect ("~/AccessDenied.aspx");
               }
            }
            catch
            {
            }
         }
      }


问:
Taking address of temporary SDL_Rect
I am trying to make a simpler container for text in SDL by way of classes. The class is supposed to contain a pointer to an SDL_Texture and an SDL_Rect as well as some methods to get the information from the instances of the class. My problem arises when I try to blit the texture to the screen with the following function:

```<code>//Assume that renderer is already created
SDL_RenderCopy(renderer, texture.getTexture(), NULL, &texture.getRect());
</code>```

The compiler brings my attention to the fourth parameter and states the following:

```<code>error: taking address of temporary [-fpermissive]
</code>```

The code for my class is:

```<code>//Class
class Texture
{
    private:
        SDL_Texture* texture;
        SDL_Rect        rect;
    public:
        Texture(){/*Don't call any of the functions when initialized like this*/}
        Texture(SDL_Texture* texure)
        {
            this->texture = texture;
        }
        SDL_Texture* getTexture()
        {
            return texture;
        }
        SDL_Rect getRect()
        {
            return rect;
        }
        void setRect(int posX, int posY, int scale, SDL_Texture* texture)
        {
            int textW = 0;
            int textH = 0;
            SDL_QueryTexture(texture, NULL, NULL, &textW, &textH);
            this->rect = {posX,posY,textW*scale, textH*scale};
        }
};
</code>```

The code for my main program is:

```<code>//Main Program
TTF_Font* font = TTF_OpenFont("./PKMNRSEU.FON", 17);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

Texture texture(renderText(font, "Hello", white, renderer));
texture.setRect(100, 100, 5, texture.getTexture());

bool running = true;

Uint32 startingTick;
SDL_Event event;

while (running)
{
    startingTick = SDL_GetTicks();
    while (SDL_PollEvent(&event))
    {
        if (event.type == SDL_QUIT)
        {
            running = false;
            break;
        }
    }

    SDL_RenderCopy(renderer, texture.getTexture(), NULL, &texture.getRect());
    SDL_RenderPresent(renderer);

    clockTick(startingTick);
}
SDL_DestroyRenderer(renderer);

TTF_CloseFont(font);
</code>```

I have also tried instantiating my object like this:

```<code>Texture* texture = new Texture(renderText(font, "Hello", white, renderer));
</code>```

But I still get the same error. I suspect it is to do with the SDL_Rect not being a pointer.

Thanks in advance!

答:
A simple solution could be to change the signature/implementation of getRect as follows:

```<code>    SDL_Rect *getRect()
    {
        return ▭
    }
</code>```

Then you can call SDL_RenderCopy like this:

```<code>SDL_RenderCopy(renderer, texture.getTexture(), NULL, texture.getRect());
</code>```

Title: Taking address of temporary SDL_Rect

Body:
I am trying to make a simpler container for text in SDL by way of classes. The class is supposed to contain a pointer to an SDL_Texture and an SDL_Rect as well as some methods to get the information from the instances of the class. My problem arises when I try to blit the texture to the screen with the following function:

//Assume that renderer is already created
SDL_RenderCopy(renderer, texture.getTexture(), NULL, &texture.getRect());

The compiler brings my attention to the fourth parameter and states the following:

error: taking address of temporary [-fpermissive]

The code for my class is:

//Class
class Texture
{
    private:
        SDL_Texture* texture;
        SDL_Rect        rect;
    public:
        Texture(){/*Don't call any of the functions when initialized like this*/}
        Texture(SDL_Texture* texure)
        {
            this->texture = texture;
        }
        SDL_Texture* getTexture()
        {
            return texture;
        }
        SDL_Rect getRect()
        {
            return rect;
        }
        void setRect(int posX, int posY, int scale, SDL_Texture* texture)
        {
            int textW = 0;
            int textH = 0;
            SDL_QueryTexture(texture, NULL, NULL, &textW, &textH);
            this->rect = {posX,posY,textW*scale, textH*scale};
        }
};

The code for my main program is:

//Main Program
TTF_Font* font = TTF_OpenFont("./PKMNRSEU.FON", 17);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

Texture texture(renderText(font, "Hello", white, renderer));
texture.setRect(100, 100, 5, texture.getTexture());

bool running = true;

Uint32 startingTick;
SDL_Event event;

while (running)
{
    startingTick = SDL_GetTicks();
    while (SDL_PollEvent(&event))
    {
        if (event.type == SDL_QUIT)
        {
            running = false;
            break;
        }
    }

    SDL_RenderCopy(renderer, texture.getTexture(), NULL, &texture.getRect());
    SDL_RenderPresent(renderer);

    clockTick(startingTick);
}
SDL_DestroyRenderer(renderer);

TTF_CloseFont(font);

I have also tried instantiating my object like this:

Texture* texture = new Texture(renderText(font, "Hello", white, renderer));

But I still get the same error. I suspect it is to do with the SDL_Rect not being a pointer.

Thanks in advance!

Body:
A simple solution could be to change the signature/implementation of getRect as follows:

    SDL_Rect *getRect()
    {
        return &rect;
    }

Then you can call SDL_RenderCopy like this:

SDL_RenderCopy(renderer, texture.getTexture(), NULL, texture.getRect());


问:
Converting two Uint32Array values to Javascript number
I found a code from here that converts Javascript number to inner IEEE representation as two Uint32 values:

```<code>function DoubleToIEEE(f)
{
  var buf = new ArrayBuffer(8);
  (new Float64Array(buf))[0] = f;
  return [ (new Uint32Array(buf))[0] ,(new Uint32Array(buf))[1] ];
}
</code>```

How to convert the returned value back to Javascript number? This way:

```<code>var number = -10.3245535;
var ieee = DoubleToIEEE(number)
var number_again = IEEEtoDouble(ieee);
// number and number_again should be the same (if ever possible)
</code>```

答:
That code is ugly as hell. Use

```<code>function DoubleToIEEE(f) {
  var buf = new ArrayBuffer(8);
  var float = new Float64Array(buf);
  var uint = new Uint32Array(buf);
  float[0] = f;
  return uint;
}
</code>```

If you want an actual Array instead of a Uint32Array (shouldn't make a difference in the most cases), add an Array.from call. You can also reduce this to a oneliner by passing the value to the Float64Array constructor:

```<code>function DoubleToIEEE(f) {
  // use either
  return new Uint32Array(Float64Array.of(f).buffer);
  return Array.from(new Uint32Array(Float64Array.of(f).buffer));
  return Array.from(new Uint32Array((new Float64Array([f])).buffer));
}
</code>```

The inverse would just write the inputs into the uint slots and return the float[0] value:

```<code>function IEEEToDouble(is) {
  var buf = new ArrayBuffer(8);
  var float = new Float64Array(buf);
  var uint = new Uint32Array(buf);
  uint[0] = is[0];
  uint[1] = is[1];
  return float[0];
}
</code>```

which can be shortened to

```<code>function IEEEToDouble(is) {
  return (new Float64Array(Uint32Array.from(is).buffer))[0];
}
</code>```

Body:
I found a code from here that converts Javascript number to inner IEEE representation as two Uint32 values:

function DoubleToIEEE(f)
{
  var buf = new ArrayBuffer(8);
  (new Float64Array(buf))[0] = f;
  return [ (new Uint32Array(buf))[0] ,(new Uint32Array(buf))[1] ];
}

How to convert the returned value back to Javascript number? This way:

var number = -10.3245535;
var ieee = DoubleToIEEE(number)
var number_again = IEEEtoDouble(ieee);
// number and number_again should be the same (if ever possible)

Body:
That code is ugly as hell. Use

function DoubleToIEEE(f) {
  var buf = new ArrayBuffer(8);
  var float = new Float64Array(buf);
  var uint = new Uint32Array(buf);
  float[0] = f;
  return uint;
}

If you want an actual Array instead of a Uint32Array (shouldn't make a difference in the most cases), add an Array.from call. You can also reduce this to a oneliner by passing the value to the Float64Array constructor:

function DoubleToIEEE(f) {
  // use either
  return new Uint32Array(Float64Array.of(f).buffer);
  return Array.from(new Uint32Array(Float64Array.of(f).buffer));
  return Array.from(new Uint32Array((new Float64Array([f])).buffer));
}

The inverse would just write the inputs into the uint slots and return the float[0] value:

function IEEEToDouble(is) {
  var buf = new ArrayBuffer(8);
  var float = new Float64Array(buf);
  var uint = new Uint32Array(buf);
  uint[0] = is[0];
  uint[1] = is[1];
  return float[0];
}

which can be shortened to

function IEEEToDouble(is) {
  return (new Float64Array(Uint32Array.from(is).buffer))[0];
}


问:
Understanding VS 2010 Module Window
When I view the Modules window in VS2010 with my code running, my code i.e. user code = yes it is shown as Optimized = No.

Should I be able to make my code run as optimized and if so how?

Additionally, I see some modules loaded which don't make sense e.g. System.Data.OracleClient.dll, why? I'm not even using oracle within my application??

答:
There is nothing to worry about :) "Optimization" is related to the JIT. See this article JIT Optimization and Debugging for more information.

The fact that System.Data.OracleClient is loaded seems more strange if you're not using Oracle, but VS 2010 has that Data Source tool window that probably hits it even when snobody is using it.

Title: Understanding VS 2010 Module Window


问:
Trigger event upon li click
I'm trying to trigger a function upon users clicking on the li elements in the example below but not having much luck outside of using onclick - i.e. clicking on the first li (value of 1) would ideally call a function where the value "1" is passed in.

Styled list control

```<code>..
    <a href="#" class="path-nav-close"></a>
    <ul id='uItem'>
        <li><a href="#" class="launch" >1</a></li>
        <li><a href="#" class="launch" onclick="alert('2')">2</a></li>

...
</code>```

https://jsfiddle.net/wL8vpuqt/5/

答:
Working fiddle.

You've just to prevent default behavior by using event.preventDefault() :

```<code>$(document).ready(function() {
  $('ul#uItem li').click(function(event) {
    event.preventDefault();

    alert($(this).text());
  });
});
</code>```

Hope this helps.

$(document).ready(function() {
  $('ul#uItem li').click(function(e) {
    e.preventDefault();

    alert($(this).text());
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* line 81, ../sass/menu.scss */
.path-nav {
  -moz-transform: translateZ(0);
  -webkit-transform: translateZ(0);
  -o-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  position: fixed;
}
/* line 87, ../sass/menu.scss */
.path-nav.path-nav-bottom-left {
  bottom: 30%;
  left: 20%;
  position: absolute;
}
/* line 93, ../sass/menu.scss */
.path-nav.path-nav-top-right {
  top: 26px;
  right: 26px;
}
/* line 100, ../sass/menu.scss */
.path-nav a {
  position: relative;
  z-index: 1;
  display: block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  border: 6px solid white;
  background: #44403d;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  -o-border-radius: 50%;
  -ms-border-radius: 50%;
  -khtml-border-radius: 50%;
  border-radius: 50%;
  color: #fff;
  text-align: center;
  font-weight: bold;
  font-size: 16px;
  font-family: sans-serif;
  text-decoration: none;
  -moz-box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -webkit-box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -o-box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
}
/* line 127, ../sass/menu.scss */
.path-nav.active a {
  -moz-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -webkit-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -o-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
}
/* line 137, ../sass/menu.scss */
.path-nav ul {
  position: absolute;
  z-index: 0;
  top: 8.5px;
  left: 8.5px;
  margin: 0;
  padding: 0;
}
/* line 147, ../sass/menu.scss */
.path-nav li {
  position: absolute;
  z-index: 0;
  display: block;
  top: 0;
  left: 0;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(1) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.175s;
  -webkit-transition-delay: 0.175s;
  -o-transition-delay: 0.175s;
  transition-delay: 0.175s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(2) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.14s;
  -webkit-transition-delay: 0.14s;
  -o-transition-delay: 0.14s;
  transition-delay: 0.14s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(3) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.105s;
  -webkit-transition-delay: 0.105s;
  -o-transition-delay: 0.105s;
  transition-delay: 0.105s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(4) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.07s;
  -webkit-transition-delay: 0.07s;
  -o-transition-delay: 0.07s;
  transition-delay: 0.07s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(5) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.035s;
  -webkit-transition-delay: 0.035s;
  -o-transition-delay: 0.035s;
  transition-delay: 0.035s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(6) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0s;
  -webkit-transition-delay: 0s;
  -o-transition-delay: 0s;
  transition-delay: 0s;
}
/* line 169, ../sass/menu.scss */
.path-nav:target li {
  -moz-transform: rotate(1800deg);
  -webkit-transform: rotate(1800deg);
  -o-transform: rotate(1800deg);
  -ms-transform: rotate(1800deg);
  transform: rotate(1800deg);
}
/* line 174, ../sass/menu.scss */
.path-nav:target .cross {
  -moz-transform-origin: 50% 50%;
  -webkit-transform-origin: 50% 50%;
  -o-transform-origin: 50% 50%;
  -ms-transform-origin: 50% 50%;
  transform-origin: 50% 50%;
  -moz-transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  -o-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(1) {
  top: -100px;
  left: 80px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(2) {
  top: -100px;
  left: 150px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(3) {
  top: -100px;
  left: 220px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(4) {
  top: -30px;
  left: 80px;

}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(5) {
  top: -30px;
  left: 150px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(6) {
  top: -30px;
  left: 220px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(7) {
  top: 40px;
  left: 80px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(8) {
  top: 40px;
  left: 150px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(9) {
  top: 40px;
  left: 220px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(10) {
  top: 110px;
  left: 150px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(1) {
  top: 265px;
  left: 0px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(2) {
  top: 252px;
  left: -82px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(3) {
  top: 214px;
  left: -156px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(4) {
  top: 156px;
  left: -214px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(5) {
  top: 82px;
  left: -252px;
}
/* line 200, ../sass/menu.scss */
.path-nav .path-nav-expander,
.path-nav .path-nav-close {
  z-index: 3;
  width: 68px;
  height: 68px;
  line-height: 68px;
}
/* line 208, ../sass/menu.scss */
.path-nav .path-nav-close {
  z-index: 2;
  position: absolute;
  top: 0;
  left: 0;
  background: none;
  outline: red;
  -moz-box-shadow: 0;
  -webkit-box-shadow: 0;
  -o-box-shadow: 0;
  box-shadow: 0;
}
/* line 222, ../sass/menu.scss */
.path-nav:target .path-nav-expander {
  z-index: 1;
}
/* line 228, ../sass/menu.scss */
.path-nav .path-nav-expander {
  position: relative;
  background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #0fd2ab), color-stop(50%, #0fd2ab), color-stop(50%, #0fd2ab));
  background: -webkit-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: -moz-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: -o-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: -ms-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  -moz-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
  -webkit-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
  -o-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
  box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
}
/* line 241, ../sass/menu.scss */
.path-nav .path-nav-expander .cross {
  position: relative;
  width: 68px;
  height: 68px;
  -moz-transition: all 0.2s;
  -webkit-transition: all 0.2s;
  -o-transition: all 0.2s;
  transition: all 0.2s;
}
/* line 249, ../sass/menu.scss */
.path-nav .path-nav-expander .cross .cross-h,
.path-nav .path-nav-expander .cross .cross-v {
  position: absolute;
  top: 50%;
  left: 50%;
  background: #fff;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  -o-border-radius: 2px;
  -ms-border-radius: 2px;
  -khtml-border-radius: 2px;
  border-radius: 2px;
}
/* line 259, ../sass/menu.scss */
.path-nav .path-nav-expander .cross .cross-h {
  width: 8px;
  margin-left: -4px;
  height: 40px;
  margin-top: -20px;
}
/* line 267, ../sass/menu.scss */
.path-nav .path-nav-expander .cross .cross-v {
  width: 40px;
  margin-left: -20px;
  height: 8px;
  margin-top: -4px;
}

/* line 277, ../sass/menu.scss */
.path-nav-top-right .path-nav-expander {
  background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #143da5), color-stop(50%, #133a9c), color-stop(50%, #103081));
  background: -webkit-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: -moz-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: -o-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: -ms-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: linear-gradient(#143da5, #133a9c 50%, #103081 50%);
}</code>```

1

2

3

4

5

6

7

8

9

10

```

Title: Trigger event upon li click

Body:
I'm trying to trigger a function upon users clicking on the li elements in the example below but not having much luck outside of using onclick - i.e. clicking on the first li (value of 1) would ideally call a function where the value "1" is passed in.

Styled list control

..

1

2

...

https://jsfiddle.net/wL8vpuqt/5/

Body:
Working fiddle.

You've just to prevent default behavior by using event.preventDefault() :

$(document).ready(function() {
  $('ul#uItem li').click(function(event) {
    event.preventDefault();

    alert($(this).text());
  });
});

Hope this helps.

$(document).ready(function() {
  $('ul#uItem li').click(function(e) {
    e.preventDefault();

    alert($(this).text());
  });
});

/* line 81, ../sass/menu.scss */
.path-nav {
  -moz-transform: translateZ(0);
  -webkit-transform: translateZ(0);
  -o-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  position: fixed;
}
/* line 87, ../sass/menu.scss */
.path-nav.path-nav-bottom-left {
  bottom: 30%;
  left: 20%;
  position: absolute;
}
/* line 93, ../sass/menu.scss */
.path-nav.path-nav-top-right {
  top: 26px;
  right: 26px;
}
/* line 100, ../sass/menu.scss */
.path-nav a {
  position: relative;
  z-index: 1;
  display: block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  border: 6px solid white;
  background: #44403d;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  -o-border-radius: 50%;
  -ms-border-radius: 50%;
  -khtml-border-radius: 50%;
  border-radius: 50%;
  color: #fff;
  text-align: center;
  font-weight: bold;
  font-size: 16px;
  font-family: sans-serif;
  text-decoration: none;
  -moz-box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -webkit-box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -o-box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
}
/* line 127, ../sass/menu.scss */
.path-nav.active a {
  -moz-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -webkit-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  -o-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
  box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 0 2px rgba(0, 0, 0, 0.8);
}
/* line 137, ../sass/menu.scss */
.path-nav ul {
  position: absolute;
  z-index: 0;
  top: 8.5px;
  left: 8.5px;
  margin: 0;
  padding: 0;
}
/* line 147, ../sass/menu.scss */
.path-nav li {
  position: absolute;
  z-index: 0;
  display: block;
  top: 0;
  left: 0;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(1) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.175s;
  -webkit-transition-delay: 0.175s;
  -o-transition-delay: 0.175s;
  transition-delay: 0.175s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(2) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.14s;
  -webkit-transition-delay: 0.14s;
  -o-transition-delay: 0.14s;
  transition-delay: 0.14s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(3) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.105s;
  -webkit-transition-delay: 0.105s;
  -o-transition-delay: 0.105s;
  transition-delay: 0.105s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(4) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.07s;
  -webkit-transition-delay: 0.07s;
  -o-transition-delay: 0.07s;
  transition-delay: 0.07s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(5) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0.035s;
  -webkit-transition-delay: 0.035s;
  -o-transition-delay: 0.035s;
  transition-delay: 0.035s;
}
/* line 155, ../sass/menu.scss */
.path-nav li:nth-child(6) {
  -moz-transition-property: all;
  -webkit-transition-property: all;
  -o-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275);
  -moz-transition-delay: 0s;
  -webkit-transition-delay: 0s;
  -o-transition-delay: 0s;
  transition-delay: 0s;
}
/* line 169, ../sass/menu.scss */
.path-nav:target li {
  -moz-transform: rotate(1800deg);
  -webkit-transform: rotate(1800deg);
  -o-transform: rotate(1800deg);
  -ms-transform: rotate(1800deg);
  transform: rotate(1800deg);
}
/* line 174, ../sass/menu.scss */
.path-nav:target .cross {
  -moz-transform-origin: 50% 50%;
  -webkit-transform-origin: 50% 50%;
  -o-transform-origin: 50% 50%;
  -ms-transform-origin: 50% 50%;
  transform-origin: 50% 50%;
  -moz-transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  -o-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(1) {
  top: -100px;
  left: 80px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(2) {
  top: -100px;
  left: 150px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(3) {
  top: -100px;
  left: 220px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(4) {
  top: -30px;
  left: 80px;

}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(5) {
  top: -30px;
  left: 150px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(6) {
  top: -30px;
  left: 220px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(7) {
  top: 40px;
  left: 80px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(8) {
  top: 40px;
  left: 150px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(9) {
  top: 40px;
  left: 220px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-bottom-left:target li:nth-child(10) {
  top: 110px;
  left: 150px;
}

/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(1) {
  top: 265px;
  left: 0px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(2) {
  top: 252px;
  left: -82px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(3) {
  top: 214px;
  left: -156px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(4) {
  top: 156px;
  left: -214px;
}
/* line 73, ../sass/menu.scss */
.path-nav.path-nav-top-right:target li:nth-child(5) {
  top: 82px;
  left: -252px;
}
/* line 200, ../sass/menu.scss */
.path-nav .path-nav-expander,
.path-nav .path-nav-close {
  z-index: 3;
  width: 68px;
  height: 68px;
  line-height: 68px;
}
/* line 208, ../sass/menu.scss */
.path-nav .path-nav-close {
  z-index: 2;
  position: absolute;
  top: 0;
  left: 0;
  background: none;
  outline: red;
  -moz-box-shadow: 0;
  -webkit-box-shadow: 0;
  -o-box-shadow: 0;
  box-shadow: 0;
}
/* line 222, ../sass/menu.scss */
.path-nav:target .path-nav-expander {
  z-index: 1;
}
/* line 228, ../sass/menu.scss */
.path-nav .path-nav-expander {
  position: relative;
  background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #0fd2ab), color-stop(50%, #0fd2ab), color-stop(50%, #0fd2ab));
  background: -webkit-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: -moz-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: -o-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: -ms-linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  background: linear-gradient(#0fd2ab, #0fd2ab 50%, #0fd2ab 50%);
  -moz-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
  -webkit-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
  -o-box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
  box-shadow: 0 0.2em 1em 2px rgba(0, 0, 0, 0.4), 0 0 0 2px rgba(0, 0, 0, 0.25), inset 0 2px 2px rgba(255, 255, 255, 0.5);
}
/* line 241, ../sass/menu.scss */
.path-nav .path-nav-expander .cross {
  position: relative;
  width: 68px;
  height: 68px;
  -moz-transition: all 0.2s;
  -webkit-transition: all 0.2s;
  -o-transition: all 0.2s;
  transition: all 0.2s;
}
/* line 249, ../sass/menu.scss */
.path-nav .path-nav-expander .cross .cross-h,
.path-nav .path-nav-expander .cross .cross-v {
  position: absolute;
  top: 50%;
  left: 50%;
  background: #fff;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  -o-border-radius: 2px;
  -ms-border-radius: 2px;
  -khtml-border-radius: 2px;
  border-radius: 2px;
}
/* line 259, ../sass/menu.scss */
.path-nav .path-nav-expander .cross .cross-h {
  width: 8px;
  margin-left: -4px;
  height: 40px;
  margin-top: -20px;
}
/* line 267, ../sass/menu.scss */
.path-nav .path-nav-expander .cross .cross-v {
  width: 40px;
  margin-left: -20px;
  height: 8px;
  margin-top: -4px;
}

/* line 277, ../sass/menu.scss */
.path-nav-top-right .path-nav-expander {
  background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #143da5), color-stop(50%, #133a9c), color-stop(50%, #103081));
  background: -webkit-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: -moz-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: -o-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: -ms-linear-gradient(#143da5, #133a9c 50%, #103081 50%);
  background: linear-gradient(#143da5, #133a9c 50%, #103081 50%);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav id="menu" class="path-nav path-nav-bottom-left">
  <a href="#menu" class="path-nav-expander">
    <div class="cross">
      <div class="cross-h"></div>
      <div class="cross-v"></div>
    </div>
  </a>
  <a href="#" class="path-nav-close"></a>
  <ul id='uItem'>
    <li><a href="#" class="launch" >1</a></li>
    <li><a href="#" class="launch">2</a></li>
    <li><a href="#" class="launch">3</a></li>
    <li><a href="#" class="launch">4</a></li>
    <li><a href="#" class="launch">5</a></li>
    <li><a href="#" class="launch">6</a></li>
    <li><a href="#" class="launch">7</a></li>
    <li><a href="#" class="launch">8</a></li>
    <li><a href="#" class="launch">9</a></li>
    <li><a href="#" class="launch" o>10</a></li>
  </ul>
</nav>


问:
weird segfault in R when using mclapply in Linux
I have encountered this weird segfault error and have zero clue how to solve it. I was running some Markov Chain Monte Carlo algorithm (a sequential algorithm that approximates a distribution). I parallelize each single iteration of this algorithm. So it is something like

```<code>for (iter in 1:T){
  res[iter] = mclapply(fun)
}
</code>```

Now the weird thing is when the size of my dataset is relatively moderate, the algorithm can run with no problem. Then I increase the dataset size (80,000 observations, not super large), the algorithm works for the first one thousand iterations and then stop with a segfault error. I have pasted the error below:

```<code>*** caught segfault ***
address 0x20, cause 'memory not mapped'

Traceback:
1: mcfork()
2: FUN(X[[i]], ...)
3: lapply(seq_len(cores), inner.do)
4: mclapply(1:n, FUN = function(k) { return(OptimRE(dataSummaries[[k]], mu + beta, v, vre))}, mc.cores = ncores)
5: getMargLikelihood0(dataSummaries_layer1[[k]], mu, v, vre, beta[k],    logarithm = TRUE)
6: FUN(X[[i]], ...)
7: lapply(X = S, FUN = FUN, ...)
8: doTryCatch(return(expr), name, parentenv, handler)
9: tryCatchOne(expr, names, parentenv, handlers[[1L]])
10: tryCatchList(expr, classes, parentenv, handlers)
11: tryCatch(expr, error = function(e) {    call <- conditionCall(e) if (!is.null(call)) {        if (identical(call[[1L]], quote(doTryCatch)))             call <- sys.call(-4L)        dcall <- deparse(call)[1L]        prefix <- paste("Error in", dcall, ": ") LONG <- 75L        msg <- conditionMessage(e)        sm <- strsplit(msg, "\n")[[1L]]        w <- 14L + nchar(dcall, type = "w") + nchar(sm[1L], type = "w")        if (is.na(w))             w <- 14L + nchar(dcall, type = "b") + nchar(sm[1L],                 type = "b")    if (w > LONG)             prefix <- paste0(prefix, "\n  ")    }    else prefix <- "Error : "    msg <- paste0(prefix, conditionMessage(e), "\n") .Internal(seterrmessage(msg[1L]))    if (!silent && identical(getOption("show.error.messages"),     TRUE)) { cat(msg, file = stderr())        .Internal(printDeferredWarnings())    }    invisible(structure(msg, class = "try-error", condition = e))})
12: try(lapply(X = S, FUN = FUN, ...), silent = TRUE)
13: sendMaster(try(lapply(X = S, FUN = FUN, ...), silent = TRUE))
14: FUN(X[[i]], ...)
15: lapply(seq_len(cores), inner.do)
16: mclapply(1:length(beta), FUN = function(k) { return(getMargLikelihood0(dataSummaries_layer1[[k]], mu,         v, vre, beta[k], logarithm = TRUE))}, mc.cores = ncores)
17: getMargLikelihood(dataSummaries_layer1, newm, news, newv, beta1)
18: FitPoissRegNRE(my[j, ], groupid, id1, id2, nb = nb, nc = nc,     sig = sig, a = a, b = b, a2 = a2[j], b2 = b2[j], ps_m = ps_m,     ps_s = ps_s, njump = njump)
19: ApplyFitPoissRegNRE(y, hashABC, hashAB, hashA, nb = 200, nc = 800,   sig = 1000, a = 2, b = 2, a2 = rep(100, 3), b2 = rep(5, 3),     ps_m = 0.01, ps_s = 0.03, njump = 4)
20: eval(expr, envir, enclos)
21: eval(ei, envir)
22: withVisible(eval(ei, envir))
</code>```

I have googled and some people did encounter this segfalut issue in R and what they usually suggested is some version conflict and R should be reinstalled. But the weird thing in my case is that my algorithm works properly in the first thousand iterations. I also ran it without parallelization and it also works fine.

Could anyone suggest what is some possible causes for this? Now I completely have no direction.

Thanks!

答:
A comment in addition to Steve's suggestion to check for zombie processes: It looks like your code is spawning off recursive mclapply(..., mc.cores = ncores) calls;

```<code>4: mclapply(1:n, FUN = function(k) { return(OptimRE(dataSummaries[[k]], mu + beta, v, vre))}, mc.cores = ncores)
[...]
16: mclapply(1:length(beta), FUN = function(k) { return(getMargLikelihood0(dataSummaries_layer1[[k]], mu, v, vre, beta[k], logarithm = TRUE))}, mc.cores = ncores)
</code>```

In other words, you might end up with "ncores * ncores" forked processes in each iteration.  I don't know what the two ncores are here, but make sure to check that this is really what you want.

Body:
I have encountered this weird segfault error and have zero clue how to solve it. I was running some Markov Chain Monte Carlo algorithm (a sequential algorithm that approximates a distribution). I parallelize each single iteration of this algorithm. So it is something like

for (iter in 1:T){
  res[iter] = mclapply(fun)
}

Now the weird thing is when the size of my dataset is relatively moderate, the algorithm can run with no problem. Then I increase the dataset size (80,000 observations, not super large), the algorithm works for the first one thousand iterations and then stop with a segfault error. I have pasted the error below:

*** caught segfault ***
address 0x20, cause 'memory not mapped'

Traceback:
1: mcfork()
2: FUN(X[[i]], ...)
3: lapply(seq_len(cores), inner.do)
4: mclapply(1:n, FUN = function(k) { return(OptimRE(dataSummaries[[k]], mu + beta, v, vre))}, mc.cores = ncores)
5: getMargLikelihood0(dataSummaries_layer1[[k]], mu, v, vre, beta[k],    logarithm = TRUE)
6: FUN(X[[i]], ...)
7: lapply(X = S, FUN = FUN, ...)
8: doTryCatch(return(expr), name, parentenv, handler)
9: tryCatchOne(expr, names, parentenv, handlers[[1L]])
10: tryCatchList(expr, classes, parentenv, handlers)
11: tryCatch(expr, error = function(e) {    call <- conditionCall(e) if (!is.null(call)) {        if (identical(call[[1L]], quote(doTryCatch)))             call <- sys.call(-4L)        dcall <- deparse(call)[1L]        prefix <- paste("Error in", dcall, ": ") LONG <- 75L        msg <- conditionMessage(e)        sm <- strsplit(msg, "\n")[[1L]]        w <- 14L + nchar(dcall, type = "w") + nchar(sm[1L], type = "w")        if (is.na(w))             w <- 14L + nchar(dcall, type = "b") + nchar(sm[1L],                 type = "b")    if (w > LONG)             prefix <- paste0(prefix, "\n  ")    }    else prefix <- "Error : "    msg <- paste0(prefix, conditionMessage(e), "\n") .Internal(seterrmessage(msg[1L]))    if (!silent && identical(getOption("show.error.messages"),     TRUE)) { cat(msg, file = stderr())        .Internal(printDeferredWarnings())    }    invisible(structure(msg, class = "try-error", condition = e))})
12: try(lapply(X = S, FUN = FUN, ...), silent = TRUE)
13: sendMaster(try(lapply(X = S, FUN = FUN, ...), silent = TRUE))
14: FUN(X[[i]], ...)
15: lapply(seq_len(cores), inner.do)
16: mclapply(1:length(beta), FUN = function(k) { return(getMargLikelihood0(dataSummaries_layer1[[k]], mu,         v, vre, beta[k], logarithm = TRUE))}, mc.cores = ncores)
17: getMargLikelihood(dataSummaries_layer1, newm, news, newv, beta1)
18: FitPoissRegNRE(my[j, ], groupid, id1, id2, nb = nb, nc = nc,     sig = sig, a = a, b = b, a2 = a2[j], b2 = b2[j], ps_m = ps_m,     ps_s = ps_s, njump = njump)
19: ApplyFitPoissRegNRE(y, hashABC, hashAB, hashA, nb = 200, nc = 800,   sig = 1000, a = 2, b = 2, a2 = rep(100, 3), b2 = rep(5, 3),     ps_m = 0.01, ps_s = 0.03, njump = 4)
20: eval(expr, envir, enclos)
21: eval(ei, envir)
22: withVisible(eval(ei, envir))

I have googled and some people did encounter this segfalut issue in R and what they usually suggested is some version conflict and R should be reinstalled. But the weird thing in my case is that my algorithm works properly in the first thousand iterations. I also ran it without parallelization and it also works fine.

Could anyone suggest what is some possible causes for this? Now I completely have no direction.

Thanks!

Body:
A comment in addition to Steve's suggestion to check for zombie processes: It looks like your code is spawning off recursive mclapply(..., mc.cores = ncores) calls;

4: mclapply(1:n, FUN = function(k) { return(OptimRE(dataSummaries[[k]], mu + beta, v, vre))}, mc.cores = ncores)
[...]
16: mclapply(1:length(beta), FUN = function(k) { return(getMargLikelihood0(dataSummaries_layer1[[k]], mu, v, vre, beta[k], logarithm = TRUE))}, mc.cores = ncores)

In other words, you might end up with "ncores * ncores" forked processes in each iteration.  I don't know what the two ncores are here, but make sure to check that this is really what you want.


问:
Broad crawling - different xpaths - Scrapy
I'm new in Scrapy. I have thousands of url,xpath tuples and values in a database.
These urls are from different domains (not allways, there can be 100 urls from the same domain).

```<code>x.com/a //h1
y.com/a //div[@class='1']
z.com/a //div[@href='...']
x.com/b //h1
x.com/c //h1
...
</code>```

Now I want to get these values every 2 hours as fast as possible but to be sure that I don't overload any of these.

Can't figure out how to do that.

My thoughts:

I could create one Spider for every different domain, set it's parsing rules and run them at once.

Is it a good practice?

EDIT:
I'm not sure how it would work with outputting data into database according to concurrency.

EDIT2:

I can do something like this - for every domain there is a new spider. But this is impossible to do having thousands of different urls and it's xpaths.

```<code>class WikiScraper(scrapy.Spider):
    name = "wiki_headers"

    def start_requests(self):
        urls = [
            'https://en.wikipedia.org/wiki/Spider',
            'https://en.wikipedia.org/wiki/Data_scraping',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//h1/text()').extract()
        print header
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

class CraigslistScraper(scrapy.Spider):
    name = "craigslist_headers"

    def start_requests(self):
        urls = [
            'https://columbusga.craigslist.org/act/6062657418.html',
            'https://columbusga.craigslist.org/acc/6060297390.html',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//span[@id="titletextonly"]/text()').extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)
</code>```

答:
if you are thinking about scrapy can't handle multiple domains at once because of the allowed_domains parameters, remember that it is optional.

If no allowed_domains parameter is set in the spider, it can work with every domain it gets.

Body:
I'm new in Scrapy. I have thousands of url,xpath tuples and values in a database.
These urls are from different domains (not allways, there can be 100 urls from the same domain).

x.com/a //h1
y.com/a //div[@class='1']
z.com/a //div[@href='...']
x.com/b //h1
x.com/c //h1
...

Now I want to get these values every 2 hours as fast as possible but to be sure that I don't overload any of these.

Can't figure out how to do that.

My thoughts:

I could create one Spider for every different domain, set it's parsing rules and run them at once.

Is it a good practice?

EDIT:
I'm not sure how it would work with outputting data into database according to concurrency.

EDIT2:

I can do something like this - for every domain there is a new spider. But this is impossible to do having thousands of different urls and it's xpaths.

class WikiScraper(scrapy.Spider):
    name = "wiki_headers"

    def start_requests(self):
        urls = [
            'https://en.wikipedia.org/wiki/Spider',
            'https://en.wikipedia.org/wiki/Data_scraping',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//h1/text()').extract()
        print header
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

class CraigslistScraper(scrapy.Spider):
    name = "craigslist_headers"

    def start_requests(self):
        urls = [
            'https://columbusga.craigslist.org/act/6062657418.html',
            'https://columbusga.craigslist.org/acc/6060297390.html',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//span[@id="titletextonly"]/text()').extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)


问:
Wait on background thread for a random time
Currently I'm using this to wait for 5 seconds on the background thread before calling a function: DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 5, execute: {

This works great but I'd like to wait for a random duration each time.
Doing something like this:

```<code>let randomTime = Int(arc4random_uniform(10))
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + randomTime, execute: {
</code>```

gives me the error: Type of expression is ambiguous without more context

Cheers.

答:
.now() returns a DispatchTime Type. Something like

```<code>DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime(uptimeNanoseconds: [any_random_generator]......
</code>```

should do. note that any_random_generator must return UInt64 and that the time is expressed in nanoseconds

Body:
Currently I'm using this to wait for 5 seconds on the background thread before calling a function: DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 5, execute: {

This works great but I'd like to wait for a random duration each time.
Doing something like this:

let randomTime = Int(arc4random_uniform(10))
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + randomTime, execute: {

gives me the error: Type of expression is ambiguous without more context

Cheers.

Body:
.now() returns a DispatchTime Type. Something like

DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime(uptimeNanoseconds: [any_random_generator]......

should do. note that any_random_generator must return UInt64 and that the time is expressed in nanoseconds