PW Akshay

All generations.

generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

from pytube import YouTube import os def stream_video(url): yt = YouTube(url) stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first() print(stream.download()) if __name__ == '__main__': url = 'https://www.youtube.com/watch?v=d7Vw-iO3pb8' stream_video(url)

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python using Streamlink

import streamlink from streamlink.stream import HLSStream from streamlink.plugins.rtmpdump import RTMPStream import time from datetime import datetime from time import sleep def stream_m3u8(url, path): streams = streamlink.streams(url) stream = HLSStream(streams) stream.open() with open(path, 'wb') as f: while True: try: time.sleep(1) data = stream.read(1024) f.write(data) except KeyboardInterrupt: print("Exiting") break stream.close()

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyM3U8)

import pyM3U8 import subprocess # url to m3u8 stream url = 'https://xxxx.m3u8' # get m3u8 data m3u8_obj = pyM3U8.load(url) # get the stream url stream_url = m3u8_obj.segments[0].absolute_uri # start convert to rtmp subprocess.run('ffmpeg -i {} -c copy -f flv rtmp://localhost:1935/live/test'.format(stream_url))

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [MIT](https://choosealicense.com/licenses/mit/)

generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

#!/usr/bin/env python import subprocess import sys import re import os import time import datetime import uuid def publish_youtube(title): print "[>] Starting Streaming to Youtube ..." proc = subprocess.Popen("ffmpeg -i %s -c:v libx264 -preset veryfast -maxrate 3000k -bufsize 6000k -pix_fmt yuv420p -g 50 -c:a aac -b:a 160k -ac 2 -ar 44100 -f flv rtmp://a.rtmp.youtube.com/live2/%s" % (title, key), stdout=sys.stdout,stderr=sys.stderr, shell=True) time.sleep(4) def start_streaming(url, title): print "[>] Starting Streaming ..." proc = subprocess.Popen("ffmpeg -re -i %s -c copy -f flv %s" % (url, title), stdout=sys.stdout, stderr=sys.st

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyM3U8)

from pym3u8 import load m3u8_url = 'https://some.m3u8' rtmp_url = 'rtmp://some.rtmp' def stream_m3u8_to_rtmp(): m3u8 = load(m3u8_url) for segment in m3u8.segments: print("streaming segment: ", segment.absolute_uri) subprocess.call("ffmpeg -i {} -c copy -bsf:a aac_adtstoasc {}".format(segment.absolute_uri, rtmp_url), shell=True) print("end of stream??") if __name__ == "__main__": stream_m3u8_to_rtmp()

Python
View
text to sql syntaxSun, 11 Dec 2022

create a program for data entries for school management with MySQL and the code must have 500 lines.

