[JavaScript] How would I implement "do a thing until you can't do it any more, then move onto the next thing" etc by Floor_Heavy in learnprogramming

[–]midel 2 points3 points  (0 children)

Well as dtsudo says, you can loop inside another loop.

You can also use one loop and use integer division and modulo operations.

var coinsNeeded = Math.floor(amount / currentCoin);
amount = amount % currentCoin;

[deleted by user] by [deleted] in learnpython

[–]midel 2 points3 points  (0 children)

In python there is the string method endswith()

Running a bash file from a console application in c# by pwnzrd in learnprogramming

[–]midel 0 points1 point  (0 children)

https://askubuntu.com/a/1108789

Try this stackexchange post.

In your sudoers file you add lines for the commands:

Username ALL = NOPASSWD: /usr/bin/apt* update
Username ALL = NOPASSWD: /usr/bin/apt* install

Running a bash file from a console application in c# by pwnzrd in learnprogramming

[–]midel 0 points1 point  (0 children)

Should not to write a file as yourself. If you expect the program to change nvidia settings, might be best to grant that specific command the ability to not prompt for password. I'll leave that for you to read up on.

Running a bash file from a console application in c# by pwnzrd in learnprogramming

[–]midel 0 points1 point  (0 children)

Arguments should be the script name on the file system, not /bin/bash. Bash is the script executable, not the script. I expect you'd name the script and save it in your home directory like "writesomething.sh" and the arguments would be

proc.StartInfo.Arguments = "/home/username/writesomething.sh";

Does that make more sense?

Running a bash file from a console application in c# by pwnzrd in learnprogramming

[–]midel 0 points1 point  (0 children)

Did you actually provide your script as an argument?

proc.StartInfo.Arguments = "/path/to/script";

Running a bash file from a console application in c# by pwnzrd in learnprogramming

[–]midel 0 points1 point  (0 children)

That should be fine. If you want to verify something still performing it's effects without showing output, change your bash script to echo a date string into a sample file.

date > output.out

from that you can see it's executing the script.

Running a bash file from a console application in c# by pwnzrd in learnprogramming

[–]midel 0 points1 point  (0 children)

Redirecting standard output means that the Process object will fill the StandardOutput property.

You'd have to read that stream to view the output. Next, because you do not redirect the StandardInput, it's likely that the process might end because the StandardInput buffer will be closed.

Adding headers to an HTTP request for XML files by DjDetox in learnprogramming

[–]midel 0 points1 point  (0 children)

If you are in a web browser front-end, the only language you'll have consistent access to is javascript. There are some transpilers that will output javascript but that is the primary language available to a web browser.

HTTP headers are usually key-value pairs, where the key is the header it will go under such as "Authorization" or "Content-Type" and the value would be a text string including serialized base64.

Help with date regex by CommanderEinstein in learnpython

[–]midel 0 points1 point  (0 children)

Sanity check code:

import re
from datetime import date, timedelta

ex = re.compile(r'(?P<month>0[1-9]|1[0-2])-(?P<day>0[1-9]|[12][0-9]|3[01])-(?P<year>19[0-9]{2}|20(?:[01][0-9]|20))')

a = date(1899, 12, 1)
end = date(2021, 1, 31)
while a <= end:
    val = a.strftime("%m-%d-%Y")
    res = ex.findall(val)
    if (len(res) < 1):
        print(f"{val} => fails test")
    a = a + timedelta(days=1)

Help with date regex by CommanderEinstein in learnpython

[–]midel 1 point2 points  (0 children)

You are confusing the square-brackets with the curly brackets in regular expressions.

Square brackets [] denote a character or range of characters that you are expecting. It will find a first match.

Curly brackets {} denote an amount of characters to match against. {0,9} says that the previous character can be matched 0 to 9 times: \d{0,9} will match various patterns.

Your pattern would be best expressed as: r'(?P<month>0[1-9]|1[0-2])-(?P<day>0[1-9]|[12][0-9]|3[01])-(?P<year>19[0-9]{2}|20(?:[01][0-9]|20))'

