Jump to content

The under 100 line challenge!

fletch to 99
from gpiozero import LED
import requests
from bs4 import BeautifulSoup
import csv
import os
import time

greenled=LED(4)
redled=LED(26)

def scrape():

   result = requests.get("https://www.pro-football-reference.com/boxscores/")
   src = result.content

   soup = BeautifulSoup(src, 'html.parser')

   length = len(soup.find_all("table"))
   table=soup.find_all("table")


   os.system('clear')
   for i in range(0,length,1):

     league_table=table[i]

     teams=league_table.find_all("tr")


     for team in teams[1:3]:
       stats=team.find_all("td")
       team_name = stats[0].text
       points = stats[1].text

       if team_name=="Buffalo Bills":
          for team in teams[1:10]:
           stats=team.find_all("td")
           if stats[0].text=="Buffalo Bills":
               bills=stats[0].text
               bills_points=stats[1].text
           else:
               opponent=stats[0].text
               opponent_points=stats[1].text

   return bills_points,opponent_points,opponent

def lights():

   bills_points,opp_points,opp=scrape() #pass bills score and opponent score from scrape function

   localtime = time.asctime( time.localtime(time.time()) )
   os.system('clear')
   print("")
   print("Bills:", bills_points)
   print(opp,":", opp_points)
   print("")
    print("As of",localtime)

   #greenled=LED(4)  add back if lights not working correctly using the led as global
   #redled=LED(26)

   if bills_points>opp_points:
       greenled.on()
       redled.off()
   elif bills_points<opp_points:
       greenled.off()
       redled.on()
   else:
       greenled.on()  #score tied
       redled.on()

   time.sleep(30) #timeout for 30 seconds between updates


while True:
  lights()

This is a silly scraper program I wrote while I was learning Python. It is meant to work on a rpi zero w and pulls data from a very simple website using tabular data. It pulls the current score of my favorite NFL team. If the Bills are winning, it will illuminate a green led, if they're losing a red led and if the score is tied, both lights will be activated. It provides an easy visual to check the status. It should be pretty easy to manipulate the code to your favorite team and GPIO pins of your choosing. 😀

Link to comment
Share on other sites

Link to post
Share on other sites

new goal
make a code to predict if user will pass or fail using ai and the following fields

 

print("If answer is yes write 1, if no write 0. If yes or no is not applicable, write the answer based on question. ")
age=int(input("What's the students age::"))
Medu=int(input("Is the mother educated::"))
Fedu=int(input("Is the father educated::"))
traveltime=int(input("For how much time does your ward travel::"))
studytime=int(input("How many hours does your ward study::"))
failures=int(input("How many failures::"))
famrel=int(input("How are the family relations::"))
freetime=int(input("How much free time does your ward get::"))
goout=int(input("How many hours does your ward go out::"))
Dalc=int(input("How much alchohol does the father consume::"))
Walc=int(input("How much alcohol does the mother consume::"))
health=int(input("How is the ward's health::"))
absences=int(input("How many absences::"))
school_GP=int(input("Is the school LPS::"))
school_MS=int(input("Is the school VIVEK::"))
sex_F=int(input("Is the sex Female::"))
sex_M=int(input("Is the sex Male::"))
address_R=int(input("Do you live in a rural area::"))
address_U=int(input("Do you live in an urban area::"))
famsize_GT3=int(input("Are there more then 3 members in your family::"))
famsize_LE3=int(input("Are there less than 3 members in your family::"))
Pstatus_A=int(input("Are the parents apart::"))
Pstatus_T=int(input("Are the parents together::"))
Mjob_at_home=int(input("Does your mother stay at home::"))
Mjob_health=int(input("Does your mother work in health sector"))
Mjob_other=int(input("Does your mother have a job other than staying at home or healthcare or services or teacher::"))
Mjob_services=int(input("Does your mother work in service sector::"))
Mjob_teacher=int(input("Is your mother a teacher::"))
Fjob_at_home=int(input("Does your father stay at home::"))
Fjob_health=int(input("Does your father work in health sector"))
Fjob_other=int(input("Does your father have a job other than staying at home or healthcare or services or teacher::"))
Fjob_services=int(input("Does your father work in service sector::"))
Fjob_teacher=int(input("Is your father a teacher::"))
reason_course=int(input("Was there a particular reason of joining this school::"))
reason_home=int(input("Was the reason that the school was near home::"))
reason_reputation=int(input("Was the reason the school's reputation::"))
reason_other=int(input("Was there some other reason::"))
guardian_father=int(input("Is the guardian father::"))
guardian_mother=int(input("Is the guardian mother::"))
guardian_other=int(input("Do you have some other guardian apart from parents::"))
schoolsup_no=int(input("You dont have education support from school::"))
schoolsup_yes=int(input("You have educational support from school::"))
famsup_no=int(input("The family doesnt support you::"))
famsup_yes=int(input("The family supports you::"))
paid_no=int(input("You dont take extra classes::"))
paid_yes=int(input("You take extra classes::"))
activities_no=int(input("You dont do extra curricular activities::"))
activities_yes=int(input("You do extra curricular activities.::"))
nursery_no=int(input("You didnt attend nursery::"))
nursery_yes=int(input("You attended nursery::"))
higher_no=int(input("You dont want to take higher education::"))
higher_yes=int(input("You want to take higher education::"))
internet_no=int(input("You dont have internet access::"))
internet_yes=int(input("You have internet access::"))
romantic_no=int(input("You are not in a relationship::"))
romantic_yes=int(input("You are in a relationship::"))
sample=[[age, Medu, Fedu, traveltime, studytime, failures, famrel, freetime, 
        goout, Dalc, Walc, health, absences, school_GP, school_MS, sex_F, 
        sex_M, address_R, address_U, famsize_GT3, famsize_LE3, Pstatus_A, Pstatus_T,
        Mjob_at_home, Mjob_health, Mjob_other, Mjob_services, Mjob_teacher,
        Fjob_at_home, Fjob_health, Fjob_other, Fjob_services, Fjob_teacher, 
        reason_course, reason_home, reason_other, reason_reputation,
        guardian_father, guardian_mother, guardian_other, schoolsup_no,
        schoolsup_yes, famsup_no, famsup_yes, paid_no, paid_yes, activities_no,
        activities_yes, nursery_no, nursery_yes, higher_no, higher_yes,
        internet_no, internet_yes, romantic_no, romantic_yes]]
 
