mercredi 1 novembre 2017

if condition does not end execution?

In my controller, I have a if condition like this

 public function index()
    {
        //if user is logged in 
        if (auth()->guard('web')->check())
        {
            return back()->withMessage('You are not allowed');
        }
      //if not logged in
      long time consuming API call here - takes 1 minute

This logic does not work as intended, as even if you are logged in, it takes one minute to show the message of 'You are not allowed'. Isn't it supposed to check the if condition first and if it matches,end the execution? It should be returning back (if logged in) instantly, but it makes the API call and takes one minute to redirect back.

Am I missing something?

Console.KeyAvailable isn't being triggered

I am wanting to detect if any key is being pressed but as far as I can tell the if statement isn't being triggered otherwise the program would shut down due to Enviroment.Exit(0).

public static int GameLoop()
        {
            while(true)
            {
                if(Console.KeyAvailable == true)
                {
                    Environment.Exit(0); //test to see if being used
                    Player.KeyPressed = Console.ReadKey().KeyChar;
                    Player.Movement();
                }

                Console.WriteLine("working");

GameLoop() is being called because Console.WriteLine("working") is being executed. Any Ideas as to why Console.KeyAvailable == true isn't being met on key press? Thanks!

Console.KeyAvailable MSDN

Implementing a dictionary to show a case statement in Python 3.x

I'm novice to Python (3.x) and I am given the task of asking students country and capital names.

The program must...

  • Read a text file of countries and their capital cities (which I have a .csv file provided)

  • Ask 10 questions about the capitals of 10 countries

  • If user gets the capital city correct, they gain one mark

  • If user gets the capital city incorrect, they should be told the correct answer

  • At the end of the 10 questions, user receives feedback about their performance depending on how many marks out of 10 they achieved.

This feedback should be implemented using a dictionary to show that case-type statements can be simulated in Python (as Python doesn't use case/switch statements).

I have written a guide to implement for the feedback depending on the amount of marks user has achieved.

This is the code I have attempted so far with the listed countries and their capitals (which is also included in the .csv file), however I am a bit stuck:

countries = {
'United Kingdom',
'France',
'Germany',
'Spain',
'Portugal',
'Poland',
'Czech Republic',
'Belgium',
'Hungary',
'Sweden',
'Norway',
'Finland'

}

capitals = {
    'London',
    'Paris',
    'Berlin',
    'Madrid',
    'Lisbon',
    'Warsaw',
    'Prague',
    'Brussels',
    'Budapest',
    'Stockholm',
    'Oslo',
    'Helinski'

}

import csv
import random

ans = True

print("Press X to quit")

try:
        # a = append, w = write
    with open('capitals.csv', 'w', newline='') as csvfile:
        write = csv.writer(csvfile, dialect='excel')

    while ans:
        # Country Input
        country = input('What is the country?')
        if country != 'X':
            if country in countries:
                country_name = countries[country]
            else:
                country_name = 'Country is not listed.'
                print('The name of the country that you have chosen is', country)

            # Capital Input
            capital = input('What is the capital?')
            if capital != 'X':
                if capital in capitals:
                    capital_name = capitals[capital]
            else:
                capital_name = 'Capital is not listed.'
                print('The name of the capital that you have chosen is', capital)

                write.writerow([country, capital])

                def validmark():
                    global mark
                    if int(mark) >=0 and int(mark) <=10:
                        return True
                    else:
                        return False

    total = input('What is the maximum amount of marks? ')
    while not validmark(total):
        total = input('Re-enter maximum amount of marks ')

        if country =="X" or capital == "X":
            print("\nGoodbye") 
            ans = False

except OSError as err:
    print("Unable to access file")

I must report how an if and a case-type construct is used for this particular piece of code.

I am still quite new to Python and programming as a whole so if you could help me out that would be much appreciated, thanks.

Excel -VBA help, Protect and Unprotect custom cells according to a list selection

Hi everyone I am trying to create a customisable spreadsheet.

So that if the user selects from a data validation list "N/A" (list is located in cell N18) a certain range of field become greyed out, and locked so that the user can not input anything into this range.

If the user selects the blank option from the list " " the user can input the information into needed in this range.

The user needs to be able to toggle from between theses values in the list and spreadsheet would need to be able to update itself each time by clicking a button on the spreadsheet.

When I click the button on the excel spreadsheet I get an Argument not optional error'

My code and error message is shown down below. Any help would be much appreciated.

Argument not optional

Dim boolLock As Boolean
Dim r As Integer
Dim ws As Worksheet




Public Sub LockUnlockFields(ByVal Target As Range)

'Fields are shaded and locked acccording to user input, t9o creat a cust UI

'Target cell range


   If Intersect(Target, Range("rESOne")) Then
  'If Sheets("Nameplate").Range("rMotBool").Value = True

Application.EnableEvents = False   'Stops events from proccessing


Select Case Target.Value

    Case Is = "N/A"
    boolLock = True
    r = 191
    Debug.Print ("Trigger 1 ")

    Case Is = " "
    boolLock = False

    Application.Wait (Now + TimeValue("0:00:01"))
    Debug.Print ("Trigger 2 ")


End Select

  ws.Unprotect Password:="myPassword"

  With Range("K26:N32")

 'fills the cells grey before locking them, or turn them back to original    colour if it's unlocked
    .Interior.Color = RGB(r, r, r)
    .Locked = boolLock

End With

ws.Protect Password:="myPassword"

Application.EnableEvents = True

End If

End Sub

Thanks

JavaScript - returning true even though condition is not fullfilled [duplicate]

This question already has an answer here:

I have the following code:

console.log(usernameExists);
if (usernameExists = true) {
  console.log("returning true");
  return true;
} else if (looped = true) {
  console.log(usernameExists+" is returned");
  looped = null;
  return false;
}

The first console.log(usernameExists) is returning false, but still I am getting a console message of "returning true", and the function in which this is, is returning true! I simply can't figure this out.

Python: Why dosen't my if-statement work correctly?

I'm trying to create a very simple tictactoe game.

I have this if-statement which dosen't seem to work as I want:

#Defining the board. 3 rows with 3 cells
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

#Player icons
p1_icon = "X"
p2_icon = "O"

#Player input
p1_input_row = 0
p1_input_cell = 0
p2_input_row = 0
p2_input_cell = 0
#Player input text
p1_turn = "Player 1's turn: "
p2_turn = "Player 2's turn: "

#String for invalid answer
invalid = "Invalid answer! Try again."

#Function for printing the board
def print_board():
    print("-------")
    print("|" + str(board[0][0]) + "|" + str(board[0][1]) + "|" + str(board[0][2]) + "|")
    print("-------")
    print("|" + str(board[1][0]) + "|" + str(board[1][1]) + "|" + str(board[1][2]) + "|")
    print("-------")
    print("|" + str(board[2][0]) + "|" + str(board[2][1]) + "|" + str(board[2][2]) + "|")
    print("-------")

#Main game-loop
while True:
    #Player 1's turn
    print(p1_turn)
    p1_input_row = int(input("Row: "))
    #Check player 1's input
    if p1_input_row == 1 or 2 or 3:
        p1_input_cell = int(input("Cell: "))
        if p1_input_cell == 1 or 2 or 3:
            board[(p1_input_row - 1)][(p1_input_cell - 1)] = p1_icon
            print_board()
        else:
            print(invalid)
    elif p1_input_row == 4:
        print("WTF")
    else:
        print(invalid)
    break

I want to check if the player (p1_input_row) choose a row between 1 and 3. If so, then the program should ask the player to choose a cell: p1_input_cell = int(input("Cell: ")). If the player didn't choose a row between 1 and 3, then display a error message. The same if-statement goes for p1_input_cell.

When I write 4for example, then the error message dosn't display. The program asks for the cell instead. Why is that?

mardi 31 octobre 2017

while loop terminating early with nested if statement

I'm writing a condition check for a simple input via prompt() in JavaScript. The idea is to repeat a prompt until the user supplies a positive integer.

In particular, if I submit a negative integer, it correctly prompts me again via case 3. However, if I answer the second prompt again with a negative integer, the code unexpectedly leaves the while loop.

In the if statement:

Case 1: checks if the user 'cancels' the prompt box (or returns an empty string), in which case I set a variable 'cancelGridCreation' to 'true' to later cancel the encapsulating process (outside of the included code), and then terminate the while loop by setting the variable 'waitingForQualifyingAnswer' to 'false'.

Case 2: checks if the response is an acceptable integer (number, integer, positive), and sets the conditional variable 'false' to terminate the while loop.

Case 3: prompts the user again, with the idea that the newly entered data will be checked again by the same 3 'if' cases.

User inputs matching cases 1 and 2 seem to work fine. However, as mentioned above, entering a negative integer 2 times terminates the while loop. See the console output that I received, entering -10 and then -20. As well, the console.log() outputs don't seem to occur in an order matching their location in the code (perhaps a processing time-lag issue?). You'll see that the console.log() from case 3 outputs before the "initial size entered" console.log(), which is coded before the while loop even starts.

Similar results seem to occur whenever case 3 is followed by another case 3 (regardless whether input is negative integers, decimals, or strings), as well as case 3 followed by case 1 (of course, here case 1 would terminate the loop, but the console log statements still seem to occur out of order).

Link to interactive code at JSBin: http://ift.tt/2xJ0e4r

JavaScript Code:

let cancelGridCreation = false;
let waitingForQualifyingAnswer = true;
let answer = prompt('Please enter the number of rows/columns, as a positive integer:', '16');
let gridSize = parseFloat(answer, 10);
console.log('initial size entered: ' + gridSize);
while (waitingForQualifyingAnswer === true) {
  console.log('top of while loop');
  if (answer == null || answer == "") {
    console.log('prompt - canceled');     
    cancelGridCreation = true;
    waitingForQualifyingAnswer = false;
  } else if (typeof gridSize === 'number' && gridSize % 1 === 0 && gridSize > 0) {
    console.log('prompt - good answer: ' + gridSize);
    waitingForQualifyingAnswer = false;
  } else {
    console.log('prompt - BAD answer: ' + gridSize);
    answer = prompt('Incorrect format entered.  Please enter the number of rows/columns, as a positive integer:', '16');
    gridSize = parseFloat(answer, 10);
    console.log('new size entered: ' + gridSize);
  }
  console.log('end of while loop');
}
console.log('done:');
console.log(gridSize);

Console Output was as follows (having entered -10 at the first prompt, and -20 at the second prompt):

    "prompt - BAD answer: -10"
    "top of while loop"
    "initial size entered: -10"
    "new size entered: -20"
    "end of while loop"
    "done:"
    -20

I'm pretty new, and realize there may be more concise ways to accomplish this. I'm interested in suggestions, however, I"m also keen to figure out why the while loop is ending when only case 3 inputs are being submitted.

Please note: The console.log() statements are only of a simple means of debugging. I realize a parseInt() would truncate any decimals, but I chose to allow integers as an acceptable size.

Thank you for any advice you can offer :)