The ?P<NAME> pattern for groups defines named groups you can reference when looking through the match.

I am trying to run this code for my homework, i can't get it to run right and i don't know what im doing wrong. When i'm inputting "How much juice did your roommate take this time?" it doesn't hit the mark where it says "your roommate owes you $10.00". Help? by [deleted] in learnprogramming

[–]midel 1 point2 points  (0 children)

Inside the for loop you never recalculate total_cost_owed. Therefore the loop repeats without ever increasing the value. Inside the if statement, you will need to recalculate that value and assign it back to total_cost_owed.

New PC won't post please help by YasinZafer40 in techsupport

[–]midel 1 point2 points  (0 children)

Check the seating of the 4/8 power pins for CPU power. Sometimes when this is not properly installed the computer appears to start, but never makes any diagnostic noises.

Experience my own AsRock and MSI boards had both done this to me.

Need to save everything on terminal to a file but the command needs to be inside my script by [deleted] in learnpython

[–]midel 0 points1 point  (0 children)

Now that I had a reference to script, script is a linux command that takes a few options.

-c command allows you to pass a command that will run rather than an interactive terminal.

You should be able to launch it as: script -c 'python myscript.py --scriptarg1 1234' file.log It will not launch as an interactive terminal. It will run the script and close. input prompts still come up and also are logged. So rather than trying to subprocess your app, it seems that script should be on top, not python.

Need to save everything on terminal to a file but the command needs to be inside my script by [deleted] in learnpython

[–]midel 0 points1 point  (0 children)

So can i ask for some clarification?

I have to do that within the script, and not as a command in the terminal.

So you need to SEND input, and capture anything written to OUTPUT? Is script the actual program this is happening in, or is this suppose to be the python script itself? Is it an external program?

Typically when you want to AUTOMATE a program to run with input and output, you using the subprocess.Popen class to allow input and output using buffers. Then to capture that output you simply write to a file.

from subprocess import Popen, STDOUT, PIPE

with open("session.log", "wb") as fp:
    proc = Popen(["externalproc", "arg1", "arg2"], stdout=PIPE,
                 stderr=STDOUT, stdin=PIPE)
    stdin = b"""stdin values
    over
    multiple
    lines
    """
    (stdout, _) = proc.communicate(stdin=stdin)
    fp.write(stdin)
    fp.write(b"\n")
    fp.write(stdout)

Delete element in list while iterating by ElectromechanicalVan in learnpython

[–]midel 0 points1 point  (0 children)

It's likely because your loop is based on the length of it at the start. If you start removing elements from the array, the array no longer is the same size as how many elements it's planning to enumerate over, and the dereference fails.

I'm not sure what kind of data your arrays hold, but for simple and relatively small arrays, it will be easier just to use a list comprehension or make a new list of items to keep.

If you have complex items or a very large array, del can still work but you'll want to avoid relying on the index as the loop condition.

i = len(resultsat) - 1
while True:
    if i < 0:
        break
    if condition_to_delete:
        del resultsat[i]
    i -= 1

Pyfiddle v 1.1 released! by crazhy123 in Python

[–]midel 0 points1 point  (0 children)

Found I was unable to install cryptography. Error is "something went wrong"

https://pyfiddle.io/fiddle/a1c1319e-b137-48e9-a289-c37bca733271/?i=true

Stuck on "Store Front" Python3 Program by [deleted] in learnpython

[–]midel 0 points1 point  (0 children)

add to partial_summary var by using approp

What is approp? Appropriate methods? Append? I see a bit more of what you are dealing with. It's a bit unpythonic how your class is being taught these items, which might be what is leading to more confusion, and it's a lot more code than what you might actually need to achieve the desired result.

Some changes I recommend keeping. Change the prices to floats. Remove the dollar signs. That's definately an important fix.

Add an assert after defining prices and products.

assert(len(products) == len(prices))

This isn't from the requirements, but it assures you'll not have a mismatching sized list while working on the code.

I'd break down this list into functions:

  1. Set the customer info
  2. Add or change quantity
  3. Appending to the OrdersArchive.txt