if u can find a more efficient way to put forward these questions since with the model i was using there were some problems with acceping string data so every question is yes or no. The model i used was working but the code is 120 lines due to the unacceptance of string data. 
Link to comment
Share on other sites

Link to post
Share on other sites

also i know that i hv done int input so string input wont work but i tried normal string input earlier and that didnt work so...

Link to comment
Share on other sites

Link to post
Share on other sites

On 11/4/2021 at 7:30 AM, steelo said:
from gpiozero import LED
import requests
from bs4 import BeautifulSoup
import csv
import os
import time

greenled=LED(4)
redled=LED(26)

def scrape():

   result = requests.get("https://www.pro-football-reference.com/boxscores/")
   src = result.content

   soup = BeautifulSoup(src, 'html.parser')

   length = len(soup.find_all("table"))
   table=soup.find_all("table")


   os.system('clear')
   for i in range(0,length,1):

     league_table=table[i]

     teams=league_table.find_all("tr")


     for team in teams[1:3]:
       stats=team.find_all("td")
       team_name = stats[0].text
       points = stats[1].text

       if team_name=="Buffalo Bills":
          for team in teams[1:10]:
           stats=team.find_all("td")
           if stats[0].text=="Buffalo Bills":
               bills=stats[0].text
               bills_points=stats[1].text
           else:
               opponent=stats[0].text
               opponent_points=stats[1].text

   return bills_points,opponent_points,opponent

def lights():

   bills_points,opp_points,opp=scrape() #pass bills score and opponent score from scrape function

   localtime = time.asctime( time.localtime(time.time()) )
   os.system('clear')
   print("")
   print("Bills:", bills_points)
   print(opp,":", opp_points)
   print("")
    print("As of",localtime)

   #greenled=LED(4)  add back if lights not working correctly using the led as global
   #redled=LED(26)

   if bills_points>opp_points:
       greenled.on()
       redled.off()
   elif bills_points<opp_points:
       greenled.off()
       redled.on()
   else:
       greenled.on()  #score tied
       redled.on()

   time.sleep(30) #timeout for 30 seconds between updates


while True:
  lights()

This is a silly scraper program I wrote while I was learning Python. It is meant to work on a rpi zero w and pulls data from a very simple website using tabular data. It pulls the current score of my favorite NFL team. If the Bills are winning, it will illuminate a green led, if they're losing a red led and if the score is tied, both lights will be activated. It provides an easy visual to check the status. It should be pretty easy to manipulate the code to your favorite team and GPIO pins of your choosing. 😀