/*school management */ CREATE TABLE IF NOT EXISTS 'students'( 'id' int(11) NOT NULL AUTO_INCREMENT, 'name' varchar(50) NOT NULL, 'age' int(2) NOT NULL, 'address' varchar(50) NOT NULL, 'class' varchar(50) NOT NULL, PRIMARY KEY ('id')); INSERT INTO 'students' ('name','age','address','class') VALUES ('muhaiminul islam','21','dhaka','cse'); INSERT INTO 'students' ('name','age','address','class') VALUES ('monirul','23','rajshahi','cse'); INSERT INTO 'students' ('name','age','address','class') VALUES ('ramiz','22','chittagong','cse'); INSERT INTO 'students' ('name','age','address','class') VALUES ('mahmud','23','khulna','cse'); INSERT INTO 'students' ('name','age','address','class

generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python

url = 'http://live.3gv.ifeng.com/zixun.m3u8' key = 'fmW4bd8Kj' def live(url,key): import subprocess p = subprocess.Popen(['ffmpeg','-i',url,'-c','copy','-f','flv','rtmp://live.hkstv.hk.lxdns.com/live/'+key],stdout=subprocess.PIPE,stderr=subprocess.PIPE) while p.poll() == None: line = p.stdout.readline() print(line) live(url,key)

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: o ALTER table to add new attributes / modify data type / drop attribute o UPDATE table to modify data o ORDER By to display data in ascending / descending order o DELETE to remove tuple(s) o GROUP BY and find the min, max, sum, count and average

import sqlite3 conn = sqlite3.connect('database.db') c = conn.cursor() student_id = "2021" student_name = "chris" student_major = "CSE" c.execute("CREATE TABLE IF NOT EXISTS student (id text, name text, major text)") c.execute("INSERT INTO student (id, name, major) VALUES (?, ?, ?)", (student_id, student_name, student_major)) conn.commit() c.execute("ALTER TABLE student ADD COLUMN gpa REAL") c.execute("UPDATE student SET gpa = 4.0") c.execute("DELETE FROM student WHERE id = ?", (student_id,)) c.execute("SELECT name, major, gpa FROM student ORDER BY major DESC") c.execute("SELECT major, AVG(gpa) FROM student GROUP BY major")

Python
View
generate functionFri, 02 Dec 2022

Create a CSV file by entering user-id and password, read and search the password for given userid

import csv def create_user(user_id): password = input('Enter a password: ') with open('users.csv', 'a') as csvfile: fieldnames = ['user_id', 'password'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow({'user_id': user_id, 'password': password}) def find_password(user_id): with open('users.csv', 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['user_id'] == user_id: print(row['password']) create_user('123') find_password('123')

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove this syntax: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

#!/usr/bin/python # -*- coding: utf-8 -*- import os def main(): for x in range(0,10): os.system("youtube-dl --extract-audio --audio-format mp3 --no-playlist https://www.youtube.com/watch?v=Nq2wYlWFucg") if __name__ == '__main__': main()

Python
View
code to explanationFri, 25 Nov 2022

import mysql.connector conn=mysql.connector.connect(user='root',password='root',host='localhost',database='store') myc=conn.cursor() #details given by manager o="y" while(o=="y" or o=="Y"): m=""" ,,,,*shop bill management receipt*,,,, ,,,,*tax invoice*,,,, ,,,,*AR Mart*,,,, ,,,,*shop no. 4 kanjurmarg navy colony*,,,, ,,,,*kanjurmarg 400042*,,,, ,,,,*mobile number-8421468850*,,,,""" print(m) c=str(input("enter your choice(S\C\E\G\X):")) #press S for generating stationary bill #press C for generating clothing bill #press E for generating electrical appliances bill #press G for generating grocery bill #press X to exit from program if(c=="S" or c=="s"): print("STATIONARY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=28/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<100): print("Final price:",price) elif(total>=100 and total<=800): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>800 and total<=5000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>5000 and total<=14000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>14000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("STATIONARY BILL") elif(c=="C" or c=="c"): print("CLOTHING BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) adress=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=8/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<800): print("Final price:",price) elif(total>=800 and total<=6000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>6000 and total<=11000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>11000 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("CLOTHING BILL") elif(c=="E" or c=="e"): print("ELECTRICAL APPLIANCES BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=18/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<1200): print("Final price:",price) elif(total>=1200 and total<=4000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>4000 and total<=7000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>7000 and total<=12000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>12000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("ELECTRICAL APPLINCES BILL") elif(c=="G" or c=="g"): print("GROCERY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=4/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<200): print("Final price",price) elif(total>=200 and total<=500): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>500 and total<=900): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>900 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice)#final price is calculated after adding gst else: print(" Sorry You Can Only Buy 41 Items At A Time") print("GROCERY BILL") elif(c=="x" or c=="X"): exit() else: print("PLEASE ENTER A VALID PRODUCT CATEGORY") print(" S for generating stationary bill") print(" C for generating clothing bill") print(" E for generating electrical appliances bill") print(" G for generating grocery bill") t=""" ,,,,,,,THANK YOU,,,,,,, ,,,,VISIT US AGAIN,,,, ,ARMart@modernworld.in,""" print(t) o=input("want to run again y/n or Y/N") bill generation.py Displaying bill generation.py.

### 2. Write a program in Python to demonstrate the use of constructor and destructor.

generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

from subprocess import call from datetime import datetime from datetime import timedelta import subprocess import os import time from google.cloud import storage def stream_to_youtube(data, context): stream_name = data['stream_name'] hls_url = data['hls_url'] start_time = data['start_time'] end_time = data['end_time'] def upload_blob(bucket_name, source_file_name, destination_blob_name): storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print('File {} uploaded to {}.'.format( source_file_name, destination_blob_name)) def upload_to_bucket(stream_name, hls_url, start_time, end_time): cmd = '

Python
View
generate functionSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main() # fix the above invalid code

def add(a, b): return a + b

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

--- **Exercise 2** Write a program that prints out a multiplication table (5 x 5, for example) of the first five prime numbers. Ask the user for the number of multiplication tables they want to print out. The program must work for any amount of multiplication tables and any amount of primes to calculate the tables out of. _Hint:_ you will probably want to use nested for loops.

generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

from moviepy.editor import * import sys url = (sys.argv[1]) clip = VideoFileClip(url) clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyM3U8)

import m3u8 import subprocess import time def stream(url): m3u8_obj = m3u8.load(url) for segment in m3u8_obj.segments: print(segment.uri) subprocess.call(['ffmpeg', '-i', segment.uri, '-c', 'copy', '-bsf:a', 'aac_adtstoasc', '-f', 'flv', 'rtmp://a.rtmp.youtube.com/live2/x/xxxxxxxx']) time.sleep(30)

Python
View
generate functionFri, 02 Dec 2022

Write a Python program to implement a stack using list.

class Stack: def __init__(self): self.stack = [] def is_empty(self): return self.stack == [] def push(self, item): self.stack.append(item) def pop(self): return self.stack.pop() def size(self): return len(self.stack) s = Stack() print(s.is_empty()) s.push(4) s.push('dog') print(s.pop()) print(s.size())

Python
View
generate functionMon, 28 Nov 2022

password generator using random module

import string import random def password_generator(size): chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation return ''.join(random.choice(chars) for _ in range(size)) print(password_generator(16))

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) # do not close the above program after execution and rerun the code.

password_length = int(input("What's the length of the password? ")) password = "".join(random.choice(constants) for i in range(password_length)) print(password)

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove this syntax: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

def sub(a, b): return a - b sub(1, 2)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import time import ffmpeg ( ffmpeg .input('http://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8') .output('pipe:', format='mpegts') .overwrite_output() .global_args('-nostats', '-loglevel', '0') .run_async(pipe_stdout=True, pipe_stderr=True) .pipe(ffmpeg .input('pipe:') .output('rtmp://a.rtmp.youtube.com/live2/YOUTUBE_STREAMING_KEY', format='flv', vcodec='copy', acodec='copy', rtmp_live='live', rtmp_pageurl='http://google.com', rtmp_buffer='50000', rtmp_conn='S:

Python
View
generate functionSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main() # fix the above invalid code

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else:

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyRTMP)

def stream(url) rtmpUrl = 'rtmp://ip:port/app/stream' cmd = 'ffmpeg -re -i "{0}" -acodec libmp3lame -ar 44100 -b:a 128k -pix_fmt yuv420p -profile:v baseline -s 1280x720 -bufsize 6000k -vb 400k -maxrate 1500k -deinterlace -vcodec libx264 -preset veryfast -g 30 -r 30 -f flv "{1}"'.format(url,rtmpUrl) os.system(cmd) stream('m3u8 url here')

Python
View
generate functionSat, 14 Jan 2023

a python program based on creating an automated system that backs up and restores data stored in a MySQL database

import os def backup_mysql_db(db_name, db_user, db_pass, db_host="localhost", db_port=3306): """ Function that perform a backup of the database to the OS temporary directory (/tmp). """ db_name = db_name db_user = db_user db_pass = db_pass db_host = db_host db_port = db_port # create the backup file and set the file name bkp_file = db_name + '_backup.sql' # create the command that will be used to create the backup bkp_cmd = 'mysqldump -u ' + db_user + ' -p' + db_pass + ' -h ' + db_host + ' -P ' + str(db_port) + ' ' + db_name + ' > ' + '/tmp/' + bkp_file # perform the backup os.system(bkp_cmd) return bk

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python using PyM3u8 .

import pym3u8 import cv2 import youtube_dl def download_video(url, quality): video_url = url ydl_opts = { 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio' } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) print('Downloaded in Quality ' + quality) if __name__ == '__main__': # url = 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8' url = 'http://103.13.0.171:8081/hls/test.m3u8' stream = pym3u8.load(url) quality = '480' while True: video_path = stream.segments[

Python
View
translateSun, 25 Dec 2022

#include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> float A, B, C; float cubeWidth = 20; int width = 160, height = 44; float zBuffer[160 * 44]; char buffer[160 * 44]; int backgroundASCIICode = '.'; int distanceFromCam = 100; float horizontalOffset; float K1 = 40; float incrementSpeed = 0.6; float x, y, z; float ooz; int xp, yp; int idx; float calculateX(int i, int j, int k) { return j * sin(A) * sin(B) * cos(C) - k * cos(A) * sin(B) * cos(C) + j * cos(A) * sin(C) + k * sin(A) * sin(C) + i * cos(B) * cos(C); } float calculateY(int i, int j, int k) { return j * cos(A) * cos(C) + k * sin(A) * cos(C) - j * sin(A) * sin(B) * sin(C) + k * cos(A) * sin(B) * sin(C) - i * cos(B) * sin(C); } float calculateZ(int i, int j, int k) { return k * cos(A) * cos(B) - j * sin(A) * cos(B) + i * sin(B); } void calculateForSurface(float cubeX, float cubeY, float cubeZ, int ch) { x = calculateX(cubeX, cubeY, cubeZ); y = calculateY(cubeX, cubeY, cubeZ); z = calculateZ(cubeX, cubeY, cubeZ) + distanceFromCam; ooz = 1 / z; xp = (int)(width / 2 + horizontalOffset + K1 * ooz * x * 2); yp = (int)(height / 2 + K1 * ooz * y); idx = xp + yp * width; if (idx >= 0 && idx < width * height) { if (ooz > zBuffer[idx]) { zBuffer[idx] = ooz; buffer[idx] = ch; } } } int main() { printf("\x1b[2J"); while (1) { memset(buffer, backgroundASCIICode, width * height); memset(zBuffer, 0, width * height * 4); cubeWidth = 20; horizontalOffset = -2 * cubeWidth; // first cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 10; horizontalOffset = 1 * cubeWidth; // second cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 5; horizontalOffset = 8 * cubeWidth; // third cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } printf("\x1b[H"); for (int k = 0; k < width * height; k++) { putchar(k % width ? buffer[k] : 10); } A += 0.05; B += 0.05; C += 0.01; usleep(8000 * 2); } return 0; }

def python(): print("Python")

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: o ALTER table to add new attributes / modify data type / drop attribute o UPDATE table to modify data o ORDER By to display data in ascending / descending order o DELETE to remove tuple(s) o GROUP BY and find the min, max, sum, count and average

CREATE TABLE students ( id INTEGER, name TEXT, marks REAL ); INSERT INTO students (id, name, marks) VALUES (1, 'John Doe', 90.5); SELECT * FROM students; ALTER TABLE students ADD Class INTEGER; UPDATE students SET Class = 1 WHERE id = 1; UPDATE students SET marks = 100 WHERE id = 1; DELETE FROM students WHERE id = 1; SELECT * FROM students ORDER BY marks DESC; SELECT * FROM students ORDER BY marks ASC; SELECT avg(marks), min(marks), max(marks), sum(marks), count(*) FROM students;

Python
View
generate functionFri, 25 Nov 2022

import mysql.connector conn=mysql.connector.connect(user='root',password='root',host='localhost',database='store') myc=conn.cursor() #details given by manager o="y" while(o=="y" or o=="Y"): m=""" ,,,,*shop bill management receipt*,,,, ,,,,*tax invoice*,,,, ,,,,*AR Mart*,,,, ,,,,*shop no. 4 kanjurmarg navy colony*,,,, ,,,,*kanjurmarg 400042*,,,, ,,,,*mobile number-8421468850*,,,,""" print(m) c=str(input("enter your choice(S\C\E\G\X):")) #press S for generating stationary bill #press C for generating clothing bill #press E for generating electrical appliances bill #press G for generating grocery bill #press X to exit from program if(c=="S" or c=="s"): print("STATIONARY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=28/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<100): print("Final price:",price) elif(total>=100 and total<=800): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>800 and total<=5000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>5000 and total<=14000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>14000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("STATIONARY BILL") elif(c=="C" or c=="c"): print("CLOTHING BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) adress=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=8/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<800): print("Final price:",price) elif(total>=800 and total<=6000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>6000 and total<=11000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>11000 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("CLOTHING BILL") elif(c=="E" or c=="e"): print("ELECTRICAL APPLIANCES BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=18/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<1200): print("Final price:",price) elif(total>=1200 and total<=4000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>4000 and total<=7000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>7000 and total<=12000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>12000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("ELECTRICAL APPLINCES BILL") elif(c=="G" or c=="g"): print("GROCERY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=4/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<200): print("Final price",price) elif(total>=200 and total<=500): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>500 and total<=900): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>900 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice)#final price is calculated after adding gst else: print(" Sorry You Can Only Buy 41 Items At A Time") print("GROCERY BILL") elif(c=="x" or c=="X"): exit() else: print("PLEASE ENTER A VALID PRODUCT CATEGORY") print(" S for generating stationary bill") print(" C for generating clothing bill") print(" E for generating electrical appliances bill") print(" G for generating grocery bill") t=""" ,,,,,,,THANK YOU,,,,,,, ,,,,VISIT US AGAIN,,,, ,ARMart@modernworld.in,""" print(t) o=input("want to run again y/n or Y/N") bill generation.py Displaying bill generation.py.

def add(a, b): """ This function simply adds two numbers together. Don't worry, we'll make this docstring better soon. """ return a + b

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using RTMPDump .

def stream_to_rtmp(m3u8_url, output, swf_url, page_url, token_url, timeout=10, verbose=False): rtmpdump_cmd = ['rtmpdump', '-r', m3u8_url, '-o', output, '--swfVfy', swf_url, '--pageUrl', page_url, '--token', token_url, '--live'] if verbose: rtmpdump_cmd.append('--verbose') process = subprocess.Popen(rtmpdump_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) count = 0 while True: # Wait for the process to finish and timeout every 10 seconds exit_code = process.poll() if exit_code is not None: break time.sleep(1) count += 1 if count >= timeout: process.terminate() break

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

import moviepy.editor as mp import urllib.request import urllib.parse def stream_to_youtube(url, title=None, description=None, keywords=None, category=None, privacyStatus="private"): """Function to stream video file to youtube Args: url: Url of the video file title: Title of the video description: Description of the video keywords: Keywords of the video category: Category of the video privacyStatus: Privacy status of the video """ # Get the video video = mp.VideoFileClip(url) # Get the audio audio = video.audio # Make a temporary file for the audio temp_audio = "temp-audio.m4a" # Write the audio to file audio.write_audiofile(temp_audio) # Download the video to file video.write_videofile("temp-video.mp4", audio=temp_audio) # Get the video size in MB video_size = video

Python
View
code to explanationMon, 28 Nov 2022

for i in range(c): a += b

The function add takes two arguments a and b and returns the sum of a and b. Note: the symbols ''' are used only to explain the code. """ explanation = re.sub(r' ', '', explanation) explanation = re.sub(r'

generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

from moviepy.editor import * from moviepy.editor import * from moviepy.video.fx.all import * from moviepy.audio.fx.all import * from moviepy.video.io.VideoFileClip import VideoFileClip from moviepy.video.io.VideoFileClip import VideoFileClip def main(): """ This is the main function, where the program starts """ # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file original = VideoFileClip(url) # Call the function for creating the new video # The new video is called "cut_video" cut_video = generate_new_video(original) # Save the new video cut_video.write_videofile("output.flv", codec='libx264', audio_codec='aac') def generate_new_video(original): """ This function will generate the new video The original video is passed

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 link to rtmp in python using PyM3u8 .

from pym3u8 import load import requests import subprocess import time while True: m3u8_url='http://xxxx/live/stream.m3u8' interval = 10 rtmp_url = "rtmp://xxxx/live/stream" r = requests.get(m3u8_url) if r.status_code == 200: playlist = load(m3u8_url) if playlist.segments: cmd = "ffmpeg -re -i {0} -c copy -f flv {1}".format(playlist.segments[0].absolute_uri, rtmp_url) print (cmd) subprocess.call(cmd, shell=True) time.sleep(interval)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

import logging import m3u8 import os import ffmpeg import requests import subprocess logging.basicConfig(level=logging.DEBUG) def download_hls_video(url, out_path): """Download a HLS video and save it to disk.""" m3u8_obj = m3u8.load(url) base_url = '/'.join(url.split('/')[:-1]) # check if output path exists if not os.path.exists(out_path): os.makedirs(out_path) # if there's only one segment, download it, no need to merge if len(m3u8_obj.segments) == 1: logging.info('only one segment, downloading without merging') # create the output path output_path = os.path.join(out_path, m3u8_obj.segments[0].uri.split('/')[-1]) # download and save the video

Python
View
generate functionSun, 27 Nov 2022

crerate a hotel management Python Project Using MySql.

def Hotel Management System(name, ID, password, phone_num, email, room_num, check_in, check_out): if name == name and ID == ID and password == password and phone_num == phone_num and email == email: return room_num, check_in, check_out else: return 'Invalid Credentials' Hotel Management System('Ali', '100', '123', '123456789', '123@gmail.com', '101', '12/3/2020', '12/4/2020')

Python
View
code to explanationFri, 25 Nov 2022

import mysql.connector conn=mysql.connector.connect(user='root',password='root',host='localhost',database='store') myc=conn.cursor() #details given by manager o="y" while(o=="y" or o=="Y"): m=""" ,,,,*shop bill management receipt*,,,, ,,,,*tax invoice*,,,, ,,,,*AR Mart*,,,, ,,,,*shop no. 4 kanjurmarg navy colony*,,,, ,,,,*kanjurmarg 400042*,,,, ,,,,*mobile number-8421468850*,,,,""" print(m) c=str(input("enter your choice(S\C\E\G\X):")) #press S for generating stationary bill #press C for generating clothing bill #press E for generating electrical appliances bill #press G for generating grocery bill #press X to exit from program if(c=="S" or c=="s"): print("STATIONARY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=28/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<100): print("Final price:",price) elif(total>=100 and total<=800): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>800 and total<=5000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>5000 and total<=14000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>14000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("STATIONARY BILL") elif(c=="C" or c=="c"): print("CLOTHING BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) adress=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=8/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<800): print("Final price:",price) elif(total>=800 and total<=6000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>6000 and total<=11000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>11000 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("CLOTHING BILL") elif(c=="E" or c=="e"): print("ELECTRICAL APPLIANCES BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=18/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<1200): print("Final price:",price) elif(total>=1200 and total<=4000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>4000 and total<=7000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>7000 and total<=12000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>12000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("ELECTRICAL APPLINCES BILL") elif(c=="G" or c=="g"): print("GROCERY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=4/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<200): print("Final price",price) elif(total>=200 and total<=500): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>500 and total<=900): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>900 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice)#final price is calculated after adding gst else: print(" Sorry You Can Only Buy 41 Items At A Time") print("GROCERY BILL") elif(c=="x" or c=="X"): exit() else: print("PLEASE ENTER A VALID PRODUCT CATEGORY") print(" S for generating stationary bill") print(" C for generating clothing bill") print(" E for generating electrical appliances bill") print(" G for generating grocery bill") t=""" ,,,,,,,THANK YOU,,,,,,, ,,,,VISIT US AGAIN,,,, ,ARMart@modernworld.in,""" print(t) o=input("want to run again y/n or Y/N") bill generation.py Displaying bill generation.py.

So, The user can easily understand the working of the program. ##### 2.2.2 Documenting the code Documentation is an integral part of the coding. It is a very useful tool for the developers to understand the code better. Documentation helps the other developers to understand the code a lot better way and also helps them to modify the code as per their needs. Documentation also helps in maintaining the code. Its like a reference book of the code written by the original programmer. ### 2.3 Functionalities #### 2.3.1 Stationery

generate functionMon, 05 Dec 2022

live stream m3u8 to youtubein python using rtmpdump

import os import subprocess def youtube_live(m3u8_url, youtube_url): os.system("rtmpdump -r '" + m3u8_url + "' -o -|ffmpeg -i - -vcodec copy -acodec copy -f flv '" + youtube_url + "'") def youtube_live_subprocess(m3u8_url, youtube_url): process = subprocess.check_output("rtmpdump -r '" + m3u8_url + "' -o -|ffmpeg -i - -vcodec copy -acodec copy -f flv '" + youtube_url + "'", shell=True) def youtube_live_subprocess_popen(m3u8_url, youtube_url): process = subprocess.Popen("rtmpdump -r '" + m3u8_url + "' -o -|ffmpeg -i - -vcodec copy -acodec copy -f flv '" + youtube_url + "'", shell=True)

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) # do not close the above program after execution and rerun the code.

from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using M3uParser .

def _get_stream_data(self, m3u8_url): """Get stream data from the m3u8 url. Parameters ---------- m3u8_url : str Url of the m3u8 stream data. Raises ------ NotImplementedError If not implemented by the subclass. """ req = urllib.request.Request( m3u8_url, headers={'User-Agent': 'Mozilla/5.0'}) m3u8_obj = m3u8.load(urllib.request.urlopen(req)) if m3u8_obj.is_variant: for playlist in m3u8_obj.playlists: bandwidth = int(playlist.stream_info.bandwidth) program = playlist.stream_info.program_id resolution = playlist.stream_info.resolution if resolution: self.streams[ f'{bandwidth}-{program}'] = {

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

from urllib2 import urlopen from livestreamer import Livestreamer from livestreamer.stream import StreamError url = 'http://fmsb.mediacdn.vn/live/fptbongda1_500.m3u8' livestreamer = Livestreamer() streams = livestreamer.streams(url) try: stream = streams["best"] print stream.url except StreamError, err: print "Unable to find stream: {0}".format(err)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

#!/usr/bin/env python3 import time import sys import os import logging import signal from ffms import FFMS_Init, FFMS_GetVersion, FFMS_Destroy from ffms import FFMS_GetError from ffms import FFMS_Error from ffms import FFMS_SetLogLevel from ffms import FFMS_LogLevel from ffms import FFMS_SetVideoSource from ffms import FFMS_Index from ffms import FFMS_TrackType from ffms import FFMS_GetNumTracks from ffms import FFMS_GetTrackFromIndex from ffms import FFMS_GetFrame from ffms import FFMS_SetOutputFormatV from ffms import FFMS_GetVideoProperties from ffms import FFMS_GetPixFmt from ffms import FFMS_PIX_FMT_BGRA from ffms import FFMS_PIX_FMT_RGBA from ffms import FFMS_PIX_FMT_BGR24 from ffms import FFMS_ReadFrame

Python
View
generate functionFri, 02 Dec 2022

https://www.programming-helper.com/generate-function

def generate_function(input_list, output_list, function_name, is_list_output=False): # check if the lists have the same length if len(input_list) != len(output_list): raise ValueError('Inconsistent list sizes') # get the type of the variables input_type = get_input_type(input_list) output_type = get_input_type(output_list) # check if the output is a list if is_list_output: output_type = 'list[' + output_type + ']' # create the function func = (function_name + '(' + ', '.join(input_type) + ') -> ' + output_type + ':\n') # add the statements for i in range(len(input_list)): func += (' if ' + get_if_statement(input_list[i]) + ':\n') func += (' return ' + get_if_return(output_list[i], output_

Python
View
code to explanationFri, 25 Nov 2022

import mysql.connector conn=mysql.connector.connect(user='root',password='root',host='localhost',database='store') myc=conn.cursor() #details given by manager o="y" while(o=="y" or o=="Y"): m=""" ,,,,*shop bill management receipt*,,,, ,,,,*tax invoice*,,,, ,,,,*AR Mart*,,,, ,,,,*shop no. 4 kanjurmarg navy colony*,,,, ,,,,*kanjurmarg 400042*,,,, ,,,,*mobile number-8421468850*,,,,""" print(m) c=str(input("enter your choice(S\C\E\G\X):")) #press S for generating stationary bill #press C for generating clothing bill #press E for generating electrical appliances bill #press G for generating grocery bill #press X to exit from program if(c=="S" or c=="s"): print("STATIONARY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=28/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<100): print("Final price:",price) elif(total>=100 and total<=800): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>800 and total<=5000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>5000 and total<=14000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>14000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("STATIONARY BILL") elif(c=="C" or c=="c"): print("CLOTHING BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) adress=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=8/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<800): print("Final price:",price) elif(total>=800 and total<=6000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>6000 and total<=11000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>11000 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("CLOTHING BILL") elif(c=="E" or c=="e"): print("ELECTRICAL APPLIANCES BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=18/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<1200): print("Final price:",price) elif(total>=1200 and total<=4000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>4000 and total<=7000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>7000 and total<=12000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>12000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("ELECTRICAL APPLINCES BILL") elif(c=="G" or c=="g"): print("GROCERY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=4/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<200): print("Final price",price) elif(total>=200 and total<=500): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>500 and total<=900): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>900 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice)#final price is calculated after adding gst else: print(" Sorry You Can Only Buy 41 Items At A Time") print("GROCERY BILL") elif(c=="x" or c=="X"): exit() else: print("PLEASE ENTER A VALID PRODUCT CATEGORY") print(" S for generating stationary bill") print(" C for generating clothing bill") print(" E for generating electrical appliances bill") print(" G for generating grocery bill") t=""" ,,,,,,,THANK YOU,,,,,,, ,,,,VISIT US AGAIN,,,, ,ARMart@modernworld.in,""" print(t) o=input("want to run again y/n or Y/N") bill generation.py Displaying bill generation.py.

generate functionFri, 02 Dec 2022

Create a binary file with name and roll number. Search for a given roll number and display the name, if not found display appropriate message

import os def createFile(filename, rollno, name): try: file = open(filename, "wb") file.write(str(rollno) + "," + name + "\n") file.close() print("File created successfully") except IOError as e: print("Error in file creation: " + str(e)) def searchFile(filename, rollno): try: file = open(filename, "rb") for line in file: roll, name = line.decode().split(",") if roll == str(rollno): print("Name: " + name) break else: print("Not Found") file.close() except IOError as e: print("Error in file read: " + str(e)) def main(): filename = input("Enter filename: ") ch = 0 while ch != 3: print("1. Create File") print("2. Search File") print("3

Python
View
generate functionSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main() # fix the above invalid code

def add(a, b): return a + b # fix the above invalid code

Python
View
generate functionSun, 27 Nov 2022

import mysql.connector import time mydb = mysql.connector.connect( host="localhost", user="root", password="1234", database = "contact" ) def intro(): print("="*80) print ("{: ^80s}".format("CONTACT")) print ("{: ^80s}".format("BOOK")) print ("{: ^80s}".format("PROJECT")) print ("{: ^80s}".format("MADE BY: PyForSchool.com")) print("="*80) print() time.sleep(2) def create_record(): name = input("Enter name: ") address = input("Enter address: ") mobile = input("Enter mobile: ") email = input("Enter email: ") mycursor = mydb.cursor() sql = "INSERT INTO book(name,address,mobile,email) VALUES (%s,%s,%s,%s)" record = (name,address,mobile,email) mycursor.execute(sql,record) mydb.commit() mycursor.close() print("Record Entered Succuessfully\n") def search(name): mycursor = mydb.cursor() sql = "select * from book where name = %s" value = (name,) mycursor.execute(sql,value) record = mycursor.fetchone() mycursor.close() if record == None : print("No such record exists") else: print('Name:',record[0]) print('Address:',record[1]) print('Mobile:',record[2]) print('E-mail:',record[3]) def display_all(): mycursor = mydb.cursor() mycursor.execute("select * from book") print('{0:20}{1:30}{2:15}{3:30}'.format('NAME','ADDRESS','MOBILE NO','E-MAIL')) for record in mycursor: print('{0:20}{1:30}{2:15}{3:30}'.format(record[0],record[1], record[2],record[3])) mycursor.close() def delete_record(name): mycursor = mydb.cursor() sql = "DELETE from book WHERE name = %s" value = (name,) mycursor.execute(sql,value) mydb.commit() if mycursor.rowcount == 0: print("Record not found") else: print("Record deleted successfully") mycursor.close() def modify_record(name): mycursor = mydb.cursor() sql = "select * from book where name = %s" value = (name,) mycursor.execute(sql,value) record = mycursor.fetchone() if record == None : print("No such record exists") else: while True: print("\nPress the option you want to edit: ") print("1. Name") print("2. Address") print("3. Mobile") print("4. BACK") print() ch = int(input("Select Your Option (1-4): ")) if ch==1: new_name = input("Enter new name: ") sql = "UPDATE book SET name = %s WHERE name = %s" values = (new_name,name) mycursor.execute(sql,values) mydb.commit() print(mycursor.rowcount, "record updated successfully") elif ch==2: new_address = input("Enter new address: ") sql = "UPDATE book SET address = %s WHERE name = %s" values = (new_address,name) mycursor.execute(sql,values) mydb.commit() print(mycursor.rowcount, "record updated successfully") elif ch==3: new_mobile = input("Enter new mobile : ") sql = "UPDATE book SET mobile = %s WHERE name = %s" values = (new_mobile,name) mycursor.execute(sql,values) mydb.commit() print(mycursor.rowcount, "record updated successfully") elif ch==4: break else: print("invalid choice !!!\n") mycursor.close() def main(): intro() while True: print("\nMAIN MENU ") print("1. ADD NEW RECORD") print("2. SEARCH RECORD") print("3. DISPLAY ALL RECORDS") print("4. DELETE RECORD") print("5. MODIFY RECORD") print("6. EXIT") print() ch = int(input("Select Your Option (1-6): ")) print() if ch==1: print("ADD NEW RECORD") create_record() elif ch==2: print("SEARCH RECORD BY NAME") name = input("Enter name: ") search(name) elif ch==3: print("DISPLAY ALL RECORDS") display_all() elif ch==4: print("DELETE RECORD") name = input("Enter name: ") delete_record(name) elif ch==5: print("MODIFY RECORD") name = input("Enter name: ") modify_record(name) elif ch==6: print("Thanks for using Contact Book") mydb.close() break else: print("Invalid choice") main() # Fix the above code

def add(a, b): return a + b def divide(a, b): return a / b print(add(1, 2)) print(divide(2, 1))

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyffmpeg

def stream_to_rtmp(m3u8_path, rtmp_path): from pyffmpeg import FFMPEG ff = FFMPEG(m3u8_path) ff.cmd.extend(['-f', 'flv', '-vcodec', 'copy', '-acodec', 'copy', '-copyts', '-copytb', '0', rtmp_path]) ff.run() stream_to_rtmp('http://m3u8.com/m3u8.m3u8', 'rtmp://rtmp.com/app/stream')

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

import subprocess import re import os import time import requests # parse the m3u8 url to get the urls of all the ts segments def parse_m3u8_url(url): r = requests.get(url) m3u8_urls = re.findall(r'\n(http[s]?://.+\.ts)', r.text) ffmpeg_cmd = 'ffmpeg -i "concat:' for url in m3u8_urls: ffmpeg_cmd = ffmpeg_cmd + url + '|' return ffmpeg_cmd[:-1] + '" -acodec copy -vcodec copy -absf aac_adtstoasc output.mp4' def download(cmd): # process the command in linux terminal and return the output process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output = process.communicate() return output def run(url):

Python
View
generate functionFri, 02 Dec 2022

The aim of the class project is to create something that is tangible and useful using Python file handling/ Python-SQL connectivity. This should be done in groups of two to three students and should be started by students at least 6 months before the submission deadline. The aim here isto find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, of course to do some of these projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves. The students should be sensitised to avoid plagiarism and violations of copyright issues while working on projects. Teachers should take necessary measures for this

def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python using PyM3u8 .

import pym3u8 import requests import ffmpeg import os url = "file:///home/prajwala/Downloads/hls/master.m3u8" os.environ["http_proxy"] = "http://127.0.0.1:8080" os.environ["https_proxy"] = "http://127.0.0.1:8080" m3u8 = pym3u8.load(url) for playlist in m3u8.playlists: print(playlist.absolute_uri) stream = ffmpeg.input(str(playlist.absolute_uri)) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/[stream-key]', rtmp_live='live', rtmp_conn='S:123456', rtmp_app='rtmp://a.rtmp.youtube.com/live2/[stream-key]') ffmpeg.run(stream)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python using LibRtmp .

import sys import os import subprocess import shlex import time import re import random import string import urllib2 import urllib import base64 import json import datetime, time import requests import getopt import logging import logging import logging.handlers #python read_m3u8.py --input_file=input.txt --input_url=input_url.txt def read_m3u8(in_file): f = open(in_file, 'r') while True: line = f.readline() if not line: break #print(line.strip()) return line.strip() f.close() def main(argv): input_file = '' input_url = '' try: opts, args = getopt.getopt(argv, "hi:u:", ["help", "input_file=", "input_url="]) except getopt.GetoptError: print 'read_

Python
View
generate functionMon, 14 Nov 2022

communicate with google website through code

import urllib import urllib2 values = {'q' : 'python programming tutorials'} data = urllib.urlencode(values) url = 'http://www.google.com/search?' + data req = urllib2.Request(url) resp = urllib2.urlopen(req) respData = resp.read() saveFile = open('withHeaders.txt','w') saveFile.write(str(respData)) saveFile.close()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url using moviepy.editor module

from moviepy.editor import VideoFileClip import argparse import subprocess def m3u8_to_mp4(m3u8_url, mp4_name): subprocess.call(["ffmpeg", "-i", m3u8_url, "-c", "copy", mp4_name]) def main(): parser = argparse.ArgumentParser( description='Get a m3u8 url from a provider and download it as mp4' ) parser.add_argument( 'm3u8_url', help='m3u8 url from provider' ) parser.add_argument( 'mp4_name', help='name for the mp4 file' ) m3u8_to_mp4() if __name__ == '__main__': main()

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove given below syntax: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

def say_hello(): return 'hello' say_hello() # Hello World Program print("hello") # Hello World Program print("hello") # Hello World Program print("hello") # Hello World Program print("hello") # Hello World Program print("hello") # Hello World Program print("hello") # Hello World Program print("hello")

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python

import subprocess m3u8_url = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' rtmp_url = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' cmd = 'ffmpeg -re -i "' + m3u8_url + '" -vcodec copy -acodec aac -strict -2 -f flv "' + rtmp_url +'"' p = subprocess.Popen(cmd, shell=True)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

#install module #python3 -m pip install python-ffmpeg-video-streaming #import module from python_ffmpeg_video_streaming import Input, Output, Stream #create inputs and outputs input1 = Input('http://liveserver.com/video.m3u8') output = Output('rtmp://streamserver', Stream(input1)) #stream with python-ffmpeg-video-streaming output.run()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import youtube_dl import ffmpeg import sys import os url = 'http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8' ydl_opts = {} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) # os.system('ffmpeg -i "' + str(url) + '" -codec copy ' + str(sys.argv[1])+'.mp3 ') import pafy url = 'http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8' video = pafy.new(url) bestaudio = video.getbestaudio() bestaudio.download()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLSStream stream = HLSStream( ffmpeg_path=r'C:\Users\Nancy\AppData\Local\Programs\Python\Python36\Scripts\ffmpeg.exe', input_path='https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8', output=r'C:\Users\Nancy\Desktop\ffmpeg_streaming-master\output.mp4', format='mp4') stream.stream()

Python
View
generate functionSun, 04 Dec 2022

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") ## remove "The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." from the above result and print the statement.

def print_statement(): statement = "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." statement = statement.replace("The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.", "") print(statement) print_statement()

Python
View
generate functionFri, 02 Dec 2022

The aim of the class project is to create something that is tangible and useful using Python file handling/ Python-SQL connectivity. This should be done in groups of two to three students and should be started by students at least 6 months before the submission deadline. The aim here isto find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, of course to do some of these projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves. The students should be sensitised to avoid plagiarism and violations of copyright issues while working on projects. Teachers should take necessary measures for this

def add(a, b): return a + b add(1, 2)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

def stream(url): """ Program to stream m3u8 url to youtube in python """ import subprocess from pytube import YouTube from moviepy.editor import VideoFileClip # Download video from internet yt = YouTube(url) yt.streams.first().download() # Convert video to mp4 video = VideoFileClip(yt.title) video.write_videofile("video.mp4") # Upload video to youtube subprocess.call("youtube-upload --title=\"{}\" --client-secrets secrets.json --private video.mp4".format(yt.title), shell=True) # Delete video file subprocess.call("rm video.mp4", shell=True) stream("https://www.youtube.com/watch?v=S0LU-vbF1tk")

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using rtmpy.

import time import sys import os import subprocess import signal from rtmpy import RTMP def handler(signum, frame): print "Stop streaming" sys.exit(0) signal.signal(signal.SIGINT, handler) # check for correct number of arguments if len(sys.argv) != 3: print 'Usage: python stream.py add rtmp://your_server_address/live/your_stream_key' sys.exit(1) stream = RTMP(sys.argv[1], out=sys.argv[2]) stream.start() while True: time.sleep(1)

Python
View
generate functionFri, 02 Dec 2022

Create a CSV file by entering user-id and password, read and search the password for given user id

import csv def create_csv_file(): csv_columns = ['user id', 'password'] try: with open('user_pass.csv', 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() user_id = input('Enter user id: ') password = input('Enter password: ') writer.writerow({'user id': user_id, 'password': password}) except IOError: print("I/O error")

Python
View
generate functionSun, 04 Dec 2022

import ffmpeg URL = input("Enter here: /n") stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) ## use some other code instead of ffmpeg.run(stream)

import youtube_dl ydl_opts = { 'format': 'bestvideo+bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

Python
View
generate functionSun, 04 Dec 2022

Program to stream m3u8 url to rtmp in python using Streamz.

from streamz import Stream import subprocess def start_stream(url, rtmp_url): command = f'ffmpeg -re -i {url} -c copy -f flv {rtmp_url}' process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) for line in process.stdout: print(line) source_stream = Stream() source_stream.map( start_stream, 'http://test.m3u8', 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx') source_stream.sink(lambda _: print("We're done!"))

Python
View
generate functionSun, 04 Dec 2022

import ffmpeg URL = input("Enter here: /n") stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) ## enhance the above code.

def ffmpeg(URL): stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) # get it from user input URL = input("Enter here: /n") ffmpeg(URL)

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to youtube in python .

def live_to_youtube(url, api_key, channel_id): r = requests.get(url, stream=True) r.raw.decode_content = True filename = 'tempfile.ts' l = 0 with open(filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) l += 1 if l >= 60: live_stream(filename, api_key, channel_id) l = 0 f.close()

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) #create a program loop of above code until user says to close it

while True: constants = ascii_letters + digits + punctuation password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) if input("Want another? ").lower() == "no": break

Python
View
generate functionSun, 04 Dec 2022

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") ## remove "The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." from the above result and print the statement (no function)

print ("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse.")

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyffmpeg

import pyffmpeg stream = pyffmpeg.VideoStream() stream.open('http://sample.vodobox.net/skate_phantom_flex_4k/skate_phantom_flex_4k.m3u8', is_input = True) stream.open('rtmp://a.rtmp.youtube.com/live2/6qg3-fj7w-xjxh-z6b5', is_output = True) stream.start()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using FLVStream .

r = requests.get('https://vod-api.streaming.media.azure.net/api/v2/assets/8bdbcb55-7cce-4a5b-9f10-c3f3a20c2857/locators/8a3a3b3f-d640-4b7f-9b42-77f37d78c4e1/assetfiles/2d33b49f-bfe4-4e0a-a4b4-ad3dd54bdf8a/media/manifest(format=m3u8-aapl)', headers={'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IlhHZU5rZU5VZU5pcE9TR0VUQzZoQk5QQSJ9.eyJhdWQiOiJodHRwczovL3ZvZC1hcGkuc3Ry

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import ffmpeg_streaming from ffmpeg_streaming import Formats, Bitrate, Representation, Size url = 'https://XXX.m3u8' stream = ffmpeg_streaming.input(url) stream \ .output('rtmp://a.rtmp.youtube.com/live2/XXXXX-XXXX-XXXX-XXXX', format='flv', vcodec='h264', vbitrate=Bitrate(1200, 1200, 'k'), acodec='aac', abitrate=Bitrate(160, 160, 'k'), aspect='16:9', strict='experimental', ) \ .run()

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyffmpeg

def stream_m3u8(m3u8_link, rtmp_link): ff = pyffmpeg.FFMpeg() input = ff.input(m3u8_link) output = ff.output(rtmp_link, vcodec='copy', acodec='copy', vsync='cfr', r='30', format='flv', f='flv') input.output(output, end=0, acodec='copy', vcodec='copy').run()

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) # do not close the above program after execution rather rerun it

print("Hello") user_input = input("what is your name") print("Hello," + user_input) # to convert the input to int a = int(input("give me a number")) b = int(input("give me another number")) print(a + b) # calling a function a = 5 b = 4 def add(a, b): return a + b result = add(a, b) print(result) # you can also do this print(add(a, b)) # putting this to use def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): return a / b print(add(1, 2)) print(subtract(1, 2)) print(multiply(1, 2)) print(divide(1, 2))

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to youtubein python using rtmpy

from subprocess import Popen, PIPE def youtube_stream(url, streamKey): ffmpeg = ['ffmpeg', '-i', url, '-vcodec', 'copy', '-acodec', 'aac', '-ar', '44100', '-f', 'flv', streamKey] p = Popen(ffmpeg, stdout=PIPE, stderr=PIPE) while True: output = p.stderr.readline() if output == '' and p.poll() is not None: break if output: print(output.strip().decode('utf-8'))

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

def add(a, b): return a + b

generate functionFri, 25 Nov 2022

import mysql.connector conn=mysql.connector.connect(user='root',password='root',host='localhost',database='store') myc=conn.cursor() #details given by manager o="y" while(o=="y" or o=="Y"): m=""" ,,,,*shop bill management receipt*,,,, ,,,,*tax invoice*,,,, ,,,,*AR Mart*,,,, ,,,,*shop no. 4 kanjurmarg navy colony*,,,, ,,,,*kanjurmarg 400042*,,,, ,,,,*mobile number-8421468850*,,,,""" print(m) c=str(input("enter your choice(S\C\E\G\X):")) #press S for generating stationary bill #press C for generating clothing bill #press E for generating electrical appliances bill #press G for generating grocery bill #press X to exit from program if(c=="S" or c=="s"): print("STATIONARY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=28/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<100): print("Final price:",price) elif(total>=100 and total<=800): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>800 and total<=5000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>5000 and total<=14000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>14000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("STATIONARY BILL") elif(c=="C" or c=="c"): print("CLOTHING BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) adress=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=8/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<800): print("Final price:",price) elif(total>=800 and total<=6000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>6000 and total<=11000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>11000 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("CLOTHING BILL") elif(c=="E" or c=="e"): print("ELECTRICAL APPLIANCES BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=18/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<1200): print("Final price:",price) elif(total>=1200 and total<=4000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>4000 and total<=7000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>7000 and total<=12000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>12000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("ELECTRICAL APPLINCES BILL") elif(c=="G" or c=="g"): print("GROCERY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=4/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<200): print("Final price",price) elif(total>=200 and total<=500): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>500 and total<=900): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>900 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice)#final price is calculated after adding gst else: print(" Sorry You Can Only Buy 41 Items At A Time") print("GROCERY BILL") elif(c=="x" or c=="X"): exit() else: print("PLEASE ENTER A VALID PRODUCT CATEGORY") print(" S for generating stationary bill") print(" C for generating clothing bill") print(" E for generating electrical appliances bill") print(" G for generating grocery bill") t=""" ,,,,,,,THANK YOU,,,,,,, ,,,,VISIT US AGAIN,,,, ,ARMart@modernworld.in,""" print(t) o=input("want to run again y/n or Y/N") bill generation.py Displaying bill generation.py.

#code

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using moviepy.editor module

import os import moviepy.editor as mp import argparse import apiclient.discovery import httplib2 from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import argparser, run_flow def youtube_upload(mp4file, title, description, keywords): # Explicitly tell the underlying HTTP transport library not to retry, since # we are handling retry logic ourselves. httplib2.RETRIES = 1 # Maximum number of times to retry before giving up. MAX_RETRIES = 10 # Always retry when these exceptions are raised. RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib2.ServerNotFoundError) # Always retry when an apiclient.errors.HttpError with one of these status # codes is raised. RETRIABLE_STATUS_CODES =

Python
View
generate functionSun, 04 Dec 2022

stream with m3u8 to rtmp in python (no ffmpeg)

def stream(url, rtmp): import time, uuid, urllib, os, signal, sys, requests, json, subprocess session = str(uuid.uuid1()) while True: response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36 OPR/67.0.3575.53'}) ts = list(map(lambda x: x.split('\n')[0], response.text.split('#EXTINF')))[1:] ts = list(map(lambda x: x.split(',')[1], ts)) ts = list(map(lambda x: 'http://' + url.split('/')[2] + x, ts)) ts = list(map(lambda x: x.split('?')[0], ts)) with open('/tmp/{

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python by PyChunkedEncode.

def live_stream_m3u8_to_rtmp(): format = "rtmp://%s/%s/%s" % ( live_stream_server_info['ip'], live_stream_server_info['app'], live_stream_server_info['stream_name'] ) chunked_encoder = PyChunkedEncode( format, live_stream_server_info['username'], live_stream_server_info['password'], live_stream_server_info['key'], live_stream_server_info['log_level']) chunked_encoder.start() chunked_encoder.join()

Python
View
generate functionSun, 04 Dec 2022

stream with m3u8 to rtmp in python (no ffmpeg)

from subprocess import Popen, PIPE import requests import os def hls2rtmp(hls_url, rtmp_url): """ hls_url: https://baidu.com/hls/stream.m3u8 rtmp_url:rtmp://baidu.com/live/stream """ rtmpdump_cmd = [ "rtmpdump", "-r", hls_url, "-o", "- | ffmpeg -i - -c copy -f flv " + rtmp_url ] p1 = Popen(rtmpdump_cmd, stdout=PIPE) p2 = Popen(["ffmpeg", "-i", "-", "-c", "copy", "-f", "flv", rtmp_url], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() output = p2.communicate()[0] hls2rtmp("https://example

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to youtube in python by PyChunkedEncode.

def live_youtube_push(filename, title, description): """ :param filename: input file :param title: video title :param description: video description :return: None """ # Specify the path to the ffmpeg binary. ffmpeg_path = "ffmpeg" # Create a new PyChunkedEncode object. video_stream = PyChunkedEncode(ffmpeg_path) # Specify the stream URL. #url = "https://a.rtmp.youtube.com/live2/{}".format(youtube_key) url = "rtmp://a.rtmp.youtube.com/live2/{}".format(youtube_key) # Set the stream URL. video_stream.set_url(url) # Specify the stream resolution. #video_stream.set_resolution(640, 360) # Specify the stream framerate. video_stream.set_framerate(60) # Specify the stream bitrate.

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pym3u8)

import json import time import datetime import subprocess import sys import pym3u8 import os def stream_to_rtmp(url, rtmp_url, duration = 0): if not os.path.isdir("logs"): os.makedirs("logs") # print(url) sys.stdout.write("{}:\tStarted: {}\n".format(rtmp_url, datetime.datetime.now())) sys.stdout.write("{}:\tStream: {}\n".format(rtmp_url, url)) process = subprocess.Popen(['ffmpeg', '-i', url, '-acodec', 'copy', '-vcodec', 'copy', '-f', 'flv', rtmp_url], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) log_file = open("logs/{}.txt".format(rtmp_url), '

Python
View
generate functionMon, 28 Nov 2022

import string print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.digits) print(string.hexdigits) print(string.whitespace) print(string.punctuation) #print above commands in one command

import string def print_all(a): print(a) return a print_all(string.ascii_letters) print_all(string.ascii_lowercase) print_all(string.ascii_uppercase) print_all(string.digits) print_all(string.hexdigits) print_all(string.whitespace) print_all(string.punctuation)

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: o ALTER table to add new attributes / modify data type / drop attribute o UPDATE table to modify data o ORDER By to display data in ascending / descending order o DELETE to remove tuple(s) o GROUP BY and find the min, max, sum, count and averag

''' def alter_table(cursor,table_name,column_name,data_type): query = "ALTER TABLE "+table_name+" ADD "+column_name+" "+data_type+";" cursor.execute(query) connection.commit() print("Table altered successfully") alter_table(cursor,"student","enrollment", "int(10)") def update_table(cursor,table_name,column_name,value,condition): query = "UPDATE "+table_name+" SET "+column_name+" = '"+value+"' WHERE "+condition+";" cursor.execute(query) connection.commit() print("Table updated successfully") update_table(cursor,"student","enrollment","123456789","name = 'charlie'") def delete_table(cursor,table_name,condition): query = "DELETE FROM "+table_name+" WHERE "+condition+";" cursor.execute(query) connection.commit()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size video_stream = ffmpeg_streaming.input('https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8') audio_stream = video_stream.audio video_stream = video_stream.video video_stream = video_stream.filter('scale', Size(1280, 720), force_original_aspect_ratio='increase') video_stream = video_stream.filter('pad', Size(1280, 720), Color(0, 0, 0)) video_stream = video_stream.output('test.mp4', format=Formats.mp4, vcodec='libx264', acodec='aac') video_stream.run()

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove given below syntax: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

def download(link): ydl_opts = {} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([link]) download("https://www.youtube.com/watch?v=Nq2wYlWFucg")

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyRTMP (no ffmpeg)

def stream_m3u8(url, rtmp): stream = pyRTMP.RTMP(rtmp) stream.open() m3u8 = requests.get(url, headers=headers) m3u8_text = m3u8.text for line in m3u8_text.splitlines(): if line.startswith("#EXTINF:"): ts_url = base_url + line.split(",")[1].strip() ts_data = requests.get(ts_url, headers=headers) stream.write(ts_data.content) print("wrote: " + ts_url)

Python
View
code to explanationFri, 25 Nov 2022

import mysql.connector conn=mysql.connector.connect(user='root',password='root',host='localhost',database='store') myc=conn.cursor() #details given by manager o="y" while(o=="y" or o=="Y"): m=""" ,,,,*shop bill management receipt*,,,, ,,,,*tax invoice*,,,, ,,,,*AR Mart*,,,, ,,,,*shop no. 4 kanjurmarg navy colony*,,,, ,,,,*kanjurmarg 400042*,,,, ,,,,*mobile number-8421468850*,,,,""" print(m) c=str(input("enter your choice(S\C\E\G\X):")) #press S for generating stationary bill #press C for generating clothing bill #press E for generating electrical appliances bill #press G for generating grocery bill #press X to exit from program if(c=="S" or c=="s"): print("STATIONARY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=28/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<100): print("Final price:",price) elif(total>=100 and total<=800): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>800 and total<=5000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>5000 and total<=14000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>14000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("STATIONARY BILL") elif(c=="C" or c=="c"): print("CLOTHING BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) adress=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=8/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<800): print("Final price:",price) elif(total>=800 and total<=6000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>6000 and total<=11000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>11000 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("CLOTHING BILL") elif(c=="E" or c=="e"): print("ELECTRICAL APPLIANCES BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=18/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<1200): print("Final price:",price) elif(total>=1200 and total<=4000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>4000 and total<=7000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>7000 and total<=12000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>12000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("ELECTRICAL APPLINCES BILL") elif(c=="G" or c=="g"): print("GROCERY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=4/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<200): print("Final price",price) elif(total>=200 and total<=500): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>500 and total<=900): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>900 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice)#final price is calculated after adding gst else: print(" Sorry You Can Only Buy 41 Items At A Time") print("GROCERY BILL") elif(c=="x" or c=="X"): exit() else: print("PLEASE ENTER A VALID PRODUCT CATEGORY") print(" S for generating stationary bill") print(" C for generating clothing bill") print(" E for generating electrical appliances bill") print(" G for generating grocery bill") t=""" ,,,,,,,THANK YOU,,,,,,, ,,,,VISIT US AGAIN,,,, ,ARMart@modernworld.in,""" print(t) o=input("want to run again y/n or Y/N") bill generation.py Displaying bill generation.py.

generate functionFri, 02 Dec 2022

Create a binary file with roll number, name and marks. Input a roll number and update the marks

#importing pandas library import pandas as pd #creating a dataframe df = pd.DataFrame({"Roll No.": [1,2,3,4,5,6,7,8,9,10], "Name": ["A","B","C","D","E","F","G","H","I","J"],"Marks":[65,75,85,84,93,95,80,88,78,86]}) #saving dataframe to csv file df.to_csv("data.csv") #opening dataframe from csv file df2 = pd.read_csv("data.csv") #updating dataframe df2 = df2.append({'Roll No.':4, 'Name':'D', 'Marks':85}, ignore_index=True) #saving dataframe to csv file df2.to_csv("data.csv")

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to rtmp server using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

import moviepy.editor as mp def stream_video_from_m3u8_to_rtmp_server(m3u8_url, rtmp_server, rtmp_stream_key): # Open the video file clip = mp.VideoFileClip(m3u8_url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile(rtmp_server, codec='libx264', audio_codec='aac')

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) # do not close the above program after execution rather rerun it.

def password_generator(password_length): from string import * constants = ascii_letters + digits + punctuation password = "" for i in range(password_length): password += random.choice(constants) print(password) password_length = int(input("What's the length of the password? ")) password_generator(password_length)

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) ## do not close the above program after execution rather rerun it

def run_again(): while True: again = input("Do you want to run again? ") if again == "yes": return True elif again == "no": return False

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 link to rtmp in python using PyM3u8 .

#!/usr/bin/env python from pym3u8 import load from pysrt import SubRipFile from subprocess import Popen, PIPE from tempfile import NamedTemporaryFile from datetime import datetime import time import re import os m3u8_url = 'http://160.111.144.40:1935/live/stream/playlist.m3u8' rtmp_url = 'rtmp://localhost/live' key = 'Q4B4Cw6n' def run_process(cmd): p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) out, err = p.communicate() return out, err def get_subtitles(subtitles_url): subtitles_url = subtitles_url.replace('\n', '').replace('\r', '') if subtitles_url: try: response = urllib2.urlopen(subtitles_url)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using Streamz.

import time import datetime as dt import numpy as np import pandas as pd import streamz import streamz.dataframe import bokeh.models as bm import bokeh.plotting as bp from tornado.ioloop import IOLoop import tornado.web import requests import pandas as pd # import data df = pd.read_csv('../data/pandas_data.csv', parse_dates=['datetime'], index_col=['datetime']) # create a streamz dataframe source = streamz.dataframe.DataFrame(streaming=True, example=df) # create a buffer of the dataframe buffer = source.buffer(10, dropna=True) # create a rolling mean rolling_mean = buffer.rolling(12).mean() # create a rolling standard deviation rolling_std = buffer.rolling(12).std() # calculate the upper and lower bounds of the Bollinger Bands upper_bound = rolling

Python
View
generate functionSun, 04 Dec 2022

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") ## remove "The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." from the above result and print the statement (no function)

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse."

Python
View
fix invalid codeSun, 11 Dec 2022

import mysql.connector # Connect to the database db = mysql.connector.connect( host="localhost", user="root", password="", database="akshay" ) # Create a cursor to interact with the database cursor = db.cursor() cursor.execute("DROP TABLE students") cursor.execute("DROP TABLE courses") # Create a table for storing students cursor.execute(""" CREATE TABLE students ( id INT PRIMARY KEY, name VARCHAR(255), grade INT ) """) # Create a table for storing courses cursor.execute(""" CREATE TABLE courses ( id INT PRIMARY KEY, name VARCHAR(255), teacher VARCHAR(255) ) """) # Create a table for storing grades cursor.execute(""" CREATE TABLE grades ( id INT PRIMARY KEY, student_id INT, course_id INT, grade INT, FOREIGN KEY (student_id) REFERENCES students(id), FOREIGN KEY (course_id) REFERENCES courses(id) ) """) # Function to add a new student to the database def add_student(): # Prompt the user to enter student information name = input("Enter the student's name: ") grade = input("Enter the student's grade: ") # Insert the student into the database cursor.execute(f"INSERT INTO students (name, grade) VALUES ('{name}', {grade})") # Function to update a student's information def update_student(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Prompt the user to enter the updated information name = input("Enter the updated name: ") grade = input("Enter the updated grade: ") # Update the student's information in the database cursor.execute(f"UPDATE students SET name = '{name}', grade = {grade} WHERE id = {student_id}") # Function to delete a student from the database def delete_student(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Delete the student from the database cursor.execute(f"DELETE FROM students WHERE id = {student_id}") # Function to add a new course to the database def add_course(): # Prompt the user to enter course information name = input("Enter the course name: ") teacher = input("Enter the course teacher: ") # Insert the course into the database cursor.execute(f"INSERT INTO courses (name, teacher) VALUES ('{name}', '{teacher}')") # Function to update a course's information def update_course(): # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Prompt the user to enter the updated information name = input("Enter the updated name: ") teacher = input("Enter the updated teacher:") # Function to delete a course from the database def delete_course(): # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Delete the course from the database cursor.execute(f"DELETE FROM courses WHERE id = {course_id}") # Function to add a new grade to the database def add_grade(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Prompt the user to enter the grade grade = input("Enter the grade: ") # Insert the grade into the database cursor.execute(f"INSERT INTO grades (student_id, course_id, grade) VALUES ({student_id}, {course_id}, {grade})") # Function to update a grade def update_grade(): # Prompt the user to enter the grade's ID grade_id = input("Enter the grade's ID: ") # Prompt the user to enter the updated grade grade = input("Enter the updated grade: ") # Update the grade in the database cursor.execute(f"UPDATE grades SET grade = {grade} WHERE id = {grade_id}") # Function to delete a grade from the database def delete_grade(): # Prompt the user to enter the grade's ID grade_id = input("Enter the grade's ID: ") # Delete the grade from the database cursor.execute(f"DELETE FROM grades WHERE id = {grade_id}") # Function to display a student's information def display_student(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Query the database to retrieve the student's information cursor.execute(f"SELECT * FROM students WHERE id = {student_id}") student = cursor.fetchone() # Print the student's information print(f"ID: {student[0]}, Name: {student[1]}, Grade: {student[2]}") # Function to display a course's information def display_course(): # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Query the database to retrieve the course's information cursor.execute(f"SELECT * FROM courses WHERE id = {course_id}") course = cursor.fetchone() # Print the course's information print(f"ID: {course[0]}, Name: {course[1]}, Teacher: {course[2]}") # Function to display a grade def display_grade(): # Prompt the user to enter the grade's ID grade_id = input("Enter the grade's ID: ") # Query the database to retrieve the grade cursor.execute(f"SELECT * FROM grades WHERE id = {grade_id}") grade = cursor.fetchone() # Print the grade #print(f"ID: {grade # Function to display all students def display_all_students(): # Query the database to retrieve all students cursor.execute("SELECT * FROM students") students = cursor.fetchall() # Print the students for student in students: print(f"ID: {student[0]}, Name: {student[1]}, Grade: {student[2]}") # Function to display all courses def display_all_courses(): # Query the database to retrieve all courses cursor.execute("SELECT * FROM courses") courses = cursor.fetchall() # Print the courses for course in courses: print(f"ID: {course[0]}, Name: {course[1]}, Teacher: {course[2]}") # Function to display all grades def display_all_grades(): # Query the database to retrieve all grades cursor.execute("SELECT * FROM grades") grades = cursor.fetchall() # Print the grades for grade in grades: print(f"ID: {grade[0]}, Student ID: {grade[1]}, Course ID: {grade[2]}, Grade: {grade[3]}") # Main program loop while True: # Display menu print("1. Add student") print("2. Update student") print("3. Delete student") print("4. Add course") print("5. Update course") print("6. Delete course") print("7. Add grade") print("8. Update grade") print("9. Delete grade") print("10. Display student") print("11. Display course") print("12. Display grade") print("13. Display all students") print("14. Display all courses") print("15. Display all grades") print("16. Exit") choice = input("Enter your choice: ") # Add a new student if choice == "1": add_student() # Update a student's information elif choice == "2": update_student() # Delete a student elif choice == "3": delete_student() # Add a new course elif choice == "4": add_course()

generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using FLVStream .

import os from subprocess import Popen, PIPE from threading import Thread from flask import Flask, send_from_directory, Response from flvstreamer import FLVStreamer app = Flask(__name__) def stream_thread(url): flv = FLVStreamer(url) flv.start() @app.route('/') def stream(): url = 'http://' + os.getenv("URL") thread = Thread(target=stream_thread, args=(url,)) thread.start() return Response(flv.stream(), mimetype='text/event-stream')

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

def youtube_stream(url): command = "ffmpeg -user_agent 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36' -i {0} -vcodec copy -acodec copy -f flv rtmp://a.rtmp.youtube.com/live2/{1}".format(url, YOUTUBE_CHANNEL_ID) subprocess.call(command, shell=True)

Python
View
generate functionSun, 04 Dec 2022

import subprocess def tube(video_id): cmd = ['youtube-dl', '--no-playlist', '--no-warnings', '--quiet', '-f', 'mp4', 'https://www.youtube.com/watch?v={}'.format(video_id) ] subprocess.run(cmd) #convert the above code into youtube_dl python

import youtube_dl ydl_opts = { 'format': 'mp4', 'no-playlist': True, 'quiet': True, 'no-warnings': True } def tube(video_id): with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v={}'.format(video_id)]) return

Python
View
generate functionSun, 04 Dec 2022

stream with m3u8 to rtmp in python (no ffmpeg)

def m3u8_to_rtmp(m3u8, rtmp): ts_list = parse_m3u8_ts(m3u8) if ts_list is None: print('Failed to parse m3u8 file') return False # get stream from ts file ts_stream = open_ts_stream(ts_list[0]) # create rtmp stream rtmp_stream = create_rtmp_stream(rtmp) # continue stream ts to rtmp stream_ts_to_rtmp(ts_stream, rtmp_stream)

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 to rtmp in python (no ffmpeg)

def streamM3U8(url, host="rtmp://127.0.0.1:1935/live"): req = urllib.request.Request(url) res = urllib.request.urlopen(req) res2 = res.read().decode('utf-8') res.close() #print(res2) patt = re.compile('(^.*?\n)') res3 = patt.findall(res2) tsUrl = res3[-1].strip() #print(tsUrl) #tsUrl = "http://192.168.1.4/live/test.ts" return streamTS(tsUrl, host) def streamTS(url, host = "rtmp://127.0.0.1:1935/live"): size = 1024 stream = urllib.request.urlopen(url) #print(stream.info()) #print(stream.getcode()) #print(stream.get

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using FLVStream .

import ffmpy import subprocess import shlex import sys import os def execute(cmd): """ Function to execute a system command and return the output. """ args = shlex.split(cmd) try: output = subprocess.check_output(args, stderr=subprocess.STDOUT).decode("utf-8") return output except: return None if __name__ == '__main__': # URL to the m3u8 file url = 'http://playertest.longtailvideo.com/adaptive/bbbfull/bbbfull.m3u8' # output RTMP URL output = 'rtmp://YOUR_RTMP_URL' # command to fetch key cmd = 'ffprobe -v quiet -print_format json -show_format -show_streams ' + url output = execute(cmd) if output is not None: key = None # if key is present, fetch it if '#EXT

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) # reprint the program after execution.

def password_generator(): import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password)

Python
View
generate functionThu, 02 Mar 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from pyyoutube import Api from pyyoutube.utils.arguments import parse_cli_args from pyyoutube.utils.stream import streaming_from_m3u8 from pyyoutube import Api from ffmpeg import FFMpeg from ffmpeg.utils.arguments import parse_cli_args from ffmpeg.utils.stream import streaming_from_m3u8 from ffmpeg.services.youtube import Youtube from pyyoutube.utils.ffmpeg import FFMpeg from pyyoutube.services.youtube import Youtube api_key = "AIzaSyBk-GZ1EwZiCKDYnI2YKXyX9o6PnL-WpKM" api = Api(api_key=api_key)

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) # rerun the program after execution.

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password)

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) #create a program loop of above code until user says to close it

