예제 #1
0
def main():
    while True:
        user_input = input('>').split(' ')
        if user_input[0].lower() == 'print':
            display()
        elif user_input[0].lower() == 'allocate':
            a = allocate(int(user_input[1]))
            print(a)
        elif user_input[0].lower() == 'free':
            free(int(user_input[1]))
        elif user_input[0].lower() == 'help':
            print(HELP)
        elif user_input[0].lower() == 'exit':
            break
        else:
            print("Type 'help' for additional info.")
예제 #2
0
def idleLoop(random_gen, blocks, chunk_num, WINDOW, player):
    """ Used this to wait for the user input to start time but still picture the level.
    That allows for time to start when the user presses a key rather than when 
    program starts.

    INPUTS: 
            if True, toggles random generation (bool)
            the list of all the blocks
            amount of chunks already loaded
            Window object
            player object

    OUTPUT:
            amount of chunks already loaded
    """
    ready = False  # True when all chunks that should be visible are loaded
    start = False
    while not start:

        for e in pygame.event.get():
            pygame.event.set_allowed(None)
            pygame.event.set_allowed((QUIT, MOUSEBUTTONDOWN, KEYDOWN))
            pygame.event.pump()

        key = pygame.key.get_pressed()

        if key[cfg.KEY_LEFT] or key[cfg.KEY_RIGHT] or key[cfg.KEY_UP]:
            if pygame.time.get_ticks(
            ) / 1000 > 0.5:  # Arbitrary, used to wait for the game to be fully loaded
                start = True

        # Loads the next chunk if needed
        chunkWasLoaded = functions.levelGeneration(random_gen, blocks,
                                                   levels.level, chunk_num)

        if chunkWasLoaded:
            chunk_num += 1
        elif not ready:
            print("ready")
            ready = True

        functions.display(WINDOW, blocks, player)  # Window dispay

    return chunk_num
import functions as func

def completion_time(bt):
    ct = []
    for i in range(len(bt)):
        if i != 0:
            ct.append(bt[i] + ct[i - 1])
        else:
            ct.append(bt[0])
    return ct


if __name__ == "__main__":
    print('Non-Preemptive process')
    print('Criteria:- Arrival Time')
    arrival_time = [0, 1, 2, 3, 4]
    burst_time = [4, 3, 1, 2, 5]
    comp_time = completion_time(burst_time)
    tat = func.turn_around_time(arrival_time, comp_time)
    w_time = func.waiting_time(comp_time, arrival_time, burst_time)
    func.display(arrival_time, burst_time, comp_time, w_time, tat)