i did something similar. I basically created a code to take the highest rates movies from imdb and go into one of my tv channels providers websites and if any of the movies were coming in the database it would print the date and time to tell when the movie will be showing(this was a time when my ott subscriptions were cut so i had to rely on live TV channels)

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Smyan Narang said:

new goal
make a code to predict if user will pass or fail using ai and the following fields

 

if u can find a more efficient way to put forward these questions since with the model i was using there were some problems with acceping string data so every question is yes or no. The model i used was working but the code is 120 lines due to the unacceptance of string data. 

If that's Python  maybe you should use tkinter or something to make a GUI and use  input boxes, checkboxes and selection lists 

Then store all your questions in a csv file, or a json file or whatever for example 

 

variable name ,  input type  (checkbox for yes/no, true/false , input ) , question text ,  answers , min , max 

 

input type :   'c' = checkbox yes/no  , 't' = text input , 'n' = number input , 'o' = option list / selection list

answers  = for selection list  , enter possible answers  separated by some special character, for example '|'  ex  "Please choose:|Female|Male|I'd rather not say"  and 0 is please choose / nothing selected , 1 is female , 2 is male , 3 is I'd rather not say 

min and max  - minimums  and maximum values allowed  ex for age, say min=1 , max = 100 and report error if number is outside range.  Or min = 1 max = 3 for the selection list above will force user to actually pick something and not leave the selection on the default "Please choose:"

 

So your first few entries above would be something like : 

 

"age" , "n" , "Student age:", "",1,100

"fedu", "c", "Mother is educated","",0,0

"medu" , "c", "Father is educated","",0,0

"traveltime" , "n", "Number of days in a year your ward travels (1..366):","",1,366

"studytime", "n", "Number of hours in a day your ward studies (1..24):", "",1,24

"fjob", "o", "Mother's workplace" , "Please choose:|Healthcare|Financial services|Education (Teacher)|Other", 1,4

"fjob_other", "t", "If Other, please enter mother's job description:", "",0,0

 

Makes it much much easier to add or remove questions, no going in code to add stuff ...  edit questions, correct limits, validate input to some degree, allow user to go back and correct instead of getting bad data... 

 

... so your program can read the csv file line by line and put them in an array and  automatically create the controls (checkbox, selection list etc) on the screen and make some basic validation. Then your program can also use the array to retrieve all the information and dump it to a file in some format you can handle (csv, json, binary dump etc)

Would be super easy to do in PHP or Javascript, to have a FORM tag and populate the form with checkboxes and text inputs and number inputs and selection lists and then when the form is submitted or a button is pressed , the php code or javascript can collect the data and save it as required.

 
Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, mariushm said:

If that's Python  maybe you should use tkinter or something to make a GUI and use  input boxes, checkboxes and selection lists 

Then store all your questions in a csv file, or a json file or whatever for example 

 

variable name ,  input type  (checkbox for yes/no, true/false , input ) , question text ,  answers , min , max 

 

input type :   'c' = checkbox yes/no  , 't' = text input , 'n' = number input , 'o' = option list / selection list

answers  = for selection list  , enter possible answers  separated by some special character, for example '|'  ex  "Please choose:|Female|Male|I'd rather not say"  and 0 is please choose / nothing selected , 1 is female , 2 is male , 3 is I'd rather not say 

min and max  - minimums  and maximum values allowed  ex for age, say min=1 , max = 100 and report error if number is outside range.  Or min = 1 max = 3 for the selection list above will force user to actually pick something and not leave the selection on the default "Please choose:"

 

So your first few entries above would be something like : 

 

"age" , "n" , "Student age:", "",1,100

"fedu", "c", "Mother is educated","",0,0

"medu" , "c", "Father is educated","",0,0

"traveltime" , "n", "Number of days in a year your ward travels (1..366):","",1,366

"studytime", "n", "Number of hours in a day your ward studies (1..24):", "",1,24

"fjob", "o", "Mother's workplace" , "Please choose:|Healthcare|Financial services|Education (Teacher)|Other", 1,4

"fjob_other", "t", "If Other, please enter mother's job description:", "",0,0

 

... so your program can read the csv file line by line and put them in an array and  automatically create the controls (checkbox, selection list etc) on the screen and make some basic validation. Then your program can also use the array to retrieve all the information and dump it to a file in some format you can handle (csv, json, binary dump etc)