while True: choice = input("Would you like to restart the program?") if choice == 'yes': continue elif choice == 'no': print('Thank you for using this program!') break else: print('Please enter yes or no') continue

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import ffmpeg_streaming import ffmpeg stream = ffmpeg_streaming.Stream(url="http://st-kv-vod.akamaized.net/b542d8a4f38a4e6e8ff0a9c9d83aa7b4/4a2f48d3/stv2/index.m3u8") file_name = "big_buck_bunny_720p_10mb.mp4" with open(file_name, 'wb') as f: for data in stream.iter_content(): f.write(data) input = ffmpeg.input(file_name) input = ffmpeg.output(file_name) input.run()

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python using Avcon .

def stream_to_youtube(m3u8_url, title, description, category, tags, output_path=None): """ :param m3u8_url: url of m3u8 file :param title: video title :param description: video description :param category: video category :param tags: video tags (list) :param output_path: path for the output file (default=None) :return: output_filename (if output_path=None) or True """ # modify the avconv command with your own configuration command = [ "avconv", "-i", m3u8_url, "-c:v", "libx264", "-c:a", "copy", "-threads", "0", "-b:v", "1000k", "-b:a", "64k", "-r", "25", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov",

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg)

import requests import subprocess import threading import time import socket import urlparse import sys import os def get_local_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) return s.getsockname()[0] def get_public_ip(): return requests.get('http://ip.42.pl/raw').text def get_url_ip(url): return socket.gethostbyname(urlparse.urlparse(url).hostname) def get_public_ip_from_url(url): return get_url_ip(url) def check_ip_available(ip): if ip == '' or ip == "127.0.0.1": return False else: return True def get_ip_from_url(url): return check_ip_available(get_public_ip_from_url(url))

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using moviepy.editor module