예제 #4
0
def main():
    #We set displaying options for Pandas dataframes
    #def set_pandas_options() -> None:
    #    pd.options.display.max_columns = 1000
    #    pd.options.display.max_rows = 1000
    #    pd.options.display.max_colwidth = 100
    #    pd.options.display.width = None
    # pd.options.display.precision = 2  # set as needed
    # set_pandas_options()

    #We load the dataset
    df = loadDataset()
    #display(df)
    dfClean = cleanDataset(df)

    #let's ping all the urls mentioned in the dataset and add the responses to the existing dataset
    #as it's a very slow process we will only do it once, save to a file and usually load the dataframe from that file
    '''
    urlStatusL=[]
    for urlElement in dfClean["url"]:
        urlStatusL.append(pingUrl(urlElement))
    print(urlStatusL) 
    dfCleanWithUrls=dfClean.insert(9,"url_status",urlStatusL,True)
    dfCleanWithUrls.to_csv('dfcleanwithurls.csv')
    '''
    dfCleanWithUrls = pd.read_csv('dfcleanwithurls.csv',
                                  encoding="utf-8",
                                  index_col=0)

    #We keep only those restaurants whose web is valid (the other have closed down and are not still in business)
    dfOnlyExistingRestaurants = dfCleanWithUrls[dfCleanWithUrls["url_status"]
                                                == 200]
    dfWithPriceAndC = dfOnlyExistingRestaurants.copy()

    #We will scrape the Url's for thre minimum price, maximum price and currency of each restaurant
    #Again it's a very slow process, so will onlyt do it once and load from the file.
    '''
    minPriceL=[]
    maxPriceL=[]
    currencyL=[]
    for urlElement in dfWithPriceAndC["url"]:
        minPrice, maxPrice, currency = scrapePrice(urlElement)
        minPriceL.append(minPrice)
        maxPriceL.append(maxPrice)
        currencyL.append(currency)
    print(minPriceL)
    print(maxPriceL)
    print(currencyL)
    dfWithPriceAndC["min_price"]=minPriceL
    dfWithPriceAndC["max_price"]=maxPriceL
    dfWithPriceAndC["currency"]=currencyL
    dfWithPriceAndC.to_csv('dfWithPriceAndC.csv')
    '''
    #we're re-doing the index numbers, as we have removed some rows that had non-existing urls (i.e restaurants out of business).
    dfWithPriceAndC = pd.read_csv('dfWithPriceAndC.csv',
                                  encoding="utf-8",
                                  index_col=0)
    dfWithPriceAndC = dfWithPriceAndC.drop(dfWithPriceAndC.columns[[0]],
                                           axis=1)
    dfWithPriceAndC.reset_index(inplace=True, drop=True)
    #dfWithPriceAndC.to_csv('output.csv',encoding = "utf-8")

    #we fix those currencies that have null values
    dfWithPriceAndCFiltered = fixCurrencies(dfWithPriceAndC)

    #We convert the min and max prices in the dataframe to floats, in order to calculate their corresponding columns in Euros
    fx_pricelist = list(
        map(giveFxrate, list(dfWithPriceAndCFiltered["currency"])))
    dfWithPriceAndCFiltered["fxrate"] = [round(x, 2) for x in fx_pricelist]
    min_pricelist = [
        float(element.replace(",", ""))
        for element in list(dfWithPriceAndCFiltered["min_price"])
    ]
    max_pricelist = []
    for element in list(dfWithPriceAndCFiltered["max_price"]):
        if element is not None and isinstance(element, float) == False:
            max_pricelist.append(float(element.replace(",", "")))
        else:
            max_pricelist.append(element)

    min_eurpricelist = [
        round(a * b, 2) for a, b in zip(min_pricelist, fx_pricelist)
    ]
    max_eurpricelist = [
        round(a * b, 2) for a, b in zip(max_pricelist, fx_pricelist)
    ]

    #We incorporate a min and max price column in Euros
    dfWithPriceAndCFiltered["min_eurprice"] = min_eurpricelist
    dfWithPriceAndCFiltered["max_eurprice"] = max_eurpricelist

    #display(dfWithPriceAndCFiltered)

    selectedCountry = str(sys.argv[1])
    print("selectedCountry is:")
    print(selectedCountry)
    selectedStars = int(sys.argv[2])
    print("selectedStars is:")
    print(selectedStars)
    resultingDf = dfWithPriceAndCFiltered[
        (dfWithPriceAndCFiltered["country"] == selectedCountry)
        & (dfWithPriceAndCFiltered["stars"] == selectedStars)]
    resultingDf = resultingDf.sort_values(by="min_eurprice")
    resultingDf.reset_index(inplace=True, drop=True)
    display(resultingDf.truncate(after=2))
예제 #5
0
import random

data_path = 'exfiles/ex3data1.mat'
data = loadmat(data_path)

X_in = data['X']
y = data['y']


# Fix stupid matlab indexing 
y[y == 10] = 0

# Display 100 randomly chosen numbers
numbers_to_display = 100
display_indices = random.sample(range(5000), numbers_to_display)
display(X_in, display_indices)
# plt.show()

############
# lrCostFunction test found online, identical to ex3.mlx worksheet
############
# test values for the parameters theta
theta_t = np.array([-2, -1, 1, 2], dtype=float)

# test values for the inputs
X_t = np.concatenate([np.ones((5, 1)), np.arange(1, 16).reshape(5, 3, order='F')/10.0], axis=1)

# test values for the labels
y_t = np.array([1, 0, 1, 0, 1])