Would be super easy to do in PHP or Javascript, to have a FORM tag and populate the form with checkboxes and text inputs and number inputs and selection lists and then when the form is submitted or a button is pressed , the php code or javascript can collect the data and save it as required.

 

i did use tkinter and made a gui and all the questions were stored in a csv file in the final project but this is the root of the project and wanted to make this part right

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, mariushm said:

If that's Python  maybe you should use tkinter or something to make a GUI and use  input boxes, checkboxes and selection lists 

Then store all your questions in a csv file, or a json file or whatever for example 

 

variable name ,  input type  (checkbox for yes/no, true/false , input ) , question text ,  answers , min , max 

 

input type :   'c' = checkbox yes/no  , 't' = text input , 'n' = number input , 'o' = option list / selection list

answers  = for selection list  , enter possible answers  separated by some special character, for example '|'  ex  "Please choose:|Female|Male|I'd rather not say"  and 0 is please choose / nothing selected , 1 is female , 2 is male , 3 is I'd rather not say 

min and max  - minimums  and maximum values allowed  ex for age, say min=1 , max = 100 and report error if number is outside range.  Or min = 1 max = 3 for the selection list above will force user to actually pick something and not leave the selection on the default "Please choose:"

 

So your first few entries above would be something like : 

 

"age" , "n" , "Student age:", "",1,100

"fedu", "c", "Mother is educated","",0,0

"medu" , "c", "Father is educated","",0,0

"traveltime" , "n", "Number of days in a year your ward travels (1..366):","",1,366

"studytime", "n", "Number of hours in a day your ward studies (1..24):", "",1,24

"fjob", "o", "Mother's workplace" , "Please choose:|Healthcare|Financial services|Education (Teacher)|Other", 1,4

"fjob_other", "t", "If Other, please enter mother's job description:", "",0,0

 

Makes it much much easier to add or remove questions, no going in code to add stuff ...  edit questions, correct limits, validate input to some degree, allow user to go back and correct instead of getting bad data... 

 

... so your program can read the csv file line by line and put them in an array and  automatically create the controls (checkbox, selection list etc) on the screen and make some basic validation. Then your program can also use the array to retrieve all the information and dump it to a file in some format you can handle (csv, json, binary dump etc)

Would be super easy to do in PHP or Javascript, to have a FORM tag and populate the form with checkboxes and text inputs and number inputs and selection lists and then when the form is submitted or a button is pressed , the php code or javascript can collect the data and save it as required.

 

but this is really good thanks

Link to comment
Share on other sites

Link to post
Share on other sites

<html>
  <body>
    <a href="https://lttstore.com" padding="30px" background="orange" margin="auto" border-radius="20px">get off of this terrible website</a>
  </body>
</html>

 

please quote me or tag me @wall03 so i can see your response

motherboard buying guide      psu buying guide      pc building guide     privacy guide

ltt meme thread

folding at home stats

 

pc:

 

RAM: 16GB DDR4-3200 CL-16

CPU: AMD Ryzen 5 3600 @ 3.6GHz

SSD: 256GB SP

GPU: Radeon RX 570 8GB OC

OS: Windows 10

Status: Main PC

Cinebench R23 score: 9097 (multi) 1236 (single)

 

don't some things look better when they are lowercase?

-wall03

 

hello dark mode users

goodbye light mode users

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 11/8/2021 at 1:14 AM, Smyan Narang said:

i did something similar. I basically created a code to take the highest rates movies from imdb and go into one of my tv channels providers websites and if any of the movies were coming in the database it would print the date and time to tell when the movie will be showing(this was a time when my ott subscriptions were cut so i had to rely on live TV channels)

I'm very new to web scraping and am finding it's really difficult to understand the layout of web sites and knowing how to consistently pull the correct data when a website updates. I've tinkered with python for about a year and would consider myself to be a beginner-intermediate. Mainly, I'm trying to find useful projects for my rpi's 😁

Link to comment
Share on other sites

Link to post
Share on other sites

On 11/19/2021 at 4:19 AM, steelo said:

I'm very new to web scraping and am finding it's really difficult to understand the layout of web sites and knowing how to consistently pull the correct data when a website updates. 😁

Take a look at css selectors.

Development tools in browsers (F12 or right click -> inspect) can help a lot to find the data you are looking for. Under the console tab there is a fancy live javascript console where you can type code. For example typing in $$("#content .game_summary") will find all elements with the game_summary class inside the #content div.