def stream_video_to_youtube(m3u8_url, title, description, category_id, client_secrets_file, credentials_file): import moviepy.editor as mp import os import subprocess print("Clip") clip = mp.VideoFileClip(m3u8_url) print("Write") clip.write_videofile("video.mp4") print("Upload") subprocess.call(['python', 'upload_video.py', '--file', 'video.mp4', '--title', title, '--description', description, '--category', category_id, '--keywords', '', '--privacyStatus', 'unlisted', '--client_secrets', client_secrets_file, '--credentials', credentials_file]) os.remove("video.mp4") stream_video_to_youtube("https://s3.amazonaws.com/vod-demo/index.m3u8", "VOD", "Video on demand",

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: 1. ALTER table to add new attributes / modify data type / drop attribute 2. UPDATE table to modify data 3. ORDER By to display data in ascending / descending order 4. DELETE to remove tuple(s) 5. GROUP BY and find the min, max, sum, count and average

import sqlite3 connection = sqlite3.connect(':memory:') cursor = connection.cursor() cursor.execute('CREATE TABLE student(roll_no INTEGER PRIMARY KEY, name TEXT, age INTEGER);') cursor.execute('INSERT INTO student(name, age) VALUES ("student0", 9);') cursor.execute('INSERT INTO student(name, age) VALUES ("student1", 10);') cursor.execute('INSERT INTO student(name, age) VALUES ("student2", 8);') cursor.execute('INSERT INTO student(name, age) VALUES ("student3", 9);') cursor.execute('INSERT INTO student(name, age) VALUES ("student4", 8);') cursor.execute('INSERT INTO student(name, age) VALUES ("student5", 10);') cursor.execute('INSERT INTO student(name, age) VALUES ("student6", 8);') cursor.execute('INSERT INTO student(name, age) VALUES ("student7", 9);

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using GStreamer .

def stream_m3u8_to_rtmp(m3u8_url, rtmp_url): Gst.init([]) playbin = Gst.ElementFactory.make("playbin", "playbin") playbin.set_property('uri', m3u8_url) playbin.set_property('buffer-size', 20 * 1024 * 1024) playbin.set_property('buffer-duration', 20 * Gst.SECOND) playbin.set_property('latency', 20 * Gst.SECOND) playbin.set_property('connection-speed', 1000) playbin.set_property('timeout', 1000000000) playbin.set_property('buffer-mode', 2) playbin.set_property('ring-buffer-max-size', 10 * 1024 * 1024) playbin.set_property('max-lateness', -1) # Add RTMP sink sink = Gst.ElementFactory.make('rtmpsink', 'sink') sink.

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to rtmp server using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

import moviepy.editor as mp url = 'https://xxxx.m3u8' clip = mp.VideoFileClip(url) clip.write_videofile('output.mp4')

Python
View
generate functionSun, 04 Dec 2022

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") ## remove "The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." from the above result and print the statement.

def printPython(): print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse.") printPython()

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to rtmp server using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

import moviepy.editor as mp video=mp.VideoFileClip("F:\moviepy.mp4") video.audio.write_audiofile("audio.mp3")

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Represent

Python
View
generate functionSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main() # fix the above invalid code

def add(a, b): return a + b add(1, 2)

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) #create a program loop of above code until user says to close it

def ask_user(): user_input = input("Press Q to quit: ").lower() if user_input == "q": return False else: return True while ask_user(): print("Looping")

Python
View
generate functionSat, 14 Jan 2023

create an automated system that backs up and restores data stored in a MySQL database

import mysql.connector from mysql.connector import Error import os from subprocess import Popen, PIPE def backup(): try: connection = mysql.connector.connect(host='127.0.0.1', database='my_database', user='root', password='password') if connection.is_connected(): db_Info = connection.get_server_info() print("Connected to MySQL Server version ", db_Info) cursor = connection.cursor() cursor.execute("select database();") record = cursor.fetchone() print("Your connected to database: ", record) pipe = Popen(['/usr/bin/mysqldump', '-u', 'root', '--databases', 'my_database', '--password=password'], stdout=PIPE) output = pipe.communicate()[0] print(output) with open('/home/database_backup.sql', 'wb') as f

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyffmpeg

def m3u8_to_rtmp(url, stream_name, local_port=10000, time_interval=5): print("start streaming m3u8 to rtmp\n") stream_cmd = "ffmpeg -i %s -c copy -f flv rtmp://localhost:%s/%s" % (url, local_port, stream_name) print(stream_cmd) stream_subprocess = subprocess.Popen(stream_cmd, shell=True, stderr=subprocess.STDOUT) print("streaming pid: %s\n" % stream_subprocess.pid) print("streaming url: %s\n" % url) print("streaming stream name: %s\n" % stream_name) print("streaming local port: %s\n" % local_port) print("streaming time interval: %s\n" % time_interval) while True: time.sleep(time_interval) if stream_subprocess.poll() is

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using Streamlink

import streamlink import subprocess # M3U8 stream m3u8_stream_url = "https://www.youtube.com/watch?v=yVUbUYq3wq4" # RTMP stream rtmp_stream_url = "rtmp://rtmp.example.com:1935/app/stream_name" # Get streams streams = streamlink.streams(m3u8_stream_url) # Get best quality stream stream = streams['best'] # Get stream url stream_url = stream.url # Create command to stream m3u8 url to rtmp command = ["ffmpeg", "-i", stream_url, "-c:v", "copy", "-c:a", "aac", "-strict", "-2", "-f", "flv", rtmp_stream_url] # Stream to rtmp server subprocess.call(command)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using LibRtmp .

def stream_m3u8_to_rtmp(m3u8_url, rtmp_url): """ Stream m3u8 url to rtmp url """ base_url = os.path.dirname(m3u8_url) m3u8 = requests.get(m3u8_url) m3u8_content = m3u8.text m3u8_list = m3u8_content.split('\n') ts_list = [] for item in m3u8_list: if item.endswith('.ts'): ts_list.append(item) ts_list = [base_url + '/' + ts for ts in ts_list] p = subprocess.Popen(['ffmpeg', '-y', '-i', 'concat:' + '|'.join(ts_list), '-c', 'copy', '-f', 'flv', '-metadata',

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using rtmpy.

def rtmpm3u8(url, rtmp_url): rtmp_conn = rtmpy.Connection(rtmp_url) rtmp_conn.connect() stream_type='live' rtmp_conn.create_stream(type=stream_type) m3u8_obj = m3u8.loads(requests.get(url).text) master_playlist = m3u8.load(url) for playlist in master_playlist.playlists: print(playlist.uri) segment_urls = [urljoin(url, segment.uri) for segment in playlist.segments] rtmp_conn.publish() for segment_url in segment_urls: segment_obj = requests.get(segment_url).content rtmp_conn.write(segment_obj, timestamp=0)

Python
View
fix invalid codeThu, 29 Dec 2022

import pygal # Create the code code = "print('Hello World!')" # Create the flowchart flowchart = pygal.Flowchart() flowchart.add(code) flowchart.render_to_file('flowchart.svg')

## License * MIT ## Contribution If you have any ideas, just [open an issue](https://github.com/peterldowns/simple-python-pygal-chart/issues/new) and tell me what you think. If you'd like to contribute, please fork the repository and make changes as you'd like. Pull requests are warmly welcome. ## Donate * [Become a patron](https://www.patreon.com/pld)

generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyffmpeg

def stream_m3u8_to_rtmp(m3u8_url): #function that: stream m3u8 url to rtmp in python with pyffmpeg #https://pypi.org/project/pyffmpeg/ #https://blog.csdn.net/u012989420/article/details/90804562 #https://www.w3cschool.cn/python/python-install-pyffmpeg.html #https://blog.csdn.net/qq_35378626/article/details/81053800 #https://www.cnblogs.com/kissazi2/p/11205442.html #https://www.jianshu.com/p/dde6cf812b0b from pyffmpeg import FFmpeg from pyffmpeg import Input from pyffmpeg import Output from pyffmpeg import Format from pyffmpeg import AudioCodec from pyffmpeg import VideoCodec from pyffmpeg import AVStream from

Python
View
generate functionSun, 27 Nov 2022

create a hotel management python project using mysql

def create_project(hotel_name, db_name, db_user, db_password): os.system("mkdir " + hotel_name) os.system("cd " + hotel_name) os.system("python3 -m venv venv") os.system("source venv/bin/activate") os.system("pip install django") os.system("django-admin startproject " + hotel_name) os.system("cd " + hotel_name) os.system("python manage.py migrate") os.system("python manage.py startapp hotel") os.system("cd hotel") os.system("touch models.py") os.system("cd ..") os.system("python manage.py makemigrations hotel") os.system("python manage.py migrate") with open('hotel/models.py', 'w') as f: f.write("from django.db import models\n\n") f.write("class Guest(

Python
View
code to explanationMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password)

This code will import the random module and the string module. Then it will make constants to use in the code. Then it will ask you how long you want the password to be. Then it will make a variable that stores the password. Then it will make a loop that makes the length of the password as long as you want it to be. Then it will print the password.

generate functionSun, 27 Nov 2022

create a school data management python project using mysql

def create_school_database(school_name): connection = mysql.connect() cursor = connection.cursor() school_db_name = school_name.lower().replace(' ', '_') query = 'CREATE DATABASE IF NOT EXISTS {}'.format(school_db_name) cursor.execute(query) connection.commit() connection.close() cursor.close()

Python
View
generate functionFri, 02 Dec 2022

Write a Python program to implement a stack using list.

def stack(): stack = [] return stack def push(stack, item): stack.append(item) def pop(stack): if len(stack) == 0: return None else: return stack.pop() def peek(stack): if len(stack) == 0: return None else: return stack[-1] stack = stack() push(stack,1) push(stack,2) push(stack,3) push(stack,4) print(pop(stack))

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size import os import shutil def encode(in_file, out_file, height=None, width=None): # TODO: Implement me pass def hls_stream(in_file, out_dir, start_time=None, duration=None): # TODO: Implement me pass def stream_to_youtube(in_file, out_dir, start_time=None, duration=None): # TODO: Implement me pass

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg and no function)

import subprocess import requests import json import time import os def main(): baseUrl = "https://m.facebook.com" authUrl = baseUrl + "/v2.6/dialog/oauth" accessUrl = baseUrl + "/v2.6/oauth/access_token" debugTokenUrl = baseUrl + "/debug_token" app_id = "app_id" app_secret = "app_secret" app_token = app_id + "|" + app_secret default_timeout = 30 default_redirect_uri = 'https://www.facebook.com/connect/login_success.html' def get_auth_token(app_token, app_id, permissions, redirect_uri=default_redirect_uri): url_get_params = { 'client_id': app_id, 'redirect_uri': redirect_uri, 'scope': permissions, } r = requests.get(authUrl, params=url_get

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: 1. ALTER table to add new attributes / modify data type / drop attribute 2. UPDATE table to modify data 3. ORDER By to display data in ascending / descending order 4. DELETE to remove tuple(s) 5. GROUP BY and find the min, max, sum, count and average

import sqlite3 conn = sqlite3.connect('student.db') c = conn.cursor() #create cursor c.execute('''DROP TABLE IF EXISTS student''') c.execute('''CREATE TABLE student ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER, marks INTEGER)''') c.execute('''INSERT INTO student VALUES (1, "Gill", 15, 80)''') c.execute('''INSERT INTO student VALUES (2, "Ben", 14, 75)''') c.execute('''INSERT INTO student VALUES (3, "Joe", 14, 65)''') c.execute('''INSERT INTO student VALUES (4, "Will", 15, 45)''') c.execute('''INSERT INTO student VALUES (5, "Calvin", 16, 80)''') c.execute('''INSERT INTO student VALUES (6, "James", 13, 40)''') c.execute('''

Python
View
generate functionFri, 02 Dec 2022

https://www.programming-helper.com/generate-function

def generate_function(name, required_params, optional_params): params = required_params for optional_param in optional_params: params.append(optional_param + ' = None') params = ', '.join(params) function = f'def {name}({params}):\n' function += f' return ""' return function

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

def stream_to_youtube(m3u8_url, youtube_url, quality, stream_id): stream = ffmpeg.input(m3u8_url, **{'stimeout': '5000000', 'reconnect': '1', 'reconnect_streamed': '1', 'reconnect_delay_max': '1000', 'reconnect_attempts': '-1'}) stream = ffmpeg.output(stream, youtube_url, vcodec='h264', acodec='aac', vb="%dk" % quality, threads=2, format='flv', **{'stimeout': '5000000', 'reconnect': '1', 'reconnect_streamed': '1', 'reconnect_delay_max': '1000', 'reconnect_attempts': '-1'}) print('Starting ffmpeg with command:') print(ffmpeg.compile(stream)) ffmpeg.run(stream, quiet=False, overwrite_output=True)

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg)

#!/usr/bin/env python """ Live streaming of a m3u8 file to rtmp The file is chunked and read in a loop. When complete it is re-read. The ffmpeg command can be modified to suit the target RTMP server. For example: ffmpeg -re -i 'http://localhost:8000/path/to/file.m3u8' \ -c copy -f flv 'rtmp://a.rtmp.youtube.com/live2/stream_key_from_youtube' """ # https://gist.github.com/rca/5c1a539f4a4be4d4c4ff import os import sys import subprocess import time import signal import logging def get_chunk_list(filename): return [ filename, *[f"{filename}-{i}" for i in range(1, 1000)] ] def get_chunk_timeout(filename): return int(os.stat(filename).st_

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

def stream_to_youtube(filename): stream = ffmpeg.input(filename) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/' + YOUTUBE_STREAM_KEY, vcodec='copy', acodec='copy', format='flv', strict='experimental', r=30, preset='ultrafast', force_key_frames='expr:gte(t,n_forced*2)') ffmpeg.run(stream)

Python
View
generate functionSun, 04 Dec 2022

import ffmpeg URL = input("Enter here: /n") stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) ## enhance the above code.

import ffmpeg def stream(URL): stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) x = input("Enter here: /n") stream(x)

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) #create a program loop of above code until user says to close it

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) ask_user = True while ask_user: if input("Run again? ") == "no": ask_user = False

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python