# test value for the regularization parameter
예제 #6
0
def sendMotorCommands(motorSpeedsIn,
                      displayChannels=False,
                      displayCommands=False):
    global goTime, board, motorEnablePin, go, sineOffset
    motorSpeeds = [0.0] * 9

    # Any motor speeds?
    for i in range(len(motorSpeedsIn)):
        motorSpeeds[i] = motorSpeedsIn[i]
        if motorSpeeds[i] > 1 or motorSpeeds[i] < -1:
            go = True
            goTime = time.time() * 1000

    # Leave disabled unless testing
    if False:
        # Test all motor commands
        sineOffset += 10.0
        motorSpeeds[1] = math.sin(sineOffset / 100.0) * 100.0
        motorSpeeds[2] = math.sin(sineOffset / 100.0) * 100.0
        motorSpeeds[3] = math.sin(sineOffset / 100.0) * 100.0
        motorSpeeds[4] = math.sin(sineOffset / 100.0) * 100.0
        motorSpeeds[5] = math.sin(sineOffset / 100.0) * 100.0
        motorSpeeds[6] = math.sin(sineOffset / 100.0) * 100.0
        motorSpeeds[7] = math.sin(sineOffset / 100.0) * 100.0
        motorSpeeds[8] = math.sin(sineOffset / 100.0) * 100.0

    # Motors been on for two seconds unused?
    if time.time() * 1000 > goTime + 2000:
        go = False

    # Display?
    if displayCommands:
        functions.display("Motors: %3d, %3d, %1f, %1f, %1f, %1f" %
                          (motorSpeeds[1], motorSpeeds[2], motorSpeeds[3],
                           motorSpeeds[4], motorSpeeds[5], motorSpeeds[6]))

    # Send
    middle = 1000.0 + 500.0  #+ 5
    scale = 5.0
    motorSpeeds = clampMotorSpeeds(motorSpeeds)
    channels = [
        int(motorSpeeds[1] * scale + middle),
        int(motorSpeeds[2] * scale + middle),
        int(motorSpeeds[4] * scale +
            middle),  # Why be these flipped, betaflight throttle
        int(motorSpeeds[3] * scale + middle),
        int(motorSpeeds[5] * scale + middle),
        int(motorSpeeds[6] * scale + middle),
        int(motorSpeeds[7] * scale + middle),
        int(motorSpeeds[8] * scale + middle)
    ]
    #if displayChannels:
    functions.display("Channels: " + str(channels))
    try:
        board.sendCMD(16, MultiWii.SET_RAW_RC, channels)
    except Exception as error:
        #        print( "\n" + str(sys.exc_info()[1]) )
        global tries
        if tries < 1:
            initMotors()

    # Set enable pin
    try:
        import RPi.GPIO as GPIO
        if go:
            GPIO.output(motorEnablePin, GPIO.HIGH)
        else:
            GPIO.output(motorEnablePin, GPIO.LOW)
    except:
        pass
예제 #7
0
import os
import platform
import functions
from victory import victory
from bank_account import account_f

while True:
    print(functions.display())
    choice = input('Выберите пункт меню')
    if choice == '1':
        name_of_dir = input("Введите имя папки: ")
        os.mkdir(name_of_dir)
    elif choice == '2':
        functions.remove_file_or_dir()
    elif choice == '3':
        functions.copy_file_or_dir()
    elif choice == '4':
        cwd = os.getcwd()
        print(os.listdir(path=cwd))
    elif choice == '5':
        print(functions.print_dirs())
    elif choice == '6':
        print(functions.print_files())
    elif choice == '7':
        print(platform.uname())
    elif choice == '8':
        print(functions.info_about_creator())
    elif choice == '9':
        victory()
    elif choice == '10':
        account_f()
예제 #8
0
import os
import platform
import functions
from victory import victory
from bank_account import account, exit

while True:
    functions.display()
    choice = input('Выберите пункт меню')
    if choice == '1':
        name_of_dir = input("Введите имя папки: ")
        os.mkdir(name_of_dir)
    elif choice == '2':
        functions.remove_file_or_dir()
    elif choice == '3':
        functions.copy_file_or_dir()
    elif choice == '4':
        cwd = os.getcwd()
        print(os.listdir(path=cwd))
    elif choice == '5':
        functions.print_dirs()
    elif choice == '6':
        functions.print_files()
    elif choice == '7':
        print(platform.uname())
    elif choice == '8':
        functions.info_about_creator()
    elif choice == '9':
        victory()
    elif choice == '10':
        account()