image.thumb.png.8de3561862f49bc961e725539370f8f6.png

 

The same thing using BeautifulSoup would look like this: soup.select('#content .game_summary')

I hope this helps

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Something that always drives me nuts is when I'm using an interface, and go to click on some part of the menu, but I do it at roughly the same time the program decides to make some change to the interface, and so I end up clicking on some button, option, etc.  It's always irritating, and depending on what the new item I can click on is, the results can be disastrous.

What I've started doing on the sites I work on is to "pause" certain events when I make changes to the interface for a few hundred milliseconds, to give the user time to recognize that the interface has changed.

The way I accomplish this is to attach an event listener to the document itself during the capturing phase (i.e. where the very first event listeners are called) and have it stop propagation and stop default.  I then use setTimeout to remove the handler after a certain period of time.

 

	function disableEvent(event, time){
	  var h = function(e){
	      e.preventDefault();
	      e.stopPropagation();
	      return false;
	  }
	  var ref = document;
	  ref.addEventListener(event, h, true);

	  setTimeout(function(){
	      ref.removeEventListener(event, h, true);
	  }, time);
	}
    
    //Example using it.  Disable the click event for 800ms
    disableEvent('click', 800);
    

Technically it doesn't fully prevent any action from taking place;  if another event listener was added to the document before this one, which also used capturing, then it could still get executed, however this is extremely unlikely since a) most people don't attach event listeners to the document itself, and b) most people don't event listeners with capturing.

 

 

 

 

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Simulate tail -f in the PowerShell:

function tail-f([string]$filename) {
	Get-Content "$filename" -Tail 10 -Wait
}

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 5 months later...

Made this Webscrapper (In Python) for an ecommerce site called Flipkart in my country. It plays you're music when the price of an the item goes below (or equal) a threshold given by the user. Mostly made it for my personal use before a sale.

 

Link

 

86 Lines!

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 months later...
  • 1 month later...

Simple Fahrenheit <-> Celsius converter in Powershell:

function FtoC([double]$fahrenheit) {
    $celsius = ($fahrenheit - 32) * (5/9)
	'{0} °F = {1} °C' -f $fahrenheit,[math]::Round($celsius,3)
}

function CtoF([double]$celsius) {
    $fahrenheit = ($celsius * (9/5)) + 32
	'{0} °C = {1} °F' -f $celsius,[math]::Round($fahrenheit,3)
}

 

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 7 months later...
# returns the number of bits in a size in one of the following units
# unit can be: TB, GB, MB, KB, B
def to_bits(sizeInUnit, unit):
    if unit[1] == 'b':
        if unit[0] == 'T':
            return to_bits(sizeInUnit * 1000, 'Gb')
        if unit[0] == 'G':
            return to_bits(sizeInUnit * 1000, 'Mb')
        if unit[0] == 'M':
            return to_bits(sizeInUnit * 1000, 'Kb')
        if unit[0] == 'K':
            return sizeInUnit * 1000 * 8
    if unit[0] == 'T':
        return to_bits(sizeInUnit * 1024, 'GB')
    if unit[0] == 'G':
        return to_bits(sizeInUnit * 1024, 'MB')
    if unit[0] == 'M':
        return to_bits(sizeInUnit * 1024, 'KB')
    if unit[0] == 'K':
        return sizeInUnit * 1024 * 8
    return -1


# speed = how many bits per second, filesize must in be bits as well
def calculateTime(speed, filesize):
    time = [0 for i in range(4)]  # days, hours, minutes, seconds
    time[3] = filesize // speed
    # get the time to be actually readable
    if time[3] > 60:
        time[2] = time[3] // 60
        time[3] %= 60
    if time[2] > 60:
        time[1] = time[2] // 60
        time[2] %= 60
    if time[1] > 24:
        time[0] = time[1] // 24
        time[1] %= 24

    big = ''
    for i in range(4):
        if time[i] != 0 or i == 3:
            if i == 0:
                big = str(time[i]) + 'd'
            elif i == 1:
                big = str(time[i]) + 'h'
            elif i == 2:
                big = str(time[i]) + 'min'
            elif i == 3:
                big = str(time[i]) + 'sec'
            break

    small = ''
    if i < 3:
        if i == 0:
            small = str(time[i + 1]) + 'h'
        elif i == 1:
            small = str(time[i + 1]) + 'min'
        elif i == 2:
            small = str(time[i + 1]) + 'sec'
    if small != '':
        return big + ' and ' + small
    return big