import requests import os import subprocess import re import threading from datetime import datetime import time import sys from queue import Queue from threading import Thread def get_m3u8_url(): url = 'https://www.youtube.com/watch?v=gJN8QyhdxL4' r = requests.get(url) print(r.text) r1 = re.findall(r'"hlsManifestUrl":"(.*?)"', r.text) return r1[0] def download_m3u8(m3u8_url): file_name = 'tmp.m3u8' print('downloading m3u8...') os.system('ffmpeg -i ' + m3u8_url + ' -c copy ' + file_name) print('downloaded m3u8') return file_name def get_ts_list(m3u8_file_name): ts_list = []

Python
View
generate functionSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main() # fix the above code

def add(a, b): return a + b add(1, 2)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using Muxer .

import subprocess import os def start_streaming(m3u8,rtmp): ffmpeg_command = "ffmpeg -i {} -acodec copy -vcodec copy -f flv -y {}".format(m3u8,rtmp) pid = subprocess.Popen(ffmpeg_command, shell=True) return pid def stop_streaming(pid): os.system("kill -9 {}".format(pid.pid)) if __name__ == "__main__": m3u8_url = "http://127.0.0.1:5000/sample.m3u8" rtmp_url = "rtmp://127.0.0.1:1935/live/mystream" p = start_streaming(m3u8_url,rtmp_url) stop_streaming(p)

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyM3U8)

import m3u8 import ffmpeg def stream_m3u8_to_rtmp(m3u8_url, rtmp_url): m3u8_obj = m3u8.load(m3u8_url) m3u8_urls = [] for playlist in m3u8_obj.playlists: m3u8_urls.append(playlist.absolute_uri) for m3u8_url in m3u8_urls: print("Streaming: " + m3u8_url) stream = ffmpeg.input(m3u8_url) stream = ffmpeg.output(stream, rtmp_url, format="flv", vcodec="copy", acodec="copy", r="30") ffmpeg.run(stream) stream_m3u8_to_rtmp("https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8", "rtmp://localhost

Python
View
code to explanationMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password)

The code above is a program in Python that generates a password of the length provided by the user. It generates the password by randomly choosing a character from a string of digits, letters, and punctuation marks.

generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using GStreamer .

def stream_m3u8_to_rtmp(m3u8_url, rtmp_url): Gst.init(None) pipeline = Gst.parse_launch("playbin uri={}".format(m3u8_url)) sink = Gst.ElementFactory.make("rtmpsink", "sink") sink.set_property("location", rtmp_url) pipeline.set_property("video-sink", sink) loop = GObject.MainLoop() pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass pipeline.set_state(Gst.State.NULL)

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python (no function)

import subprocess url = 'http://192.168.1.1/hls/test.m3u8' rtmp_url = 'rtmp://192.168.1.1/live/my_stream' ffmpeg = "ffmpeg -i '{}' -vcodec copy -acodec copy -f flv '{}'".format(url, rtmp_url) process = subprocess.Popen(ffmpeg.split(), stdout=subprocess.PIPE) output, error = process.communicate() print(output)

Python
View
generate functionMon, 28 Nov 2022

password generator using random module (no function)