예제 #9
0
파일: motors.py 프로젝트: tjacobs/betabot
def sendMotorCommands(motorSpeedsIn,
                      simulator=None,
                      displayChannels=False,
                      displayCommands=False):
    global goTime, board, motorEnablePin, go, sineOffset
    motorSpeeds = [0.0] * 9

    # Any motor speeds?
    for i in range(len(motorSpeedsIn)):
        motorSpeeds[i] = motorSpeedsIn[i]
        if motorSpeeds[i] > 2 or motorSpeeds[i] < -2:
            # Set used time as now
            #			if go == False:
            #				time.sleep( 2 )
            go = True
            goTime = time.time() * 1000

    # Leave disabled
    if False:
        # Test all motor commands
        sineOffset += 10.0
        motorSpeeds[1] = math.sin(sineOffset / 100.0) * 100.0  # Right hip
        motorSpeeds[2] = math.sin(sineOffset / 100.0) * 100.0  # Left hip
        motorSpeeds[3] = math.sin(
            sineOffset / 100.0) * 100.0  # Right knee servo
        motorSpeeds[4] = math.sin(
            sineOffset / 100.0) * 100.0  # Left knee servo
        motorSpeeds[5] = math.sin(
            sineOffset / 100.0) * 100.0  # Right foot servo
        motorSpeeds[6] = math.sin(
            sineOffset / 100.0) * 100.0  # Left foot servo
        motorSpeeds[7] = math.sin(sineOffset / 100.0) * 100.0  # Unused
        motorSpeeds[8] = math.sin(sineOffset / 100.0) * 100.0  # Unused

    # Motors been on for two seconds unused?
    if time.time() * 1000 > goTime + 2000:
        go = False

    # Display?
    if (displayCommands):
        functions.display("Motors: %3d, %3d, %1f, %1f, %1f, %1f" %
                          (motorSpeeds[1], motorSpeeds[2], motorSpeeds[3],
                           motorSpeeds[4], motorSpeeds[5], motorSpeeds[6]))

    # Send
    middle = 1000.0 + 500.0  #+ 5
    scale = 5.0
    motorSpeeds = clampMotorSpeeds(motorSpeeds)
    channels = [
        int(motorSpeeds[1] * scale + middle),
        int(motorSpeeds[2] * scale + middle),
        int(motorSpeeds[4] * scale +
            middle),  # Why be these flipped, betaflight throttle
        int(motorSpeeds[3] * scale + middle),
        int(motorSpeeds[5] * scale + middle),
        int(motorSpeeds[6] * scale + middle),
        int(motorSpeeds[7] * scale + middle),
        int(motorSpeeds[8] * scale + middle)
    ]
    if (displayChannels):
        functions.display("Channels: " + str(channels))
    try:
        board.sendCMD(16, MultiWii.SET_RAW_RC, channels)
    except Exception as error:
        print("\n" + str(sys.exc_info()[1]))
        initMotors()

    # Set enable pin
    try:
        import RPi.GPIO as GPIO
        if (go):
            GPIO.output(motorEnablePin, GPIO.HIGH)
        else:
            GPIO.output(motorEnablePin, GPIO.LOW)
    except:
        pass

    # Update simulator
    if simulator and simulator.simulator:
        simulator.simulator.simStep(motorSpeeds)
예제 #10
0
 print("You can play Sudoku at the following levels:")
 for i in levelGame:
     print(i, ".", levelGame[i])
 while True:
     print("")
     selc_levGame = input("Please type in the number of your choice:  ")
     if selc_levGame == "1":
         printBoard = True
         while True:
             if printBoard == True:
                 print(" ")
                 print(" Sudoku game: Easy ")
                 print(" ")
                 ## Add this to be a random drawn board
                 grid = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..'
                 display(grid_values_StartingBoard(grid))
             print(" ")
             for i in solutionGame:
                 print(i, ".", solutionGame[i])
             solutionGame_choice = input(
                 "Please type in the number of your choice:  ")
             if solutionGame_choice == "1":
                 display(eliminate(grid_values(grid)))
                 printBoard = False
             elif solutionGame_choice == "2":
                 display(search(grid_values(grid)))
                 printBoard = False
             elif solutionGame_choice == "3":
                 break
             elif solutionGame_choice == "4":
                 exit()