def checkInput(speed):
    return speed[:-2].isnumeric() and speed[-2] in 'TGMK' and speed[-1] in 'Bb'


while True:
    working = False
    while not working:
        SPEED = input('Please enter your measured downloadspeed \n(example 1: 8MB -> 8megaBytes per second, example 2: 42Kb -> 42 kiloBits per second)\n')
        working = checkInput(SPEED)
        if not working:
            print(f'"{SPEED}" is a wrong input, please try again! (HINT: only whole numbers are supported!)')

    working = False
    while not working:
        SIZE = input('Please enter the size of the file to be downloaded\n(example 1: 42GB -> 42 gigaBytes, example 2: 69 Kb -> 69 kiloBits\n')
        working = checkInput(SIZE)
        if not working:
            print(f'"{SIZE}" is a wrong input, please try again! (HINT: only whole numbers are supported!)')
    print(f'\n\nyour download will take about {calculateTime(to_bits(int(SPEED[:-2]), SPEED[-2] + SPEED[-1]), to_bits(int(SIZE[:-2]), SIZE[-2] + SIZE[-1]))}')

    if input('do you want to do another calculation?(Y|N)\n') not in 'Yy':
        break

 

not pretty, but appears to be working. You enter how much filesize you can download per second and how a big a file you are download is and you get an estimate for download time. The prefix of the unit (G, M, etc.) is always in capital and the B (B/b) indicates wether your unit is in bytes or bits.

Initially i wanted to clean up the code after completing, to get back under 100 lines, but i managed to do so without it (good job, i guess?? should have cleaned the code anyway probably). Hope i made no mistake in the unit conversions.

Link to comment
Share on other sites

Link to post
Share on other sites

This script creates a Firefox headless browser that will tune into a PeerTube live stream if one is available. By default it checks https://jupiter.tube/ (the peertube instance of the guys at Jupiter Broadcasting). This script is not useful for everyone, but it will help the swarm effect that is really needed for a PeerTube stream.

At the time of this post, it is only 63 lines.

 

 
P.S. The repo has instructions to run in docker if anyone is interesting in this little script
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 11/23/2022 at 12:10 AM, Dat Guy said:

Simple Fahrenheit <-> Celsius converter in Powershell

 

As I have dropped Windows at home, I rewrote it in a portable language:

 

COBOL.

 

       IDENTIFICATION DIVISION.
       PROGRAM-ID. cf.

      *> CDDL HEADER
      *> --------------
      *> The contents of this file are subject to the terms of the
      *> Common Development and Distribution License, Version 1.1 only
      *> (the "License").  You may not use this file except in compliance
      *> with the License.
      *>
      *> A copy of the CDDL is available via the Internet at
      *> https://spdx.org/licenses/CDDL-1.1.html
      *>
      *> When distributing Covered Code, include this CDDL HEADER in each
      *> file and include the contents of the LICENSE file from this
      *> distribution.
      *> --------------

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       
      *> We store four variables here:
      *> - input unit (c/C or f/F)
      *> - input value (decimal number)
      *> - formatted input (without leading zeroes)
      *> - output value (without leading zeroes)

       01 input-unit PIC X(1) VALUE SPACES.
       01 input-value PIC S9(10)V999 COMP-3.
       01 input-formatted PIC +ZZ9.99.
       01 output-value PIC +ZZ9.99.

       PROCEDURE DIVISION.
       PERFORM 0000-START.

       0000-USAGE.
           DISPLAY "Usage: cf <source: 'c' or 'f'> <value>."
           STOP RUN.

       0000-START.
           ACCEPT input-unit FROM ARGUMENT-VALUE
           IF input-unit = SPACE OR LOW-VALUES THEN
      *> argv[1] should be C or F, but is not set instead.
      *> argv[2] defaults to 0.0.
               PERFORM 0000-USAGE
           ELSE
      *> Cleanup: trim() input-unit
               INSPECT input-unit REPLACING ALL SPACES BY LOW-VALUES
               MOVE FUNCTION UPPER-CASE(input-unit) to input-unit
           END-IF

           ACCEPT input-value FROM ARGUMENT-VALUE
           MOVE input-value TO input-formatted

           IF input-unit = "C" THEN
               COMPUTE output-value = input-value * (9 / 5) + 32
               DISPLAY input-formatted " °C = " output-value " °F"
           ELSE
               COMPUTE output-value = (input-value - 32) * (5 / 9)
               DISPLAY input-formatted " °F = " output-value " °C"
           END-IF

       STOP RUN.