import random letters = "abcdefghijklmnopqrstuvwxyz" uppercase_letters = letters.upper() numbers = "0123456789" symbols = "!@#$%^&*()_+-=:;?><,.{}[]" all = letters + uppercase_letters + numbers + symbols password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(all) print(password)

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove: V[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

import youtube_dl ydl_opts = {} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=Nq2wYlWFucg'])

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table

# Create student table cur.execute("CREATE TABLE IF NOT EXISTS student (name TEXT, studentNumber INTEGER)") # Insert data cur.execute("INSERT INTO student VALUES('Bob', 123456)") cur.execute("INSERT INTO student VALUES('Alice', 234567)") cur.execute("INSERT INTO student VALUES('John', 345678)") # Commit conn.commit() # Query cur.execute("SELECT * FROM student") print(cur.fetchall()) # Delete cur.execute("DELETE FROM student WHERE name='Bob'") # Update cur.execute("UPDATE student SET studentNumber=987654 WHERE name='John'") # Commit conn.commit() # Query cur.execute("SELECT * FROM student") print(cur.fetchall())

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import ffmpeg_streaming from ffmpeg_streaming import Formats, Bitrate, Representation stream = ffmpeg_streaming.input('https://mnmedias.api.telequebec.tv/m3u8/29880.m3u8') video = stream.video.filter('fps', fps=30, round='up') video = video.filter('scale', width=1280, height=720) audio = stream.audio.filter('aformat', channel_layouts='mono') output = ffmpeg_streaming.output(stream, 'rtmp://a.rtmp.youtube.com/live2/m2k2-ttgv-wyzt-8xnx', format=Formats.hls, acodec='aac', vcodec='libx264', strict='experimental', hls_time=10, hls_list_size=0) output.run()

Python
View
generate functionThu, 29 Dec 2022

program which will generate flowchart of codes given by user

import pygame import os import glob def list_all_images(directory): return [os.path.basename(f) for f in glob.glob(directory + "*")] def draw_flowchart(draw, flowchart_input_text, flowchart_output_text, flowchart_flow_text): print(flowchart_input_text) print(flowchart_output_text) print(flowchart_flow_text) flowchart_input_array = flowchart_input_text.split(',') flowchart_output_array = flowchart_output_text.split(',') flowchart_flow_array = flowchart_flow_text.split(',') for i in range(0, len(flowchart_input_array)): draw.rect(screen, (0,0,0), (100,100+50*i, 40, 40), 0) draw.rect(screen, (0,0,0), (100,100+50*i+40,

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python using Avcon .

import subprocess def main(): m3u8_url = "http://localhost:8080/master.m3u8" stream_title = "mylive" stream_privacy = "public" rtmp_server = "rtmp://a.rtmp.youtube.com/live2" rtmp_key = "12345-abcde-678910-fghij" subprocess.call([ 'ffmpeg', '-i', m3u8_url, '-acodec', 'copy', '-vcodec', 'copy', '-f', 'flv', rtmp_server + '/' + rtmp_key ]) if __name__ == "__main__": main()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from pytube import YouTube from pytube.extract import apply_descrambler from pytube.request import apply_signature from pytube.exceptions import RegexMatchError from pytube.helpers import safe_filename from pytube.helpers import safe_get from pytube.helpers import safe_print from pytube.helpers import remove_quotes from pytube.helpers import unescape from pytube.helpers import video_extension from pytube.helpers import video_id from pytube.helpers import yt_url_validation from pytube.helpers import Caption from pytube.helpers import CaptionQuery from pytube.helpers import Stream from pytube.helpers import StreamQuery from pytube.helpers import CaptionTrack from pytube.contrib import annotations from pytube.contrib import caption_converter from pytube.contrib import app from pytube.contrib import request from pytube.contrib import extract from pytube.contrib import download from pytube.contrib import play

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to youtubein python using rtmpy

import rtmpy # connect to the stream stream = rtmpy.Connection('rtmp://a.rtmp.youtube.com/live2/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', live=True) # send the stream stream.connect() stream.create_stream() stream.publish('live', 'live') stream.write(open('/path/to/file.mp3', 'rb').read())

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python using Streamlink

import subprocess import os import argparse def stream(url, path): subprocess.call(["streamlink", url, "best", "-o", path]) if __name__ == '__main__': parser = argparse.ArgumentParser(description='CLI') parser.add_argument('-i', '--input', help='Input URL', required=True) parser.add_argument('-o', '--output', help='Output File', required=True) args = vars(parser.parse_args()) stream(args['input'], args['output'])

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

- 通常来说,在代码中,我们使用的是四个空格(或者是Tab符号),而不是空格,但是在Markdown中,空格+空格,那么就会有换行的效果,所以需要在Markdown正文中的代码中使用四个空格,而在代码中使用四个空格或者Tab符号。 - 在Markdown标记语言中,如果你想要在代码中使用四个空格

generate functionSun, 04 Dec 2022

import ffmpeg URL = input("Enter here: /n") stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) ## enhance the above code.

def convert(url): stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) convert("Enter URL here")

Python
View
generate functionTue, 03 Jan 2023

function for printing centralized words

def print_centered_line(text): text = str(text) text_len = len(text) left_spaces = (80 - text_len) // 2 right_spaces = (80 - text_len) - left_spaces print(' ' * left_spaces, text, ' ' * right_spaces, sep='') print_centered_line('spam and eggs') print_centered_line('spam, spam and eggs') print_centered_line(12) print_centered_line('spam, spam, spam and eggs')

Python
View
generate functionTue, 03 Jan 2023

centralize the printed output in python using shutil

import shutil def print_centralized(string, symbol=1): """ print a string to the center of the terminal :param string: The string to print :param symbol: The width of the symbol (1 or 2) :return: None """ term_size = shutil.get_terminal_size() break_line = (term_size.columns - len(string)) // 2 if symbol == 1: begin = "| " + "-" * break_line end = "-" * break_line + " |" else: begin = "|-" + "-" * break_line end = "-" * break_line + "-|" print(begin + string + end)

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/index.m3u8 # remove the lines starting with [youtube] from stdout (no function)

from subprocess import Popen, PIPE, STDOUT f = open('youtube_download.out', 'w') out = Popen(["youtube-dl", "Nq2wYlWFucg"], stdout=PIPE, stderr=STDOUT) for line in iter(out.stdout.readline, b''): f.write(line.decode('utf-8'))

Python
View
generate functionSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main() # fix the above invalid code

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else:

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

import requests from bs4 import BeautifulSoup import re import os #url = 'https://www.imdb.com/title/tt7286456/episodes' url = 'https://www1.gogoanime.io/category/slam-dunk' response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") # print(soup.prettify()) episodes_links = [] episode_name = [] for link in soup.findAll('a'): if '/watch' in link.get('href'): episodes_links.append(link.get('href')) episode_name.append(link.get('title')) # print(episodes_links) # print(episode_name) # The episodes_links contains all the episodes links. # Let's say we want to see the first episode. for i in range(len(episodes_links)): # html = requests.get("http://www1.gogoan

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python (no function)

import subprocess import os import time #ffmpeg -i 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8' -c copy -bsf:a aac_adtstoasc -f flv rtmp://a.rtmp.youtube.com/live2/zpc3-3uq3-9x7p-g5q6 ffmpegCmd = 'ffmpeg -re -i "http://live.chosun.gscdn.com/live/tvchosun1.m3u8" -c copy -bsf:a aac_adtstoasc -f flv rtmp://a.rtmp.youtube.com/live2/zpc3-3uq3-9x7p-g5q6' subprocess.run(ffmpegCmd, shell=True)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size import os import sys if len(sys.argv) <= 2: print('Usage: program.py <url> <youtubelive-streamkey>') exit() url = sys.argv[1] stream_key = sys.argv[2] # python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module stream = FFMPEG_Streaming_Video_to_YoutubeLive(url, stream_key, format=Formats.hls, representation=Representation(Size(640, 360), Bitrate(400)), representation=Representation(Size(854, 480), Bitrate(800)), representation=Representation(Size(1280, 720), Bitrate(1600))) stream.start() # to stop the stream stream.stop()

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using rtmpy.

import rtmpy import time def stream(stream_name, url): """ Function to stream m3u8 url to rtmp """ r = rtmpy.RTMP( rtmp='rtmp://a.rtmp.youtube.com/live2', app='app', playpath=stream_name, swfUrl='http://www.twitch.tv/widgets/live_embed_player.swf?hostname=www.twitch.tv&channel=' + stream_name + '&auto_play=true&start_volume=25', tcUrl='rtmp://a.rtmp.youtube.com/live2', pageUrl='http://www.twitch.tv/' + stream_name, live=True ) r.connect() r.publish(stream_name) r.stream('http://www.twitch.tv/' + stream_name + '/hls/' + url + '.m3u8') time.sleep(5) stream('

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

# the above code is the output of a program now remove: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

![calculator_output](https://user-images.githubusercontent.com/54179065/65385323-e6c8b800-ddb2-11e9-8f36-9af7a3c3e3f7.png) ## MACHINE LEARNING **1) K-NEAREST NEIGHBOURS(KNN)** * KNN is a supervised machine learning algorithm which can be used for both classification as well as regression problems. But it is mostly used in classification problems. * KNN is a non-parametric and lazy learning algorithm. Non-parametric means there is no assumption for underlying data distribution. In other words, the model structure determined from the dataset. This will be very helpful in practice where most of the real world datasets do not follow mathematical theoretical assumptions. Lazy algorithm means it does not need any training data points for model generation. All training data used in the testing phase. This makes training faster and testing phase slower and costlier. Costly testing phase means time and memory. * KNN algorithm uses ‘feature similarity’ to predict the

generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: o ALTER table to add new attributes / modify data type / drop attribute o UPDATE table to modify data o ORDER By to display data in ascending / descending order o DELETE to remove tuple(s) o GROUP BY and find the min, max, sum, count and average

import pandas as pd student = pd.DataFrame({ 'ID': [1, 2, 3, 4, 5, 6], 'Name': ['A', 'B', 'C', 'D', 'E', 'F'], 'Gender': ['M', 'F', 'M', 'M', 'F', 'M'], 'Age': [18, 19, 20, 21, 22, 23], 'Grade': [2, 1, 4, 3, 2, 4] }) # ALTER table to add new attributes / modify data type / drop attribute student['City'] = ['B', 'A', 'C', 'A', 'B', 'C'] student['Grade'] = student['Grade'].astype('category') student.drop(['City'], axis=1) # UPDATE table to modify data student['Name'] = ['AA', 'BB', 'CC', 'DD', 'EE', 'FF'] student['Gender'] = 'M' student.loc[student['ID'] = 1, 'Grade'] = 2

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: o ALTER table to add new attributes / modify data type / drop attribute o UPDATE table to modify data o ORDER By to display data in ascending / descending order o DELETE to remove tuple(s) o GROUP BY and find the min, max, sum, count and averag

class Student: def __init__(self, name, age, grade): self.name = name self.age = age self.grade = grade # 0 - 100 def get_grade(self): return self.grade class Course: def __init__(self): self.students = [] def add_student(self, student): if len(self.students) < 30: self.students.append(student) def get_average_grade(self): value = 0 for student in self.students: value = value + student.get_grade() return value / len(self.students) s1 = Student("Tim", 19, 95) s2 = Student("Bill", 19, 75) s3 = Student("Jill", 19, 65) course = Course() course.add_student(s1) course.add_student(s2) course.add_student(s3) course.

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: 1. ALTER table to add new attributes / modify data type / drop attribute 2. UPDATE table to modify data 3. ORDER By to display data in ascending / descending order 4. DELETE to remove tuple(s) 5. GROUP BY and find the min, max, sum, count and average

import sqlite3 connection = sqlite3.connect("database.db") DB_cursor = connection.cursor() DB_cursor.execute("CREATE TABLE students (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL, sex TEXT NOT NULL)" ) DB_cursor.execute("INSERT INTO students (name, age, sex) VALUES ('John', '21', 'M')") DB_cursor.execute("INSERT INTO students (name, age, sex) VALUES ('Mary', '25', 'F')") connection.commit() DB_cursor.execute("SELECT * FROM students") DB_cursor.execute("SELECT name, sex FROM students") DB_cursor.execute("ALTER TABLE students ADD COLUMN school TEXT") DB_cursor.execute("ALTER TABLE students MODIFY age INTEGER") DB_cursor.execute("ALTER TABLE students DROP COLUMN school") DB_cursor.execute("UPDATE

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLSStream, HLSStreamWriter, HLSStreamWriterError src = 'http://hls.nokia.com/nokia/Nokia_LTE_Dummy_H264_2M/Nokia_LTE_Dummy_H264_2M.m3u8' hls = HLSStreamWriter(src, stream_name='stream') hls.streams.append(HLSStream('out.m3u8', bitrate=Bitrate(1280, 'k'), representation=Representation(size=Size(1280, 720)), format=Formats.h264())) hls.start()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.mp4", codec='libx264', audio_codec='aac')

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 linkto rtmp in python using PyM3u8 .

import pym3u8 import http.client import urllib.request import urllib.parse import urllib.error import base64 import subprocess import threading import time import json # You must provide an m3u8 playlist url. The program will download the m3u8 # and segment files as they are listed in the m3u8 file. The files will be # downloaded to the current directory. # The program will merge the files into a single file called # merged_stream.ts # The program will then stream the file to the address you set below. # The program will then loop and check the playlist every 60 seconds. # If changes are detected the program will download and stream any new # segments to the rtmp server. # # m3u8 file: https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to rtmp server using moviepy module you can also modify this code to do so: from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

from moviepy.editor import VideoFileClip # Replace with the actual M3U8 URL url = "https://xxxxxxx.m3u8" # Open the video file clip = VideoFileClip(url) # Set the codecs and other options clip = clip.set_fps(30).set_audio_fps(44100).set_audio_bitrate(128) # Write the video to file clip.write_videofile("output.flv", codec='libx264', audio_codec='aac')

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

# Exercise 3 > Practice Exe03.py and Exe04.py. # Exercise 4 > Practice Exe03.py and Exe04.py.

generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

import re re.sub(r'\[youtube\].*?\n', '', output)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using PyM3u8 .

def stream_file(self, url, duration=0): """ Stream file from url to rtmp server :param url: url of file :param duration: duration in seconds of file to stream, 0 for entire file """ if 'm3u8' in url: self.stream_m3u8(url, duration) else: raise NotImplementedError('Only m3u8 streaming is supported at this time')

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python

import requests import re import time import subprocess def get_m3u8(url): #url = "http://douyu.com/lapi/live/getPlay/96419" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} response = requests.get(url, headers=headers) data = response.text strinfo = re.compile('hls_url="(.*?)"') result = strinfo.findall(data) #print(result[0]) return result[0] def stream(url): print('start') p = subprocess.Popen(['ffmpeg', '-i', url, '-c:v', 'libx264', '-c:a', 'aac', '-strict', '-2', '-f', '

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg and no function)

using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string url = "http://hls.cnr.cn/live/hls/cctv4_2/index.m3u8"; var request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 10000; request.Method = "GET"; request.KeepAlive = false; using (var response = (HttpWebResponse)request.GetResponse()) { using (var stream = response.GetResponseStream()) using (var reader = new System.IO.StreamReader(stream)) { var result = reader.ReadToEnd(); var lines = result.Split('\n'); foreach (var i in lines) { if (i.StartsWith("http")) { var f =

generate functionTue, 06 Dec 2022

live stream m3u8 to youtube in python using rtmpy

import subprocess import os def runstream(m3u_url): # runs FFMPEG to stream the live m3u8 to youtube # requires ffmpeg installed and environment variable set subprocess.Popen("ffmpeg -re -i " + m3u_url + " -c copy -f flv rtmp://a.rtmp.youtube.com/live2/" + os.getenv("YOUTUBE_STREAM_KEY")) pass runstream("https://mylivestream.com/hls/mystream.m3u8")

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using rtmpy.

import rtmpy # create the client client = rtmpy.Client() client.connect('rtmp://localhost/stream') # publish the stream client.publish('rtmp://streaming.server.com/stream.m3u8') # disconnect client.disconnect() # the default connection parameters are { 'app': 'stream', 'port': 1935, 'flash_ver': 'FMLE/3.0 (compatible; FMSc/1.0)', 'swf_url': 'http://streaming.server.com/example/stream.swf', 'tc_url': 'rtmp://streaming.server.com', 'page_url': 'http://streaming.server.com', 'video_size': (640, 480) }

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using Videostream .

import videostream import ffmpeg # the code is from https://github.com/zachbruggeman/videostream # this is a demo to stream webcam to rtmp server by using videostream # coding=utf-8 # 以下是在docker環境下使用videostream這個package,將webcam的畫面轉成rtmp檔案 # 轉檔案的過程,基本上只要有ffmpeg的指令就可以做到,但很麻煩,因此使用videostream這個package簡化 # 這個package使用python執行,可以直接在docker中執行,不

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using Streamz.

import streamz from streamz import Stream import ffmpeg import time import os # m3u8 url url = 'http://hls-dvr-prod-us-west-1.hls.ttvnw.net/v1/playlist/hU2mEJ6YwZ6_0fHx4HBduA.m3u8?signature=4ae3e3a5d5a5b5de5c5f0d1aaf7fefbd&sig=c9a2b0fceb2f65ccae727f1c80d6b2c2&expire=1543979200&allow_source=true' # rtmp url rtmpUrl = 'rtmp://live-dfw.twitch.tv/app/live_230751265_RgYvN8rjWq3EqCe3qyFbvXKWgZuJzc' # ffmpeg command cmd = ffmpeg.input(url) \ .output(

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

import subprocess def stream_m3u8_to_youtube(m3u8_url, stream_key, title, description, quality, camera_name): yt_url = "rtmp://a.rtmp.youtube.com/live2" cmd = f''' ffmpeg -v error -i {m3u8_url} -acodec copy -vcodec copy \ -f flv {yt_url}/{stream_key} -bsf:a aac_adtstoasc -c copy \ -metadata copy:title="{title}" \ -metadata copy:description="{description}" \ -metadata copy:quality="{quality}" \ -metadata copy:camera_name="{camera_name}"''' subprocess.call(cmd, shell=True)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

# libraries from ffmpeg_streaming import Formats from ffmpeg_streaming import Bitrate from ffmpeg_streaming import Formats from ffmpeg_streaming import Representation from ffmpeg_streaming import Representation from ffmpeg_streaming import Streaming from ffmpeg_streaming import Streaming # url url = "https://storage.googleapis.com/shaka-demo-assets/angel-one/dash.mpd" # video stream from url stream1 = Streaming(url, timeout=10).streams[0] # video creation stream2 = stream1.stream(Representation(128000, 'mp4a.40.2', 'en', 'audio/mp4', 'aac', Bitrate(128000, 128000))) # upload to youtube stream2.output('output.mp4', format=Formats.mp4, audio_bitrate=128000)

Python
View
generate functionSun, 04 Dec 2022

Program to stream m3u8 url to rtmp in python using Streamz.

import os import signal import subprocess from streamz import Stream from streamz.dataframe import DataFrame from streamz.dataframe import DataFrame def run_command(command): return subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=os.setsid, ) def kill_process_tree(pid, sig=signal.SIGTERM): """Kill an entire process tree (including grandchildren) with signal "sig" and return a (gone, still_alive) tuple. "gone" is a list of os.waitpid() style results for all the children that were killed. "still_alive" is a list of pid's that were alive before the signal was sent that were still alive after it was sent. """ assert pid != os.getpid(), "error: cannot kill self" parent = psutil.Process(pid) children

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size def main(): input_stream = "http://hls.iptv.ge/stream/content/b054634c-8cbe-47ce-98f0-eba51e7c9f82/playlist.m3u8" output_file_path = "out.mp4" output_stream = "rtmp://a.rtmp.youtube.com/live2/[youtube_code]" formats = Formats( format_id='mp4', format_note='mp4', format='mp4', extensions='mp4', ffmpeg_codec='libx264', ffmpeg_full_codec='libx264', audio_codec='aac', ) bitrate = Bitrate( bitrate=65536, width=1280, height=720, video_codec='h264', fps=30, ) representation =

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/index.m3u8 # remove the lines starting with [youtube] from stdout (no function)

def remove_youtube_lines(lines): for l in lines: if l.startswith('[youtube]'): continue yield l for l in remove_youtube_lines(lines): print(l) # OR for l in lines: if l.startswith('[youtube]'): continue print(l)

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg and no function)

++ #include <iostream> #include <string> #include <regex> #include <fstream> #include <streambuf> #include <memory> #include <algorithm> #include <functional> #include <map> #include <unistd.h> #include <openssl/md5.h> #include <curl/curl.h> using namespace std; #define CFG_PATH "./cfg" #define CFG_FILE "hls.cfg" #define LOG_PATH "./log" #define LOG_FILE "hls.log" void log_info(string content); void log_error(string content); void log_info(string content) { time_t now; time(&now); string time_str = ctime(&now); time_str.replace(time_str.find("\n"), 1, ""); time_str += " ";

generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyRTMP)

def stream(url): # Create an RTMPClient instance client = pyrtmp.RTMPClient(sys.argv[2], sys.argv[3], sys.argv[4]) # Connect to the RTMP server if not client.connect(): print('Could not connect to the RTMP server') return # Perform a stream publish if not client.publish(sys.argv[5]): print('Could not publish to the RTMP server') return # Stream the specified file if not client.stream(url): print('Could not stream the file') return stream('http://my.m3u8.url')

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyM3U8)

import sys import subprocess as sp import pym3u8 def get_segments(m3u8_url): playlist = pym3u8.load(m3u8_url) segments = playlist.segments return segments def streaming(m3u8_url, rtmp_url): segments = get_segments(m3u8_url) cmd = ['ffmpeg'] for segment in segments: cmd.extend(['-i', segment.uri]) cmd.extend(['-c', 'copy']) cmd.extend(['-f', 'flv']) cmd.append(rtmp_url) sp.Popen(cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL).wait() if __name__ == '__main__': m3u8_url = sys.argv[1] rtmp_url = sys.argv[2] streaming(m3u8_url, rtmp

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to rtmp in python using RTMPDump .

import os import sys def StartRTMPStream(channel_name, channel_url): os.system( r"rtmpdump -r '{0}' -o {1}.mp4".format(channel_url, channel_name) ) def StartRTMPStreamWithProxy(channel_name, channel_url, proxy_url): os.system( r"rtmpdump -r '{0}' -o {1}.mp4 --swfVfy 'http://www.ustream.tv/flash/viewer.swf' --swfUrl 'http://www.ustream.tv/flash/viewer.swf' --conn S:'http://www.ustream.tv/flash/viewer.connection.token' --conn S:'{2}'".format(channel_url, channel_name, proxy_url) )

Python
View
generate functionSun, 04 Dec 2022

stream with m3u8 to rtmp in python (no ffmpeg)

#!/usr/bin/python import requests import subprocess import time url = "https://video.afreecatv.com/playlist/vod/playlist_cdn.m3u8?key=%s&p=%s&user=%s&code=%s" key='5a5b5c5d5e5f' p='1' user='1234' code='1234' url = (url % (key,p,user,code)) res = requests.get(url, stream=True) with open("list.m3u8", "wb") as f: for chunk in res.iter_content(chunk_size=1024): if chunk: f.write(chunk) for line in open("list.m3u8", "rb").readlines(): if line[0:4] == b"http": url = line.strip() print(url) subprocess.call("ffmpeg -i %s -c copy -

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import youtube_upload from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python (no function)

import subprocess import time while True: p = subprocess.Popen(["ffmpeg", "-re", "-i", "http://example.com/my.m3u8", "-acodec", "copy", "-vcodec", "copy", "-f", "flv", "rtmp://example.com/live/mystream"]) print("live stream started") p.wait() print("live stream stopped") time.sleep(2)

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg and no function)

def m3u8_to_rtmp_flv(m3u8_url, rtmp_url): ts_urls = [urljoin(m3u8_url, url) for url in re.findall(r'(/.*?\.ts)', requests.get(m3u8_url).text)] ts_urls = ts_urls if ts_urls: ts_url = random.choice(ts_urls) response = requests.get(ts_url, stream=True) if response.status_code == 200: print("Streaming:", ts_url) return ffmpeg_stream(response, rtmp_url) def ffmpeg_stream(response, rtmp_url): ffmpeg_cmd = ['ffmpeg', '-y', '-i', '-', '-c', 'copy', '-f', 'flv', rtmp_url] proc = Popen(ffmpeg_cmd, stdin=PIPE, stderr=P

generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: o ALTER table to add new attributes / modify data type / drop attribute o UPDATE table to modify data o ORDER By to display data in ascending / descending order o DELETE to remove tuple(s) o GROUP BY and find the min, max, sum, count and averag

import sqlite3 conn = sqlite3.connect('student.db') print("Opened database successfully") conn.execute('''CREATE TABLE STUDENT (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), MARKS INT);''') print("Table created successfully") conn.execute("INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,MARKS) \ VALUES (1, 'Paul', 32, 'California', 200)"); conn.execute("INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,MARKS) \ VALUES (2, 'Allen', 25, 'Texas', 500)"); conn.execute("INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,MARKS) \ VALUES (3, 'Teddy', 23, 'Norway', 200)"); conn.execute("INSERT INTO STUDENT (ID,NAME

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import ffmpeg from livestreamer import Livestreamer, StreamError from livestreamer.stream import RTMPStream from livestreamer.plugins import Plugin, PluginError, NoStreamsError from livestreamer.stream import RTMPStream from livestreamer.compat import urlparse, urljoin, bytes, str from livestreamer.plugin import Plugin from livestreamer.plugin.api import http from livestreamer.exceptions import (NoPluginError, NoStreamsError, PluginError, StreamError) from livestreamer.stream import StreamProcess from livestreamer.stream.flvconcat import FLVTagDemuxer, FLVTagMuxer, FLVTagParseError class YoutubeLive(Plugin): @classmethod def can_handle_url(self, url): return "youtube" in url def _get_streams(self): self.logger.debug("Fetching stream info") # This URL is used for fetching the RTMP URL res = http.get(self.url) url = urljoin(

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg and no function)

def m3u8_to_rtmp(m3u8_url, rtmp_url): # m3u8_url = "https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8" # rtmp_url = "rtmp://localhost:1935/live/stream" key_uri = m3u8_url.split("/")[-1] m3u8_dir_path = "./" + key_uri ts_file_list = [] ts_file_name = [] ts_path_list = [] ts_path_name = [] print("key_uri:%s" % key_uri) if not os.path.exists(m3u8_dir_path): os.mkdir(m3u8_dir_path) # print(m3u8_url) r = requests.get(m3u8_url) with open(key_uri, "

Python
View
generate functionMon, 05 Dec 2022

live stream m3u8 to rtmp in python (no function)

import subprocess import time try: while True: process = subprocess.Popen("ffmpeg -i 'http://xxx/xxx.m3u8' -c copy -f flv 'rtmp://xxx/xxx/xxx'", shell=True, stdout=subprocess.PIPE) time.sleep(5) except KeyboardInterrupt: print("\nCtrl-C pressed. Shutting down.")

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLS, DASH stream = HLS( Formats.h264(), Size(width=1280, height=720), Bitrate(128, 128), Representation(720, 1080) ) stream.add_input("https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8").output("../output.m3u8").run()

Python
View
generate functionFri, 02 Dec 2022

Create a binary file with name and roll number. Search for a given roll number and display the name, if not found display appropriate message

def create(name, roll_no): file = open("student.txt", 'w') file.write("Name: " + name + "\n") file.write("Roll number: " + roll_no) file.close() def search(roll_no): file = open("student.txt", 'r') for line in file: if line.startswith("Roll number:"): if line[13:] == roll_no: print("Found") return print("Not Found") create("Rohan", "17BCE0522") search("17BCE0522")

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyffmpeg

import pyffmpeg input_url = "http://example.com/test.m3u8" output_url = "rtmp://127.0.0.1/live/test" stream = pyffmpeg.VideoStream() stream.open(input_url) out = pyffmpeg.VideoOutput(output_url, stream.streams[0].width, stream.streams[0].height, "flv", "libx264") while True: frame = stream.get_frame() if not frame: break out.write_frame(frame) out.close() stream.close()

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using LibRtmp .

def stream_m3u8_rtmp(m3u8_url, rtmp_url): response = requests.get(m3u8_url) m3u8_content = response.content m3u8_lines = m3u8_content.split("\n") m3u8_ts_lines = [e for e in m3u8_lines if e.startswith("http")] for ts_url in m3u8_ts_lines: response = requests.get(ts_url) ts_content = response.content ts_file_name = path.basename(ts_url) print ts_file_name with open(ts_file_name, "wb") as f: f.write(ts_content) stream(ts_file_name, rtmp_url) os.remove(ts_file_name)

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove this syntax: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

def add(a, b): return a + b add(1, 2)

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 urlto rtmp in python using FLVStream .

from flvstreamer.streamer import FLVStreamer streamer = FLVStreamer() streamer.setup( url="http://wowzaec2demo.streamlock.net/vod-multitrack/_definst_/smil:ElephantsDream/ElephantsDream.smil/playlist.m3u8", is_live=False, rtmp="rtmp://a.rtmp.youtube.com/live2", app="vod-multitrack", playpath="mp4:ElephantsDream/ElephantsDream.mp4" ) streamer.start()

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLS, DASH, Format hls_stream = HLS( [ Representation(Bitrate('1000k'), Width(1920), Height(1080)), Representation(Bitrate('500k'), Width(1280), Height(720)), Representation(Bitrate('400k'), Width(1024), Height(576)), Representation(Bitrate('300k'), Width(640), Height(480)) ], [ Format(Formats.mpegts, Representation(Bitrate('0k'), Width(640), Height(480))), Format(Formats.mp4, Representation(Bitrate('0k'), Width(640), Height(480))), ], base_url='http://localhost:8000/hls/' ) dash_stream = DASH( [ Representation(Bitrate('1000k'), Width(1920), Height(1080)), Representation(Bitrate('500k'), Width(

Python
View
generate functionSun, 04 Dec 2022

stream with m3u8 to rtmp in python (no ffmpeg)

import sys import requests import ffmpeg import http import json import subprocess import streamlink import os import time import threading from urllib.parse import urlparse import datetime import dateutil.parser def m3u8(url, rtmp): # get m3u8 url from url streams = streamlink.streams(url) stream = streams["best"].url print("stream " + stream) start(stream, rtmp) def start(url, rtmp): # set up url = urlparse(url) url = url._replace(netloc='127.0.0.1:8080') url = url.geturl() rtmp = urlparse(rtmp) rtmp = rtmp._replace(netloc='127.0.0.1:1935') rtmp = rtmp.geturl() t = threading.Thread(target=thread, args=(url, rtmp)) t.start() def thread(

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import requests from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLS def main(): url = "http://www.streambox.fr/playlists/test_001/stream.m3u8" response = requests.get(url, stream=True) print(response) #print(response.text) if response.status_code == 200: representation = Representation(Bitrate(128 * 1024), Size(640, 480)) hls_stream = HLS(representation) hls_stream.parse_m3u8(response.text) path_to_save = "/home/joshua/Desktop/py-ffmpeg/media/index.m3u8" hls_stream.save(path_to_save) else: print("error") if __name__ == "__main__": main()

Python
View
translateSun, 25 Dec 2022

#include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> float A, B, C; float cubeWidth = 20; int width = 160, height = 44; float zBuffer[160 * 44]; char buffer[160 * 44]; int backgroundASCIICode = '.'; int distanceFromCam = 100; float horizontalOffset; float K1 = 40; float incrementSpeed = 0.6; float x, y, z; float ooz; int xp, yp; int idx; float calculateX(int i, int j, int k) { return j * sin(A) * sin(B) * cos(C) - k * cos(A) * sin(B) * cos(C) + j * cos(A) * sin(C) + k * sin(A) * sin(C) + i * cos(B) * cos(C); } float calculateY(int i, int j, int k) { return j * cos(A) * cos(C) + k * sin(A) * cos(C) - j * sin(A) * sin(B) * sin(C) + k * cos(A) * sin(B) * sin(C) - i * cos(B) * sin(C); } float calculateZ(int i, int j, int k) { return k * cos(A) * cos(B) - j * sin(A) * cos(B) + i * sin(B); } void calculateForSurface(float cubeX, float cubeY, float cubeZ, int ch) { x = calculateX(cubeX, cubeY, cubeZ); y = calculateY(cubeX, cubeY, cubeZ); z = calculateZ(cubeX, cubeY, cubeZ) + distanceFromCam; ooz = 1 / z; xp = (int)(width / 2 + horizontalOffset + K1 * ooz * x * 2); yp = (int)(height / 2 + K1 * ooz * y); idx = xp + yp * width; if (idx >= 0 && idx < width * height) { if (ooz > zBuffer[idx]) { zBuffer[idx] = ooz; buffer[idx] = ch; } } } int main() { printf("\x1b[2J"); while (1) { memset(buffer, backgroundASCIICode, width * height); memset(zBuffer, 0, width * height * 4); cubeWidth = 20; horizontalOffset = -2 * cubeWidth; // first cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 10; horizontalOffset = 1 * cubeWidth; // second cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 5; horizontalOffset = 8 * cubeWidth; // third cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } printf("\x1b[H"); for (int k = 0; k < width * height; k++) { putchar(k % width ? buffer[k] : 10); } A += 0.05; B += 0.05; C += 0.01; usleep(8000 * 2); } return 0; }

Python
View
generate functionFri, 02 Dec 2022

Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the file

def read_file_and_display_stat(file_name): with open(file_name, "r") as input_file: content = input_file.read() num_vow = 0 num_cons = 0 num_upper = 0 num_lower = 0 for char in content: if char in "aeiouAEIOU": num_vow += 1 elif char.isalpha(): num_cons += 1 elif char.islower(): num_lower += 1 elif char.isupper(): num_upper += 1 print("Number of vowels: " + str(num_vow)) print("Number of consonants: " + str(num_cons)) print("Number of uppercase letters: " + str(num_upper)) print("Number of lowercase letters: " + str(num_lower)) read_file_and_display_stat("functions_and_files.txt")

Python
View
generate functionMon, 28 Nov 2022

import string print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.digits) print(string.hexdigits) print(string.whitespace) print(string.punctuation) #make above commands in one command

def make_string(): import string print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.digits) print(string.hexdigits) print(string.whitespace) print(string.punctuation) make_string()

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg and no function)

def m3u8_to_rtmp(url, rtmp, timeout=10): r = requests.get(url, stream=True) chunks = [] ts_urls = [] for chunk in r.iter_content(chunk_size=1024): if chunk: chunks.append(chunk) else: m3u8_str = b''.join(chunks) ts_urls = re.findall(r'(?<=#EXTINF:)[^\n]+\n(http[^\n]+)', m3u8_str.decode('utf-8')) break ts_urls = [(url, response_headers(url)) for url in ts_urls] if not ts_urls: raise Exception("Could not get ts urls") ts_urls = sorted(ts_urls, key=lambda x: x[0]) rtmp_url = rtmp + '/' + url.split('/')[-1].split('

Python
View
generate functionSun, 27 Nov 2022

crate a hotel management python project using mysql

def create_hotel(): # create a 'hotel' database # create a 'rooms' table, with 'room_number', 'room_type', 'price' columns # create a 'guests' table, with 'guest_name', 'room_number' # create a 'bookings' table, with 'guest_name', 'room_number', 'check_in_date', 'check_out_date' columns # insert at least 3 guests into the 'guests' table # insert at least 3 bookings into the 'bookings' table pass

Python
View
generate functionFri, 02 Dec 2022

The aim of the class project is to create something that is tangible and useful using Python file handling/ Python-SQL connectivity. This should be done in groups of two to three students and should be started by students at least 6 months before the submission deadline. The aim here isto find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, of course to do some of these projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves. The students should be sensitised to avoid plagiarism and violations of copyright issues while working on projects. Teachers should take necessary measures for this

def add(a, b): return a + b add(1, 2)

Python
View
generate functionFri, 02 Dec 2022

Create a student table and insert data. Implement the following SQL commands on the student table: 1. ALTER table to add new attributes / modify data type / drop attribute 2. UPDATE table to modify data 3. ORDER By to display data in ascending / descending order 4. DELETE to remove tuple(s) 5. GROUP BY and find the min, max, sum, count and average

import sqlite3 conn = sqlite3.connect('student_records.db') c = conn.cursor() # Create table c.execute('''CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY, name text, gender text, age INTEGER, grade REAL, dept text)''') # Insert a row of data c.execute("INSERT INTO student VALUES (1, 'Mary', 'female', 20, 'A', 'CSE')") c.execute("INSERT INTO student VALUES (2, 'John', 'male', 21, 'B', 'CSE')") c.execute("INSERT INTO student VALUES (3, 'Jane', 'female', 20, 'A+', 'CSE')") c.execute("INSERT INTO student VALUES (4, 'Mike', 'male', 20, 'A+', 'CSE')") c.execute("INSERT INTO student VALUES (5, 'Tom', 'male', 21, 'B+', 'CSE')") c.execute("INS

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

import m3u8 import ffmpy import requests import youtube_dl def stream2youtube(stream_url, youtube_url): m3u8_obj = m3u8.load(stream_url) ts_list = [] for x in m3u8_obj.segments: ts_list.append(x.uri) if ts_list: for t in ts_list: if not t.startswith('http'): print(t) url = stream_url.replace(stream_url.split('/')[-1], t) r = requests.get(url, allow_redirects=True) with open(t, 'wb') as f: f.write(r.content) else: continue try: stream_url.split('/')[-1] ff = ffmpy.FFmpeg( inputs={stream_url.split('/')[-1]: None}, outputs={'output.mp

Python
View
fix invalid codeSun, 11 Dec 2022

import mysql.connector # Connect to the database db = mysql.connector.connect( host="localhost", user="root", password="", database="akshay" ) # Create a cursor to interact with the database cursor = db.cursor() cursor.execute("DROP TABLE students") cursor.execute("DROP TABLE courses") # Create a table for storing students cursor.execute(""" CREATE TABLE students ( id INT PRIMARY KEY, name VARCHAR(255), grade INT ) """) # Create a table for storing courses cursor.execute(""" CREATE TABLE courses ( id INT PRIMARY KEY, name VARCHAR(255), teacher VARCHAR(255) ) """) # Create a table for storing grades cursor.execute(""" CREATE TABLE grades ( id INT PRIMARY KEY, student_id INT, course_id INT, grade INT, FOREIGN KEY (student_id) REFERENCES students(id), FOREIGN KEY (course_id) REFERENCES courses(id) ) """) # Function to add a new student to the database def add_student(): # Prompt the user to enter student information name = input("Enter the student's name: ") grade = input("Enter the student's grade: ") # Insert the student into the database cursor.execute(f"INSERT INTO students (name, grade) VALUES ('{name}', {grade})") # Function to update a student's information def update_student(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Prompt the user to enter the updated information name = input("Enter the updated name: ") grade = input("Enter the updated grade: ") # Update the student's information in the database cursor.execute(f"UPDATE students SET name = '{name}', grade = {grade} WHERE id = {student_id}") # Function to delete a student from the database def delete_student(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Delete the student from the database cursor.execute(f"DELETE FROM students WHERE id = {student_id}") # Function to add a new course to the database def add_course(): # Prompt the user to enter course information name = input("Enter the course name: ") teacher = input("Enter the course teacher: ") # Insert the course into the database cursor.execute(f"INSERT INTO courses (name, teacher) VALUES ('{name}', '{teacher}')") # Function to update a course's information def update_course(): # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Prompt the user to enter the updated information name = input("Enter the updated name: ") teacher = input("Enter the updated teacher:") # Function to delete a course from the database def delete_course(): # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Delete the course from the database cursor.execute(f"DELETE FROM courses WHERE id = {course_id}") # Function to add a new grade to the database def add_grade(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Prompt the user to enter the grade grade = input("Enter the grade: ") # Insert the grade into the database cursor.execute(f"INSERT INTO grades (student_id, course_id, grade) VALUES ({student_id}, {course_id}, {grade})") # Function to update a grade def update_grade(): # Prompt the user to enter the grade's ID grade_id = input("Enter the grade's ID: ") # Prompt the user to enter the updated grade grade = input("Enter the updated grade: ") # Update the grade in the database cursor.execute(f"UPDATE grades SET grade = {grade} WHERE id = {grade_id}") # Function to delete a grade from the database def delete_grade(): # Prompt the user to enter the grade's ID grade_id = input("Enter the grade's ID: ") # Delete the grade from the database cursor.execute(f"DELETE FROM grades WHERE id = {grade_id}") # Function to display a student's information def display_student(): # Prompt the user to enter the student's ID student_id = input("Enter the student's ID: ") # Query the database to retrieve the student's information cursor.execute(f"SELECT * FROM students WHERE id = {student_id}") student = cursor.fetchone() # Print the student's information print(f"ID: {student[0]}, Name: {student[1]}, Grade: {student[2]}") # Function to display a course's information def display_course(): # Prompt the user to enter the course's ID course_id = input("Enter the course's ID: ") # Query the database to retrieve the course's information cursor.execute(f"SELECT * FROM courses WHERE id = {course_id}") course = cursor.fetchone() # Print the course's information print(f"ID: {course[0]}, Name: {course[1]}, Teacher: {course[2]}") # Function to display a grade def display_grade(): # Prompt the user to enter the grade's ID grade_id = input("Enter the grade's ID: ") # Query the database to retrieve the grade cursor.execute(f"SELECT * FROM grades WHERE id = {grade_id}") grade = cursor.fetchone() # Print the grade #print(f"ID: {grade # Function to display all students def display_all_students(): # Query the database to retrieve all students cursor.execute("SELECT * FROM students") students = cursor.fetchall() # Print the students for student in students: print(f"ID: {student[0]}, Name: {student[1]}, Grade: {student[2]}") # Function to display all courses def display_all_courses(): # Query the database to retrieve all courses cursor.execute("SELECT * FROM courses") courses = cursor.fetchall() # Print the courses for course in courses: print(f"ID: {course[0]}, Name: {course[1]}, Teacher: {course[2]}") # Function to display all grades def display_all_grades(): # Query the database to retrieve all grades cursor.execute("SELECT * FROM grades") grades = cursor.fetchall() # Print the grades for grade in grades: print(f"ID: {grade[0]}, Student ID: {grade[1]}, Course ID: {grade[2]}, Grade: {grade[3]}") # Main program loop while True: # Display menu print("1. Add student") print("2. Update student") print("3. Delete student") print("4. Add course") print("5. Update course") print("6. Delete course") print("7. Add grade") print("8. Update grade") print("9. Delete grade") print("10. Display student") print("11. Display course") print("12. Display grade") print("13. Display all students") print("14. Display all courses") print("15. Display all grades") print("16. Exit") choice = input("Enter your choice: ") # Add a new student if choice == "1": add_student() # Update a student's information elif choice == "2": update_student() # Delete a student elif choice == "3": delete_student() # Add a new course elif choice == "4": add_course()

code to explanationFri, 25 Nov 2022

import mysql.connector conn=mysql.connector.connect(user='root',password='root',host='localhost',database='store') myc=conn.cursor() #details given by manager o="y" while(o=="y" or o=="Y"): m=""" ,,,,*shop bill management receipt*,,,, ,,,,*tax invoice*,,,, ,,,,*AR Mart*,,,, ,,,,*shop no. 4 kanjurmarg navy colony*,,,, ,,,,*kanjurmarg 400042*,,,, ,,,,*mobile number-8421468850*,,,,""" print(m) c=str(input("enter your choice(S\C\E\G\X):")) #press S for generating stationary bill #press C for generating clothing bill #press E for generating electrical appliances bill #press G for generating grocery bill #press X to exit from program if(c=="S" or c=="s"): print("STATIONARY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=28/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<100): print("Final price:",price) elif(total>=100 and total<=800): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>800 and total<=5000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>5000 and total<=14000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>14000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("STATIONARY BILL") elif(c=="C" or c=="c"): print("CLOTHING BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) adress=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=8/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<800): print("Final price:",price) elif(total>=800 and total<=6000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>6000 and total<=11000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>11000 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("CLOTHING BILL") elif(c=="E" or c=="e"): print("ELECTRICAL APPLIANCES BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=18/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<1200): print("Final price:",price) elif(total>=1200 and total<=4000): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>4000 and total<=7000): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>7000 and total<=12000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>12000): discount=25/100 dprice=total*discount print("Final price:",price-dprice) else: print(" Sorry You Can Only Buy 41 Items At A Time") print("ELECTRICAL APPLINCES BILL") elif(c=="G" or c=="g"): print("GROCERY BILL") date=input("invoice date:") impt=int(input("no. of item purchase:")) print("details of customer") customer=str(input("customer's name:Mr./Miss:")) address=str(input("customer's adress:")) city=str(input("customer's city:")) state=str(input("customer's state:")) mobilenumber=int(input("customer's mobile number:")) total=0 maxitem=41 # maximum number of items can be purchased at a time if(impt<=maxitem): for a in range(1,impt+1): print("serial no:",a) i=str(input("item:")) rate=float(input("price of item in rupees:")) qty=int(input("quantity of item purchased:")) value=qty*rate # total price of product with no. of quantity print("Total price:",value) # total amount of particular product total=total+value # total amount of all products sql="insert into item (serial_no,item_name,price,quantity) values({},'{}',{},{})".format(a,i,rate,qty) myc.execute(sql) conn.commit() print("Items Purchased Till Now:") myc.execute('select * from item') data=myc.fetchall() for row in data: print(row) print("Total Amount:",total) gst=4/100 gtax=total*gst #gst taxed amount price=total+gtax # total amount of all products after adding gst if(total<200): print("Final price",price) elif(total>=200 and total<=500): discount=5/100 dprice=total*discount # discount amount print("Final price:",price-dprice) elif(total>500 and total<=900): discount=15/100 dprice=total*discount print("Final price:",price-dprice) elif(total>900 and total<=15000): discount=20/100 dprice=total*discount print("Final price:",price-dprice) elif(total>15000): discount=25/100 dprice=total*discount print("Final price:",price-dprice)#final price is calculated after adding gst else: print(" Sorry You Can Only Buy 41 Items At A Time") print("GROCERY BILL") elif(c=="x" or c=="X"): exit() else: print("PLEASE ENTER A VALID PRODUCT CATEGORY") print(" S for generating stationary bill") print(" C for generating clothing bill") print(" E for generating electrical appliances bill") print(" G for generating grocery bill") t=""" ,,,,,,,THANK YOU,,,,,,, ,,,,VISIT US AGAIN,,,, ,ARMart@modernworld.in,""" print(t) o=input("want to run again y/n or Y/N") bill generation.py Displaying bill generation.py.

generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (with pyRTMP)

def stream_m3u8(url, rtmp_url): t = threading.Thread(target=stream_m3u8_thread, args=(url, rtmp_url)) t.start() return str(t.ident) def stream_m3u8_thread(url, rtmp_url): ts_segments = m3u8_to_ts(url) ts_segments = ts_segments + " \n" log_info("stream start") for chunk in iter(lambda: ts_segments, ''): rtmp_stream.write(chunk) rtmp_stream.close() log_info("stream end") #os._exit(0)

Python
View
generate functionFri, 02 Dec 2022

Create a binary file with roll number, name and marks. Input a roll number and update the marks

import os from os.path import isfile def create_file(roll_no, name, marks): #Check if file exists if isfile("students.txt"): #File Exists with open("students.txt", "a") as students_file: students_file.write("\n" + str(roll_no) + "\t" + name + "\t" + str(marks)) else: #Create a new file with open("students.txt", "w") as students_file: students_file.write("Roll Number\tName\tMarks") students_file.write("\n" + str(roll_no) + "\t" + name + "\t" + str(marks)) def update_marks(roll_no, new_marks): with open("students.txt", "r") as students_file: lines = students_file.readlines() with open("students.txt", "w") as students_file: for line in lines

Python
View
generate functionSun, 04 Dec 2022

import ffmpeg URL = input("Enter here: /n") stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) ## use some other code instead of "ffmpeg.run(stream)"

import ffmpeg URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLS, DASH, RTMP out1 = HLS( name="video_out", formats=[Formats.h264(), Formats.mpegts()], # see Formats map="video_out", hls_list_size=3, # keep 3 hls files hls_time=4, # 4 seconds hls_flags="split_by_time", # or split_by_time, append_list or omit ) out2 = DASH( name="video_out", formats=[Formats.h264(), Formats.vp9()], # see Formats map="video_out", dash_segment_duration=3, # 3 seconds ) out3 = RTMP( name="video_out", format=Formats.h264(), # see Formats map="video_out", rtmp_live

Python
View
generate functionMon, 28 Nov 2022

import string print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.digits) print(string.hexdigits) print(string.whitespace) print(string.punctuation) #print above commands in one command

def print_all_ascii(): import string print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.digits) print(string.hexdigits) print(string.whitespace) print(string.punctuation) print_all_ascii()

Python
View
generate functionThu, 02 Mar 2023

create a python program to stream video from m3u8 url to youtube using python ffmpeg video streaming modules (do not create function)(do not use subprocess)

from ffmpy import FFmpeg ff = FFmpeg( inputs={'https://www.wowza.com/_h264/BigBuckBunny_115k.m3u8': None}, outputs={'rtmp://a.rtmp.youtube.com/live2/gke2-exa7-u2jf-m7bz': '-c:v libx264 -c:a aac -ar 44100 -ac 2 -b:v 1500k -b:a 96k -pix_fmt yuv420p -profile:v main -s 1280x720 -preset veryfast -g 60 -r 30'} ) ff.run()

Python
View
generate functionSun, 04 Dec 2022

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") ## print("The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") from the above result

def add(a, b): return a + b add(1, 2)

Python
View
generate functionSun, 04 Dec 2022

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") ## remove "The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." from the above result and print the statement (no function)

s = "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." print(s[:s.find("The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.")])

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLSStream, format_bitrate, Representation stream = HLSStream(input_path='m3u8 url', output="youtube url") stream.parse_codec_data() bitrate = Bitrate( 128, 128 ) size = Size( 320, 240 ) stream.generate_representations( bitrate, size, ) stream.start(capture_output=True)

Python
View
translateSun, 25 Dec 2022

#include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> float A, B, C; float cubeWidth = 20; int width = 160, height = 44; float zBuffer[160 * 44]; char buffer[160 * 44]; int backgroundASCIICode = '.'; int distanceFromCam = 100; float horizontalOffset; float K1 = 40; float incrementSpeed = 0.6; float x, y, z; float ooz; int xp, yp; int idx; float calculateX(int i, int j, int k) { return j * sin(A) * sin(B) * cos(C) - k * cos(A) * sin(B) * cos(C) + j * cos(A) * sin(C) + k * sin(A) * sin(C) + i * cos(B) * cos(C); } float calculateY(int i, int j, int k) { return j * cos(A) * cos(C) + k * sin(A) * cos(C) - j * sin(A) * sin(B) * sin(C) + k * cos(A) * sin(B) * sin(C) - i * cos(B) * sin(C); } float calculateZ(int i, int j, int k) { return k * cos(A) * cos(B) - j * sin(A) * cos(B) + i * sin(B); } void calculateForSurface(float cubeX, float cubeY, float cubeZ, int ch) { x = calculateX(cubeX, cubeY, cubeZ); y = calculateY(cubeX, cubeY, cubeZ); z = calculateZ(cubeX, cubeY, cubeZ) + distanceFromCam; ooz = 1 / z; xp = (int)(width / 2 + horizontalOffset + K1 * ooz * x * 2); yp = (int)(height / 2 + K1 * ooz * y); idx = xp + yp * width; if (idx >= 0 && idx < width * height) { if (ooz > zBuffer[idx]) { zBuffer[idx] = ooz; buffer[idx] = ch; } } } int main() { printf("\x1b[2J"); while (1) { memset(buffer, backgroundASCIICode, width * height); memset(zBuffer, 0, width * height * 4); cubeWidth = 20; horizontalOffset = -2 * cubeWidth; // first cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 10; horizontalOffset = 1 * cubeWidth; // second cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 5; horizontalOffset = 8 * cubeWidth; // third cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } printf("\x1b[H"); for (int k = 0; k < width * height; k++) { putchar(k % width ? buffer[k] : 10); } A += 0.05; B += 0.05; C += 0.01; usleep(8000 * 2); } return 0; }

#include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> float A, B, C; float cubeWidth = 20; int width = 160, height = 44; float zBuffer[160 * 44]; char buffer[160 * 44]; int backgroundASCIICode = '.'; int distanceFromCam = 100; float horizontalOffset; float K1 = 40; float incrementSpeed = 0.6; float x, y, z; float ooz; int xp, yp; int idx; float calculateX(int i, int j, int k) { return j * sin(A) * sin(B) * cos(C) - k * cos(A) * sin(B) * cos(C) + j * cos(A) * sin(C) + k * sin(A) * sin(C) + i * cos(B) * cos(C); } float calculateY(int i, int j,

Python
View
generate functionSun, 04 Dec 2022

import ffmpeg URL = input("Enter here: /n") stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream) ## enhance the above code.

def getStream(youtubeUrl): URL = input("Enter here: /n") stream = ffmpeg.input(URL) stream = ffmpeg.output(stream, 'rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx', format='flv', vcodec="copy", acodec="aac", ac="2", ar="44100", ab="128k", strict="-2", flags="+global_header", bufsize="3000k") ffmpeg.run(stream)

Python
View
generate functionSun, 04 Dec 2022

print("Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.") ## remove "The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." from the above result and print the statement.

a = "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed." print(a) print(a.replace("The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.", " "))

Python
View
generate functionMon, 28 Nov 2022

password generator using random module (no function)

import random digits = list(range(10)) lower_alpha = list(map(chr, range(97, 123))) upper_alpha = list(map(chr, range(65, 91))) all_chars = digits + lower_alpha + upper_alpha def password_generator(length): pw = random.choices(all_chars, k=length) return "".join(pw) password_generator(10)

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove this syntax: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

def youtube_download(url): ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) youtube_download('https://www.youtube.com/watch?v=Nq2wYlWFucg')

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

#!/usr/bin/env python from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLSStream import requests from bs4 import BeautifulSoup from urllib.request import urlopen # Getting the M3U8 URL url = 'https://github.com/lazyadmin/python-ffmpeg-video-streaming/blob/master/sample.m3u8' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') link = soup.pre.text # Getting the stream object stream = HLSStream(link) # Get the available formats print('Available formats:') for f in stream.formats: print(f) # Get the available profiles print('\nAvailable profiles:') for p in stream.profiles: print(p) # Get the available subtitles print('\nAvailable subtitles:') for s in stream.subtitles: print(s)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import HLS, Media, Output from ffmpeg_streaming.inputs import Input from datetime import datetime from random import randint from time import sleep import os from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. CLIENT_SECRETS_FILE = "client_secret.json" # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account and requires requests to use an SSL connection. SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3'

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

# -*- coding: utf-8 -*- import os,time from ffmpy import FFmpeg def video_stream(url): print url video_info = FFmpeg( inputs={url: None}, outputs={'rtmp://a.rtmp.youtube.com/live2/[youtube_key]': None} ).run() print 'start' time.sleep(2) print video_info if __name__ == '__main__': url = 'http://url.m3u8' video_stream(url)

Python
View
generate functionTue, 06 Dec 2022

live stream m3u8 to youtube in python using rtmpy

import subprocess import time import sys from rtmpy import RTMPClient import urllib.request import re url = str(sys.argv[1]) while True: print("updating...") response = urllib.request.urlopen(url) data = response.read() text = data.decode('utf-8') m3u8 = re.search('(?P<url>https?://[^\s]+)', text).group("url") print(m3u8) client = RTMPClient(app="live", host="rtmp://x.rtmp.youtube.com/live2", rtmp_timeout=15) client.connect() client.publish(m3u8) client.close() time.sleep(5)

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1670163677/ei/fViMY-WpI4qSjuMPoMO28A8/ip/2405:201:6011:130:55f7:e546:53f0:e17f/id/Nq2wYlWFucg.1/itag/91/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/sgoap/gir%3Dyes%3Bitag%3D139/sgovp/gir%3Dyes%3Bitag%3D160/hls_chunk_host/rr2---sn-gwpa-qxaee.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/202500/mh/ML/mm/44/mn/sn-gwpa-qxaee/ms/lva/mv/m/mvi/2/pl/47/dover/11/pacing/0/keepalive/yes/fexp/24001373,24007246/mt/1670141798/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAK6h2dfGPHnwhV_VCgruzNyvckD3aDyFakDLVuSXktECAiEA4SblyD6MAcdWR2uUJXV7oTUf8oU8J2wVtH0PxOb-SbQ%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRAIgGPgPppH5iMXZKjOorcl3WpIPwhJ6SwtynFh2xfoCThgCIGWJwcjC8dVOmyMBUhANNWwecLi2rpFHVdRpgh-vQZUt/playlist/index.m3u8 ## the above code is the output of a program now remove: [youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest

def remove(string, remove): return string.replace(remove, '') remove("this is a string", "is")

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python using PyM3u8 .

import requests import os def _get_key(): return os.environ['YOUTUBE_KEY'] def create_broadcast(title, description, scheduled_start_time): url = 'https://www.googleapis.com/youtube/v3/liveBroadcasts' headers = { 'Authorization': 'Bearer ' + _get_key(), 'Content-Type': 'application/json' } data = { 'kind': 'youtube#liveBroadcast', 'snippet': { 'title': title, 'description': description, 'scheduledStartTime': scheduled_start_time }, 'status': { 'privacyStatus': 'public' } } r = requests.post(url, headers=headers, json=data) return r.json() def create_stream(title, description): url = 'https://www.googleapis.com/youtube/v3/liveStreams' headers = {

Python
View
generate functionMon, 28 Nov 2022

password generator using random module

import random def password_generator(n): chars = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*" password = "" for i in range(n): password += random.choice(chars) return password password_generator(15)

Python
View
translateSun, 25 Dec 2022

#include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> float A, B, C; float cubeWidth = 20; int width = 160, height = 44; float zBuffer[160 * 44]; char buffer[160 * 44]; int backgroundASCIICode = '.'; int distanceFromCam = 100; float horizontalOffset; float K1 = 40; float incrementSpeed = 0.6; float x, y, z; float ooz; int xp, yp; int idx; float calculateX(int i, int j, int k) { return j * sin(A) * sin(B) * cos(C) - k * cos(A) * sin(B) * cos(C) + j * cos(A) * sin(C) + k * sin(A) * sin(C) + i * cos(B) * cos(C); } float calculateY(int i, int j, int k) { return j * cos(A) * cos(C) + k * sin(A) * cos(C) - j * sin(A) * sin(B) * sin(C) + k * cos(A) * sin(B) * sin(C) - i * cos(B) * sin(C); } float calculateZ(int i, int j, int k) { return k * cos(A) * cos(B) - j * sin(A) * cos(B) + i * sin(B); } void calculateForSurface(float cubeX, float cubeY, float cubeZ, int ch) { x = calculateX(cubeX, cubeY, cubeZ); y = calculateY(cubeX, cubeY, cubeZ); z = calculateZ(cubeX, cubeY, cubeZ) + distanceFromCam; ooz = 1 / z; xp = (int)(width / 2 + horizontalOffset + K1 * ooz * x * 2); yp = (int)(height / 2 + K1 * ooz * y); idx = xp + yp * width; if (idx >= 0 && idx < width * height) { if (ooz > zBuffer[idx]) { zBuffer[idx] = ooz; buffer[idx] = ch; } } } int main() { printf("\x1b[2J"); while (1) { memset(buffer, backgroundASCIICode, width * height); memset(zBuffer, 0, width * height * 4); cubeWidth = 20; horizontalOffset = -2 * cubeWidth; // first cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 10; horizontalOffset = 1 * cubeWidth; // second cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } cubeWidth = 5; horizontalOffset = 8 * cubeWidth; // third cube for (float cubeX = -cubeWidth; cubeX < cubeWidth; cubeX += incrementSpeed) { for (float cubeY = -cubeWidth; cubeY < cubeWidth; cubeY += incrementSpeed) { calculateForSurface(cubeX, cubeY, -cubeWidth, '@'); calculateForSurface(cubeWidth, cubeY, cubeX, '$'); calculateForSurface(-cubeWidth, cubeY, -cubeX, '~'); calculateForSurface(-cubeX, cubeY, cubeWidth, '#'); calculateForSurface(cubeX, -cubeWidth, -cubeY, ';'); calculateForSurface(cubeX, cubeWidth, cubeY, '+'); } } printf("\x1b[H"); for (int k = 0; k < width * height; k++) { putchar(k % width ? buffer[k] : 10); } A += 0.05; B += 0.05; C += 0.01; usleep(8000 * 2); } return 0; }

def add(a, b): return a + b

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import ffmpeg import io import os import subprocess as sp def generate_stream(): INRES = '1280x720' # input resolution OUTRES = '1280x720' # output resolution FPS = '30' # target FPS # URL = 'https://www.youtube.com/watch?v=bJLG97xE7Oc' # input video URL # URL = 'http://techslides.com/demos/sample-videos/small.mp4' #URL = 'http://localhost:8080/?action=stream' URL = 'https://www.youtube.com/watch?v=lWjQ2Df0w_E' # URL = 'https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4' # FFMPEG_BIN = "ffmpeg" # on Linux ans Mac OS FFMPEG_BIN = "C:/ffmpeg/bin/ffmpeg.exe" # on Windows

Python
View
generate functionTue, 03 Jan 2023

import shutil def print_full_line(): width = shutil.get_terminal_size().columns print("=" * width) print_full_line() ## minimize this code

from shutil import get_terminal_size from math import pi, sin def print_full_line(): width = get_terminal_size().columns print("=" * width) def area_of_circle(radius): return pi * (radius ** 2) def area_of_triangle(base, height): return (base * height) / 2 def area_of_sector(radius, angle): return area_of_circle(radius) * (angle / 360) def area_of_segment(radius, angle): return area_of_sector(radius, angle) - (0.5 * radius * radius * sin(angle * pi / 180)) radius = float(input("enter radius")) angle = float(input("enter angle")) print("are of circle = ", area_of_circle(radius)) print("area of triangle = ", area_of_triangle(radius, angle)) print("area of segment = ", area_of_segment(radius, angle))

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python (no ffmpeg)

def streamm3u8(m3u8url, rtmpurl): m3u8stream = urllib.urlopen(m3u8url) m3u8content = m3u8stream.read() m3u8stream.close() m3u8lines = m3u8content.splitlines() tsurl = m3u8lines[-1] tsstream = urllib.urlopen(tsurl) tsdata = tsstream.read() tsstream.close() rtmpclient = pyrtmp.RTMPClient(rtmpurl, tsdata) rtmpclient.write() rtmpclient.close()

Python
View
generate functionSun, 27 Nov 2022

crerate a hotel management python project using mysql

def hotel_management_system(customer_name, customer_id, customer_email, customer_phone_number, customer_address, customer_payment_method): return f'Customer Name: {customer_name} \n Customer ID: {customer_id} \n Customer Email: {customer_email} \n Customer Phone Number: {customer_phone_number} \n Customer Address: {customer_address} \n Customer Payment Method: {customer_payment_method}' hotel_management_system('Kwame', 7, 'kwame@gmail.com', '0900000000', 'Kumasi, Ghana', 'MTN Mobile Money')

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

def streamtoYoutube(stream_url, youtube_stream_key): stream_url = stream_url youtube_stream_key = youtube_stream_key ffmpeg_command = f"ffmpeg -use_wallclock_as_timestamps 1 -i {stream_url} -c copy -f flv rtmp://a.rtmp.youtube.com/live2/{youtube_stream_key}" return os.system(ffmpeg_command) streamtoYoutube("your_stream_url", "your_youtube_stream_key")

Python
View
generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python using Avcon .

import subprocess import os import sys import requests def stream(link, title, description, tags, category_id, privacy_status, thumbnail_path, access_token): cmd = 'avconv -i "{}" -c:v copy -c:a aac -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/{}'.format(link, access_token) cmd_ = cmd.split() subprocess.Popen(cmd_) print("Streaming started.") print("\n") print('You can watch the streaming at https://www.youtube.com/watch?v={}'.format(access_token))

Python
View
generate functionThu, 02 Mar 2023

create a python program to stream video from m3u8 url to youtube using python ffmpeg video streaming modules (do not create function)(do not use subprocess)

import ffmpeg import os import subprocess # Open a video file and recorder the file names # and durations of all the video streams. input = ffmpeg.input('C:\Users\TEMP\Downloads\hls\hls.m3u8') print('Streams:', input.streams.video) # Print the metadata of each video stream. for stream in input.streams.video: print('Metadata:', stream) # Select the first video stream and get its metadata. metadata = input.streams.video[0] # Create an output stream that is a copy of the input stream, # with the same metadata. output = ffmpeg.output(input, metadata, 'output.mkv') # Save the output stream to a file. ffmpeg.run(output)

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using python-ffmpeg-video-streaming module (do not create function)(do not use subprocess)

import os import sys from ffmpeg_streaming import Formats, Bitrate, Representation, Size from ffmpeg_streaming import H264Codec, AACCodec, CodecOptions, Formats, Representation, Size from ffmpeg_streaming import Formats, Bitrate, Representation, Size, Profile from ffmpeg_streaming import FFmpeg # url = "http://www.streambox.fr/playlists/test_001/stream.m3u8" url = "https://bitmovin-a.akamaihd.net/content/sintel/hls/playlist.m3u8" output_url = 'rtmp://a.rtmp.youtube.com/live2/********-********-****-****-********' # ffmpeg -i $url -vcodec copy -acodec copy -f flv $output_url ff = FFmpeg( inputs={url: None}, outputs={output_url: '-vcodec copy -acodec copy -f flv'} ) print(

Python
View
generate functionFri, 02 Dec 2022

The aim of the class project is to create something that is tangible and useful using Python file handling/ Python-SQL connectivity. This should be done in groups of two to three students and should be started by students at least 6 months before the submission deadline. The aim here isto find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, of course to do some of these projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves. The students should be sensitised to avoid plagiarism and violations of copyright issues while working on projects. Teachers should take necessary measures for this

def add(a, b): return a + b add(1, 2)

Python
View
generate functionMon, 28 Nov 2022

import random from string import * constants = ascii_letters + digits + punctuation print(constants) password_length = int(input("What's the length of the password? ")) password = "" for i in range(password_length): password += random.choice(constants) print(password) # do not close the above program after execution and rerun the code.

# Function that takes two numbers and returns their sum. def add(a, b): return a + b # Function that takes two numbers and returns their product. def multiply(a, b): return a * b def subtraction(a, b): return a - b print(add(1, 2)) print(multiply(1, 2)) print(subtraction(1, 2))

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/index.m3u8 # remove the lines starting with [youtube] from stdout (no function)

import subprocess def download_youtube(video_id): cmd = ['youtube-dl', '--no-playlist', '--no-warnings', '--quiet', '-f', 'mp4', 'https://www.youtube.com/watch?v={}'.format(video_id) ] subprocess.run(cmd)

Python
View
generate functionSun, 04 Dec 2022

[youtube] Nq2wYlWFucg: Downloading webpage [youtube] Downloading just video Nq2wYlWFucg because of --no-playlist [youtube] Nq2wYlWFucg: Downloading m3u8 information [youtube] Nq2wYlWFucg: Downloading MPD manifest https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/index.m3u8 # remove the lines starting with [youtube] from stdout (no function)

def get_filename(url): return url.split('/')[-1] get_filename('https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/index.m3u8')

Python
View
generate functionTue, 17 Jan 2023

create a python program to stream video from m3u8 url to youtube using moviepy.editor module

import os import sys import subprocess import moviepy.editor as mp # color class class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # fucntion to check the arguments def check_arguments(): if len(sys.argv) != 4: print(bcolors.WARNING + "Invalid arguments" + bcolors.ENDC) print("Usage: stream_to_youtube.py <m3u8_url> <youtube_url> <duration_in_seconds>") print("Example: stream_to_youtube.py https://www.sample-videos.com/video123/m3u8/hls-variant-audio

Python
View
fix invalid codeSun, 11 Dec 2022

from tkinter import * def result(a,b): print(a,b) return int(a) * int(b) def btnclick(i): operation = i if(operation == "add"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "sub"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "mul"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) elif(operation == "div"): res = result(e1.get(),e2.get()) e3.delete(0,END) e3.insert(0,res) else: pass def btnclear(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) root = Tk() root.configure(bg = "white") root.title("Calculator") root.geometry("400x500") e1 = Entry(root, font = "none 30", bg = "white",width = 30) e1.pack() e2 = Entry(root, font = "none 30", bg = "white",width = 30) e2.pack() e3 = Entry(root, font = "none 30", bg = "white",width = 30) e3.pack() B_ADD = Button(root, text = "ADD", font = "none 30",width = 10, command = lambda:btnclick("add")) B_ADD.pack() B_SUB = Button(root, text = "SUB", font = "none 30",width = 10, command = lambda:btnclick("sub")) B_SUB.pack() B_MUL = Button(root, text = "MUL", font = "none 30",width = 10, command = lambda:btnclick("mul")) B_MUL.pack() B_DIV = Button(root, text = "DIV", font = "none 30",width = 10, command = lambda:btnclick("div")) B_DIV.pack() B_EQ = Button(root, text = "EQ", font = "none 30",width = 10,command = lambda:btnclick("")) B_EQ.pack() B_CLEAR = Button(root, text = "CLEAR", font = "none 30",width = 10, command = btnclear) B_CLEAR.pack() root.mainloop() if __name__ == "__main__": main()

## 4. To fix the invalid code by using the Python AST module

generate functionMon, 05 Dec 2022

Program to stream m3u8 url to youtube in python

import requests from bs4 import BeautifulSoup import subprocess, os, sys def stream_to_youtube(m3u8_url): streamlink = "streamlink" quality = "best" youtube_stream_url = "rtmp://a.rtmp.youtube.com/live2" streamlink_cmd = [streamlink, m3u8_url, quality, "-Q", "--hls-segment-threads", "4", "--hls-live-edge", "3", "-O"] ffmpeg_cmd = ["ffmpeg", "-i", "-", "-c", "copy", "-f", "flv", youtube_stream_url] with subprocess.Popen(streamlink_cmd, stdout=subprocess.PIPE) as streamlink_process, subprocess.Popen( ffmpeg_cmd, stdin=streamlink_process.stdout, stdout=sys.stdout, stderr=sys.stderr) as ffmpeg_process: streamlink_process.

Python
View
generate functionMon, 05 Dec 2022

Program to live stream m3u8 to rtmp in python (no ffmpeg and no function)

import subprocess import threading import shlex import os import sys import urllib import time import datetime def log(s): print('[%s][%s] %s' % (datetime.datetime.now(), threading.currentThread().getName(), s)) def runCmd(cmd): try: p = subprocess.Popen(shlex.split(cmd), stdout=sys.stdout, stderr=sys.stderr) return p except Exception as e: log("Error: " + str(e)) def getFile(url): try: tmp = urllib.request.urlopen(url) return tmp.readlines() except Exception as e: log("Error: " + str(e)) def getFile2(url): try: return urllib.request.urlopen(url).read() except Exception as e: log("Error: " + str(e)) def getFile3

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python using Streamlink

def stream_m3u8(url): cwd = os.getcwd() os.chdir(os.path.join(cwd, '..', '..', '..', '..', '..', 'Streamlink', 'bin', 'streamlink')) subprocess.call(['streamlink', url, 'best', '--quiet', '--hls-live-restart', '--hls-segment-threads', '3', '--hls-segment-timeout', '30', '--hls-segment-attempts', '3', '--hls-playlist-reload', '30', '--hls-segment-timeout', '30', '-o', '-', '|', 'ffmpeg', '-i', 'pipe:0', '-c', 'copy', '-f', 'flv', 'rtmp://a.rtmp.youtube.com/live2/' + livestreamkey]) os.chdir(cwd)

Python
View
generate functionSun, 04 Dec 2022

stream m3u8 url to rtmp in python with pyffmpeg

def stream(url, rtmp): from pyffmpeg import FFmpeg from threading import Thread from time import sleep from sys import exit ff = FFmpeg( inputs={url: None}, outputs={rtmp: '-loglevel panic'} ) try: ff.run() except KeyboardInterrupt: print('\nKeyboardInterrupt') except Exception as e: print('\nException', e) finally: ff.process.kill()

Python
View

Questions about programming?Chat with your personal AI assistant