예제 #11
0
def main(random_gen, canLose, player_name):
    """ Main function. Contains the main loop of the game.

    INPUTS: 
            if True, toggles random generation (bool)
            name of the player (str)
    """

    # List of all the Blocks
    blocks = []

    # Init the player
    player = entities.Player.Player()

    # Display Setup
    WINDOW = pygame.display.set_mode((
        cfg.SIZE_X,  # Dimensions of WINDOW
        cfg.SIZE_Y))

    # Time
    CLOCK = pygame.time.Clock()

    # Inits TODO: explain variables
    chunk_num = 1  # 1 because of the init chunk
    prev_chunks_passed = 0

    chunk_times = []
    last_time = 0

    # Loads the first chunk of the map
    functions.loadChunk(blocks, levels.level[0], 0)

    # Idle screen
    # Using this to wait for the user input to start time but still picture the level
    chunk_num = idleLoop(random_gen, blocks, chunk_num, WINDOW, player)

    start_time = pygame.time.get_ticks() / 1000

    # Main loop
    over = False
    while not over:

        CLOCK.tick(20)  # 20 FPS

        for e in pygame.event.get():
            pygame.event.set_allowed(None)
            pygame.event.set_allowed((QUIT, MOUSEBUTTONDOWN, KEYDOWN))
            pygame.event.pump()

            if e.type == pygame.QUIT or (e.type == KEYDOWN and e.key
                                         == K_RETURN):  # quit condition
                over = True

        if player.rect.y + cfg.PLAYER_HEIGHT > cfg.SIZE_Y and canLose:
            over = True

        # Moves the camera if needed
        functions.camera(player, blocks)

        # Moves the player when m1 is on click
        if pygame.mouse.get_pressed()[0]:
            functions.mouse(player)

        # Moves the player
        functions.move(player, blocks)

        # Not very viable but works for that list length
        chunks_passed = 0
        for block in blocks:
            if block.type == "end" and block.rect.x < player.rect.x:
                chunks_passed += 1

        if chunks_passed == prev_chunks_passed + 1:
            current_time = pygame.time.get_ticks() / 1000 - start_time
            print("chunk n°", chunks_passed, ": ", current_time)

            chunk_times.append(round(current_time - last_time, 3))
            last_time = current_time
            prev_chunks_passed += 1

        # Loads the next chunk if needed
        chunkWasLoaded = functions.levelGeneration(random_gen, blocks,
                                                   levels.level, chunk_num)

        if chunkWasLoaded:
            chunk_num += 1

        functions.display(WINDOW, blocks, player)  # Window dispay

    # Displays the score in console
    score, chunks_passed, end_time = functions.score_func(
        current_time, player, blocks)
    print('Chunk nb:', chunks_passed, 'Time:', end_time)
    print('Score:', score)

    # Saving
    filename = os.path.join(cfg.DATA_FOLDER, cfg.DATA_FILE)
    functions.save(filename, player_name, score, chunks_passed, end_time,
                   chunk_times, levels.NB_CHUNK)
예제 #12
0
파일: Sudoku.py 프로젝트: Bahramif/Result
import functions

" Reading an unsolved Sudoku from a CSV file called input.csv consisting of an unsolved Sudoku with 0’s representing blanks"

Test = open("input.csv", 'r')
text = Test.read()
grid = text.replace(',', '')
grid1 = grid.replace('\n', '')
Test.close()


# Solving Sudoku puzzle using Constraint Propagation algorithm
output = functions.display(functions.search(functions.parse_grid(grid1)))


# Convert the final result to CSV format
j = 1
list1 = ''
for i in output:
    if j % 9 != 0:
        list1 = list1 + i + ","
    elif j % 9 == 0:
        list1 = list1 + i + "\n"
    j += 1


# Saving the result in a CSV file called Result.csv
out = open("Result.csv", 'w')
out.write(list1)
out.close()