.

 

Usage:

> cf c 30    # 30 C in F

> cf f 30    # 30 F in C

 

😎

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...
def print_menu():
    print("1. Add Task")
    print("2. View Tasks")
    print("3. Mark Task as Completed")
    print("4. Remove Task")
    print("5. Quit")

def add_task(tasks):
    task_name = input("Enter task name: ")
    tasks[task_name] = False
    print("Task added!")

def view_tasks(tasks):
    print("Tasks:")
    for task, completed in tasks.items():
        status = "Completed" if completed else "Not Completed"
        print(f"- {task} ({status})")

def mark_completed(tasks):
    task_name = input("Enter task name to mark as completed: ")
    if task_name in tasks:
        tasks[task_name] = True
        print("Task marked as completed!")
    else:
        print("Task not found.")

def remove_task(tasks):
    task_name = input("Enter task name to remove: ")
    if task_name in tasks:
        del tasks[task_name]
        print("Task removed!")
    else:
        print("Task not found.")

def main():
    tasks = {}

    while True:
        print_menu()
        choice = input("Select an option: ")

        if choice == "1":
            add_task(tasks)
        elif choice == "2":
            view_tasks(tasks)
        elif choice == "3":
            mark_completed(tasks)
        elif choice == "4":
            remove_task(tasks)
        elif choice == "5":
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Please select a valid option.")

if __name__ == "__main__":
    main()

Simple task management program

Link to comment
Share on other sites

Link to post
Share on other sites

While True do: print (" forum member ")

Lua code.

I like computers. And watching them blow up while playing GTA 5. Remember to update to Windows 11! 😁 

Forum Member

Spoiler

Brroooooo spiders are the only web developers that enjoy finding bugs.

Forum Member Definition:

 

A person who participates on an internet forum. Also called a forumite. So why does the word forumite remind me of a species of mites?

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 months later...

I wanted to make something for those times where I have a list of stuff I need to do something with, and I need to keep track of where I am in the list, while also copying the item in the list to use it. This seemed like something I needed a lot in the past, but never actually used it once I made it (probably due to changing job roles).

 

A list of stuff can be entered in the big box (one item per line), click the button and you get the list to work from. Click a row and it will copy it to your clipboard and cross the item off the list. Click something again and it will uncross it off, to show it still needs to be done, but won't copy it again. I have some memory when writing this of it not working in certain situations (when hosted maybe... but I just tried it with a local file, no server, in Safari and Firefox, as well as hosted on a web server and it all seems to work, so maybe I fixed it and forgot). The reload arrow in the upper right takes you back to the input screen.

 

I had to make the braces kind of ugly for the 100 line limit, but it's 100 exactly.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CopyDo</title>
    <style>
      h1 {
        border-bottom: 1px solid black;
        text-align: center; }
      input[type=text] {
        padding: 6px 5px;
        margin: 4px 0;
        border: 1px solid #ccc;
        border-radius: 4px;
        font-size: 1rem; }
      button {
          padding: 0.5em 1em;
          margin-right: 0.5em;
          background-color: rgb(60,179,113);
          border: none;
          border-radius: 8px;
          color: white; }
      .block-list {
          list-style-type: none;
          padding: 0;
          font-size: 1.5em; }
      .block-list a {
          text-decoration: none;
          display: block;
          padding: .5em;
          color:rgb(22, 22, 22);
          cursor: pointer; }
      .block-list a:hover {
          background-color: rgb(60,179,113);
          color: white; }
      .block-list li{ padding: .5em 0; }
      .pull-right { float: right; }
      #checklist { display: none; }
      #input > textarea {
        display: block;
        margin: 0 auto;
        height: 50vh;
        width: 75vw; }
      #input > button {
        display: block;
        margin: 0 auto;
        width: 75vw;
        height: 4em;
        margin-top: 1em; }
      .done {
        text-decoration: line-through;
        color: lightgray; }
      .copied::after {
        float: right;
        content: "Copied!"; }
      .pointer { cursor: pointer; }
    </style>