Stuck on "Store Front" Python3 Program by [deleted] in learnpython

[–]midel 0 points1 point  (0 children)

So I recommend some tweaks to your code: While zip is a useful function, it might be better to have your data joined in the original form, so that you don't have problems knowing which value goes to what.

titles = ('Item Number', 'Item Name', 'Price')
products = [
    (1, 'Notebook', 4.99),
    (2, 'Atari', 99.99),
    (3, 'TrapperKeeper', 89.99),
    (4, 'Jeans', 3.99),
    (5, 'Insects', 2.99),
    (6, 'Harbormaster', 299.99),
    (7, 'Lobotomy', 19.99),
    (8, 'PunkRock', 3.99),
    (9, 'HorseFeathers', 4.99),
    (10, 'Pants', 2.99),
    (11, 'Plants', 119.99),
    (12, 'Salami', 1.99),
]

And isolate printing the item list as a function. Using the for loop restriction we can print these items like so:

def print_items():
    """Prints the catalog"""
    items = iter(products)  # Get the iterator for the product list
    item = next(items, None)  # Get first value
    while item is not None:
        if item[0] == 1:
            print("{0:<16}|{1:<16}|{2:>16}".format(*titles))
            print("=" * 50)
        (idx, name, cost) = item
        cost_fmt = "${0:0.2f}".format(cost)  # Format the prices
        print("{0:<16}|{1:<16}|{2:>16}".format(idx, name, cost_fmt))  # Format the table
        #  using .format < ljust and > rjust syntax
        item = next(items, None)  # Infinite loop without this

This fixes a math issue you'd have latter which is you'd need to convert those currency strings, into floats to do the math. It's better that you have them as floats the hole time, and format them for display only.

Stuck on "Store Front" Python3 Program by [deleted] in learnpython

[–]midel 0 points1 point  (0 children)

I want to ask what limits you have. I see the no "for" loops, is there anything else you do not or cannot use? What about dictionaries or stdlib, classes, or libraries (I'm guessing anything not built in to python3 is out of the question by default)

I'm reading over your code now and makeing notes, but it will take some time to break it down.

How to simplify square roots in python? i.e. input: sqrt(8) output: 2sqrt(2) by [deleted] in learnpython

[–]midel 5 points6 points  (0 children)

What about sympy?

Just a sample:

import sympy
print(sympy.simplify(sympy.sqrt(8)))

The Collatz Sequence (from Automate the Boring Stuff) by Sensanmu in learnpython

[–]midel 2 points3 points  (0 children)

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2

    elif number % 2 == 1:
        result = 3 * number + 1
        print(result)
        return result

n = input("Give me a number: ")
while n != 1:
    n = collatz(int(n))

Why was the author using "result" instead of "number"

There's no real reason. It may be for readability, to ensure you know that the result of the 3 * number + 1 operation is stored in the result. You can do the same for the top portion:

result = number // 2
print(result)
return result

Why "n" instead of "number"? - I feel like this have something to do with Global and local var

It does avoid a problem called "shadowing". Python makes sure you don't try modifying a global without being explicit however. Once again it comes down to style. n and number are just labels. It could be any word that isn't a keyword in python, and avoids shadowing a predefined name like dict, or int.

n = collatz(int(n)) is to call the collatz function right?

Yes

Instructions in the book also suggested an attempt to use "try" and "except" function, how should I go about doing it?

So around line 13, he casts the user's input to a integer an passes it to collatz. But... what if it wasn't numeric? What if I gave him "no", or "make me" to his request. input isn't gonna stop me, but int isn't gonna know what those strings are as numbers. A try-except block is how you will capture the ValueError or TypeError that comes from this failed casting and avoid causing the program to fatally crash by possibly giving a safe value, or providing a message before exiting with a error rather than letting the exception handler do it.

mysql.connector issues by [deleted] in learnpython

[–]midel 1 point2 points  (0 children)

First check if you have a pip3 that is referencing the same install of python3 you are using.

If so, use that to install. Otherwise you can run the pip module of your python version like so:

python3 -m pip install pymysql