</head>
<body>
    <h1>CopyDo<span class="pull-right pointer" onclick="back_to_input()">&circlearrowright;</span></h1>
    <div id="input">
      <textarea id="user_input" placeholder="1. Enter one item per line and click the button.&#10;2. On the resulting screen, as you click to check items off the list.&#10;3. The text will automatically be copied to your clipboard for use."></textarea>
      <button onclick="generate_list()">Do It</button>
    </div>
    <div id="checklist">^</div>
    <script>
        function back_to_input() {
            document.getElementById("checklist").style.display = "none";
            document.getElementById("input").style.display = "block"; }
        function generate_list() {
            const text_input = document.getElementById("user_input").value;
            const text_list = text_input.split(/\r\n|\r|\n/);
            let list_body = "<ul class='block-list'>";
            text_list.forEach( line => {
              const formatted_line = `<a><li>${line}</li></a>`;
              list_body = list_body.concat("\n", formatted_line);
            });
            list_body = list_body.concat("\n", "</ul>");
            document.getElementById("checklist").innerHTML = list_body;
            document.getElementById("input").style.display = "none";
            document.getElementById("checklist").style.display = "block";
            set_event_listeners(); }
        async function copy_text(element) {
          const copyText = element.innerHTML
          navigator.clipboard.writeText(copyText);
          element.classList.toggle("copied"); }
        function set_event_listeners() {
            const li = document.getElementsByTagName("li");
            for (let i = 0; i < li.length; i++) {
              li[i].addEventListener("click", function() {
                const already_done = li[i].className.includes("done");
                li[i].classList.toggle("done");
                if (!already_done) {
                  Array.from(document.querySelectorAll('.copied')).forEach((el) => el.classList.remove('copied'));
                  copy_text(li[i]); } }); } }
    </script>
</body>
</html>

 

Link to comment
Share on other sites

Link to post
Share on other sites

This is a little website I made because my microwave is only 800 watts and most packaged food is tested at 1000 or 1100. This lets me pick the wattage of the directions vs the wattage of my microwave, set the time from the directions, and it tells me how long to cook it. I use this constantly. 94 lines.

 

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Microwave Calculator</title>
  <style>
    form  { display: table;      }
    p     { display: table-row;  }

    .left_col {
      display: table-cell;
      padding-right: 2rem;
    }
    .right_col {
      display: table-cell;
    }

    .time {
      padding-left: .5rem;
    }
  </style>
</head>
<body>
  <h1>Microwave Calculator</h1>

  <form oninput="calculate();">
    <p>
      <label class="left_col" for="from">From:</label>
      <select class="right_col" id="from" name="from">
        <option value="500">500</option>
        <option value="600">600</option>
        <option value="700">700</option>
        <option value="800">800</option>
        <option value="900">900</option>
        <option value="1000" selected>1000</option>
        <option value="1100">1100</option>
        <option value="1200">1200</option>
      </select>
    </p>

    <p>
      <label class="left_col" for="to">To:</label>
      <select class="right_col" id="to" name="to">
        <option value="500">500</option>
        <option value="600">600</option>
        <option value="700">700</option>
        <option value="800" selected>800</option>
        <option value="900">900</option>
        <option value="1000">1000</option>
        <option value="1100">1100</option>
        <option value="1200">1200</option>
      </select>
    </p>

    <p>
      <div class="left_col"><input type="range" id="time" name="time" min="0" max="900" step="15" value="180"></div>
      <label class="right_col time" id="setting" for="time"></label>
    </p>

  </form>
  <br>
  <p id="result"></p>

<script>

  function secondsToTime(e){
    var h = Math.floor(e / 3600).toString().padStart(2,'0'),
        m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
        s = Math.floor(e % 60).toString().padStart(2,'0');

    // return `${h}:${m}:${s}`;
    return `${m}:${s}`;
  }

  function calculate() {
      const from = parseInt(document.getElementById("from").value);
      const to = parseInt(document.getElementById("to").value);
      const total_seconds = parseInt(document.getElementById("time").value);

      const new_total_seconds = total_seconds * (from/to);

      setting
      document.getElementById("setting").innerHTML = `${secondsToTime(total_seconds)}`;
      document.getElementById("result").innerHTML = `
      Set it for <strong>${secondsToTime(new_total_seconds)}</strong>.
      `;
  }

  window.onload = () => calculate();
</script>
</body>
</html>

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 months later...

A python application with GUI that adds image art to .mp3 files
36 lines with comments.

 

EmbedJpgMp3AlbumArt

Voice to text and input to focused window. Option to press enter after input.
54 lines with comments.

 

Voice-to-Text

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×