├── 1710.05006.pdf ├── 3D_cube_projection.py ├── AI_tictactoe.py ├── ARIMA1.py ├── ARIMA2.py ├── AdventureGame.py ├── CPU_meter.py ├── CRUD_app.py ├── CRUD_application.py ├── Camera.py ├── CursesControl_Demo2.py ├── FileSystem_view.py ├── FinCalc.py ├── FinanGraph.py ├── Google_finanIntraday.py ├── Honda_Goldwing.jpg ├── LTSM_model.py ├── MDI_application.py ├── OpenGL1.py ├── QR_detector_cv2.py ├── Qr_Camera.py ├── QtDigital_Clock.py ├── QtWeb_browser.py ├── README.md ├── ROC.py ├── SVD.py ├── SVD2.py ├── SnakeGame_tutorial.py ├── Sprites.zip ├── Video_Filter.py ├── Year_Calendar.py ├── _poli.py ├── adiv_numero.py ├── ajuste_retornos.py ├── anger_square.png ├── anomaly_transaction_detection.py ├── async_audioPlay.py ├── async_record.py ├── audio_book.py ├── automate_boringStuff.py ├── bezier.py ├── bezier_latest.py ├── bezier_surface.py ├── bgrer.py ├── blurring_faces_images.py ├── blurring_faces_video.py ├── bollinger.py ├── bollinger_bands.py ├── bollinger_bands_ex2.py ├── borel_cantelli.py ├── calcula_factorial.py ├── calculo_interes.py ├── calculo_interesB.py ├── calculo_retornos.py ├── car_detector.py ├── celsius_2_farenheit.py ├── cesar_hack.py ├── changing_halls_raycasting.py ├── chat.py ├── check_vid_audio.py ├── cifrado_cesar.py ├── cifrado_vigenere.py ├── clahe.py ├── clasifc_sectores_sp500.py ├── client.py ├── clipboard_copy.py ├── cmd_plot.py ├── cmd_sine.py ├── cmd_sine2.py ├── cmd_sineplot.py ├── cmd_sineplotB.py ├── coloumb.py ├── compara_imagenes.py ├── compare_image.zip ├── concurrent_futures_example.py ├── copiador.py ├── crazy_text.py ├── crea_excel.py ├── crt_image_effect.py ├── cube_3d.py ├── currency_converter.py ├── cursesControl_demo.py ├── daily_return.py ├── data_extractor.py ├── datos_google.py ├── detector_contornos.py ├── dibujar_poligonos.py ├── direct_text_to_speech.py ├── display_HTML.py ├── distributions.py ├── dob.jpg ├── drake.py ├── ejemRegresion_lineal.py ├── ejem_clases.py ├── ejem_clases2.py ├── ejemplo1_amp.py ├── ejemplo1_opencv.py ├── ejemplo_cola.py ├── ejemplo_con_map.py ├── ejemplo_grafbarras3d.py ├── ejemplo_listbox.py ├── ejemplo_pila.py ├── ejemplo_reduce.py ├── ejemplo_thread.py ├── ejemplo_thread2.py ├── ejemplo_timeit.py ├── ejemplo_wordcloud.py ├── ejemplo_zip.py ├── ejercicio_hash.py ├── email_sender.py ├── encryption.py ├── encuentra_duplicados.py ├── escribe_fichero.py ├── estimacion_pi.py ├── etf.py ├── etf_rand.py ├── exchanges.py ├── extract_imagemetadata.py ├── fileType_searcher.py ├── file_compressor.py ├── file_explorer.py ├── file_finder.py ├── file_finder_regex.py ├── frames_to_video.py ├── func_parametrica.py ├── funci.py ├── galaxy_simulator.py ├── game.py ├── gbm_plot.py ├── gbm_simulator.py ├── get_folder_size.py ├── get_foldersize.py ├── get_worldbank_info.py ├── getting_indian_cities.py ├── grabadora_sonido.py ├── grafica_barras.py ├── grafica_circular.py ├── grafica_superficie.py ├── handwritting_digits_recognizer.py ├── hangman.py ├── hangmanCLI.py ├── hash_maker_CLI.py ├── hexa_bin.py ├── hexa_to_binar.py ├── hexabin.py ├── histogram.py ├── hora_salida.py ├── image.jpg ├── image_drawing.py ├── image_extractor.py ├── image_pixelator.py ├── inserta_grafica.py ├── insertion_sort.py ├── intercala_silencios.py ├── juego_vida.py ├── koch_snowflake.py ├── lena.jpg ├── lenna.jpg ├── letra_dni.py ├── librosa_display_waveplot.py ├── lineal_regression.py ├── link_collector.py ├── live_graph.py ├── logistic_regression.py ├── lorenzAnimation_creator.py ├── macd.py ├── manipulate_cube_rotation.py ├── markowitz.py ├── merge_sort.py ├── mi_login.py ├── minimizer.py ├── minimos_cuadrados.py ├── mkgif.py ├── mod_voice.py ├── mod_voice2.py ├── modula.py ├── modula2.py ├── modulaB.py ├── modula_am.py ├── modula_am_graf.py ├── modula_audio.py ├── modulacion_am.py ├── modulacion_am_grafica.py ├── modulacion_fm.py ├── modulaciones.py ├── motion_filtering.py ├── move_tk.py ├── movement_detector.py ├── moving_blocks.py ├── muestra_foto.py ├── multiple_lineal_regression.py ├── multiple_shares_dfs.py ├── music_player.py ├── new_openglTriangle.py ├── noise_redux.py ├── noisedFrames_generator.py ├── notepad.py ├── ogl_Bezier.py ├── openGL_triangle.py ├── opensave_file.py ├── painty.py ├── painty_B.py ├── pandas2excel_example.py ├── pares_con_filter.py ├── password_manager.py ├── passwords_generator.py ├── plot_2stock_prices.py ├── pmv_inidicator.py ├── pmw_counter.py ├── practica1_cv2.py ├── primer_juego.py ├── probaility_of_detection.py ├── pygame_cube.py ├── pygame_cube2.py ├── pygame_cube3.py ├── pygame_cubeMove.py ├── pygame_test.py ├── pyqt_photo.py ├── python_code_editor.py ├── r_py.py ├── radiobutton_ejemplo.py ├── radiobuttons.py ├── random_tone_generator.py ├── random_tone_generator2.py ├── random_tone_maker.py ├── receiver.py ├── regresion_lineal.py ├── reloj_digital.py ├── reloj_digital2.py ├── reproduce_audio.py ├── reverse_cipher.py ├── robot_control.py ├── rotate_cubeOpenGL.py ├── rotate_simple_square.py ├── rotationandtraslation_cube.py ├── sapimienta.py ├── sayit.py ├── scatter.py ├── screen_assistant.py ├── sender.py ├── serializacion.py ├── server.py ├── server_expro.py ├── simple_bitcoin_miner.py ├── sine_anim.py ├── sinusoid_interact.py ├── sphere.py ├── square_anim.py ├── steganography.py ├── stereo_sound_example.py ├── stock_graph.py ├── sumaColumnas_matriz.py ├── sumaFilas_matriz.py ├── symbols.txt ├── system_info.py ├── system_info_viewfinder.py ├── tablas_logaritmos.py ├── tareas_con_hilos.py ├── tareas_sin_hilos.py ├── terminal_progress_bar.py ├── test_consti.py ├── test_normalidad.py ├── test_valoracion.py ├── testeto.py ├── tic_tac_toe.py ├── ticker_info.py ├── to_do.py ├── to_do_app.py ├── tone.py ├── trading_bot.py ├── tres_en_raya.py ├── triangle_mov.py ├── turtle_art.py ├── tutorial_painty.py ├── tutorial_painty2.py ├── ur_voice.py ├── utilid_librosaPlot.py ├── vectors.py ├── vectors2.py ├── ventana_pestañas.py ├── ver_gif.py ├── ver_imagen.py ├── vid2gif.py ├── videoCaptura_ejemplo.py ├── videoToFrames.py ├── video_compressor.py ├── weather_app.py ├── windows_logo_turtle.py └── world_population.py /1710.05006.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/1710.05006.pdf -------------------------------------------------------------------------------- /ARIMA1.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | from pandas_datareader import data as pdr 5 | import yfinance as yf 6 | from statsmodels.tsa.arima.model import ARIMA 7 | from sklearn.metrics import mean_squared_error 8 | from math import sqrt 9 | 10 | # Configure Yahoo Finance data source 11 | yf.pdr_override() 12 | 13 | # Download historical stock data 14 | ticker = "AAPL" 15 | start_date = "2020-01-01" 16 | end_date = "2021-01-01" 17 | stock_data = pdr.get_data_yahoo(ticker, start=start_date, end=end_date) 18 | 19 | # Select the closing prices 20 | closing_prices = stock_data["Close"] 21 | 22 | # Split the data into training and testing sets 23 | train_data = closing_prices[:int(len(closing_prices) * 0.8)] 24 | test_data = closing_prices[int(len(closing_prices) * 0.8):] 25 | 26 | # Fit the ARIMA model 27 | model = ARIMA(train_data, order=(1, 2, 1)) 28 | model_fit = model.fit() 29 | 30 | # Print AIC and BIC values 31 | print("AIC: ", model_fit.aic) 32 | print("BIC: ", model_fit.bic) 33 | 34 | # Forecast the stock prices using the ARIMA model 35 | forecast = model_fit.forecast(steps=len(test_data)) 36 | 37 | # Calculate the root mean squared error (RMSE) 38 | rmse = sqrt(mean_squared_error(test_data, forecast)) 39 | print("RMSE: ", rmse) 40 | 41 | # Plot the actual vs. predicted closing prices 42 | plt.figure(figsize=(12, 6)) 43 | plt.plot(train_data, label="Training data") 44 | plt.plot(test_data, label="Actual closing prices") 45 | plt.plot(test_data.index, forecast, label="Predicted closing prices") 46 | plt.xlabel("Date") 47 | plt.ylabel("Closing Price") 48 | plt.title(f"{ticker} Stock Closing Price Prediction using ARIMA") 49 | plt.legend() 50 | plt.show() 51 | -------------------------------------------------------------------------------- /CPU_meter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from tkinter import * 4 | import psutil 5 | 6 | def cpu_met(): 7 | cpu_use = psutil.cpu_percent(interval = 1) 8 | cpu_label.config(text='{}%'.format(cpu_use)) 9 | cpu_label.after(200,cpu_met) 10 | 11 | ventana = Tk() 12 | ventana.geometry("480x140") 13 | ventana.title("Total CPU Usage") 14 | ventana.configure(bg='midnight blue') 15 | cpu_label = Label(ventana,bg="black",fg="green",anchor=NE,font="Arial 30 bold",width=6) 16 | cpu_label.place(x=230,y=20) 17 | 18 | digi=Label(ventana,text="CPU Usage:",font="arial 24 bold",bg='midnight blue',fg="white") 19 | digi.place(x=20,y=25) 20 | 21 | cpu_met() 22 | 23 | ventana.mainloop() 24 | 25 | -------------------------------------------------------------------------------- /CursesControl_Demo2.py: -------------------------------------------------------------------------------- 1 | import curses 2 | import time 3 | import random 4 | from curses import textpad 5 | 6 | stdscr = curses.initscr() 7 | curses.curs_set(0) 8 | curses.noecho() 9 | curses.cbreak() 10 | stdscr.keypad(True) 11 | 12 | def main(stdscr): 13 | texto="CENTRE" 14 | sh, sw = stdscr.getmaxyx() 15 | posicion1=sh//2 16 | posicion2=sw//2 17 | #def main(stdscr): 18 | stdscr.addstr(posicion1,(posicion2)-((len(texto))//2),texto) 19 | wp=[] 20 | for i in range(12): 21 | n=random.randint(1,28) 22 | m=random.randint(1,116) 23 | stdscr.addstr(n,m,"*") 24 | wp.append((n,m)) 25 | 26 | while True: 27 | key=stdscr.getch() 28 | if key==curses.KEY_RIGHT: 29 | posicion2=posicion2+1 30 | texto="RIGHT" 31 | elif key==curses.KEY_DOWN: 32 | posicion1=posicion1+1 33 | texto="DOWN" 34 | elif key==curses.KEY_LEFT: 35 | posicion2=posicion2-1 36 | texto="LEFT" 37 | elif key==curses.KEY_UP: 38 | posicion1=posicion1-1 39 | texto="UP" 40 | current_p=(posicion1,posicion2) 41 | if current_p in wp: 42 | stdscr.clear() 43 | texto="BOOOM!" 44 | #stdscr.clear() 45 | stdscr.addstr(posicion1,(posicion2)-((len(texto))//2),texto) 46 | 47 | main(stdscr) 48 | 49 | stdscr.refresh() 50 | #time.sleep(1) 51 | stdscr.clear() 52 | 53 | curses.curs_set(1) 54 | curses.echo() 55 | curses.nocbrek() 56 | stdscr.keypad(False) 57 | 58 | 59 | curses.endwin() 60 | -------------------------------------------------------------------------------- /FileSystem_view.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | from PyQt5.QtWidgets import QApplication, QWidget, QTreeView, QFileSystemModel, QVBoxLayout 4 | from PyQt5.QtCore import QModelIndex 5 | 6 | class FileSystemView(QWidget): 7 | def __init__(self, dir_path): 8 | super().__init__() 9 | 10 | #TITULO Y DIMENSIONES DE LA VENTANA. 11 | self.setWindowTitle('File System Viewer') 12 | self.setGeometry(300, 300, 800, 300) 13 | 14 | #DEFINIR DIRECTORIO. 15 | self.model = QFileSystemModel() 16 | self.model.setRootPath(dir_path) 17 | 18 | #GENERAR VISTA DE ARCHIVOS Y CARPETAS. 19 | self.tree = QTreeView() 20 | self.tree.setModel(self.model) 21 | self.tree.setRootIndex(self.model.index(dirPath)) 22 | self.tree.setColumnWidth(200,250) 23 | self.tree.setAlternatingRowColors(True) 24 | 25 | #MOSTRAR VENTANA CON LAS VISTA. 26 | layout = QVBoxLayout() 27 | layout.addWidget(self.tree) 28 | 29 | self.setLayout(layout) 30 | 31 | 32 | if __name__ == '__main__': 33 | app = QApplication(sys.argv) 34 | 35 | #DIRECTORIO BASE. 36 | dirPath = os.getcwd() 37 | 38 | demo = FileSystemView(dirPath) 39 | demo.show() 40 | sys.exit(app.exec_()) 41 | -------------------------------------------------------------------------------- /FinCalc.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | 3 | root = Tk() 4 | root.geometry('700x300') 5 | 6 | 7 | root.mainloop() 8 | -------------------------------------------------------------------------------- /Google_finanIntraday.py: -------------------------------------------------------------------------------- 1 | from alpha_vantage.timeseries import TimeSeries 2 | 3 | ts = TimeSeries(key='YOUR_API_KEY') 4 | data, meta_data = ts.get_intraday('GOOGL') 5 | 6 | print(data) 7 | print(meta_data) 8 | -------------------------------------------------------------------------------- /Honda_Goldwing.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/Honda_Goldwing.jpg -------------------------------------------------------------------------------- /MDI_application.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication, QMainWindow, QMdiArea, QAction, QMdiSubWindow, QTextEdit 2 | import sys 3 | 4 | 5 | 6 | class MDIWindow(QMainWindow): 7 | 8 | count = 0 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.mdi = QMdiArea() 13 | self.setCentralWidget(self.mdi) 14 | bar = self.menuBar() 15 | self.name = "" 16 | file = bar.addMenu("File") 17 | file.addAction("New") 18 | file.addAction("cascade") 19 | file.addAction("Tiled") 20 | file.triggered[QAction].connect(self.WindowTrig) 21 | self.setWindowTitle("MDI Application") 22 | 23 | def WindowTrig(self, p): 24 | 25 | 26 | if p.text() == "New": 27 | MDIWindow.count = MDIWindow.count + 1 28 | sub = QMdiSubWindow() 29 | sub.setWidget(QTextEdit()) 30 | self.name = "Sub Window" + str(MDIWindow.count) 31 | sub.setWindowTitle("Sub Window" + str(MDIWindow.count)) 32 | self.mdi.addSubWindow(sub) 33 | #self.setWindowTitle("MDI Application"+"-"+self.name) 34 | sub.show() 35 | 36 | if p.text() == "cascade": 37 | self.mdi.cascadeSubWindows() 38 | 39 | if p.text() == "Tiled": 40 | self.mdi.tileSubWindows() 41 | 42 | app = QApplication(sys.argv) 43 | mdi =MDIWindow() 44 | mdi.show() 45 | app.exec_() 46 | 47 | -------------------------------------------------------------------------------- /OpenGL1.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | from OpenGL.GL import * 3 | 4 | class App: 5 | def __init__(self): 6 | pg.init() 7 | pg.display.set_mode((640,480), pg.OPENGL|pg.DOUBLEBUF) 8 | self.clock = pg.time.Clock() 9 | 10 | 11 | #glClearColor(0.0,0.0,1.0,1.0) 12 | glClearColor(0, 0, 1, 1) 13 | self.mainloop() 14 | print("hello") 15 | 16 | def mainloop(self): 17 | running = True 18 | while(running): 19 | for event in pg.event.get(): 20 | if event.type == pg.QUIT: 21 | running = False 22 | glClear(GL_COLOR_BUFFER_BIT) 23 | pg.display.flip() 24 | 25 | self.clock.tick() 26 | framerate = int(self.clock.get_fps()) 27 | pg.display.set_caption(f"Running at {framerate} fps.") 28 | 29 | self.quit() 30 | 31 | def quit(self): 32 | pg.quit() 33 | 34 | 35 | if __name__=="__main__": 36 | App() 37 | -------------------------------------------------------------------------------- /QR_detector_cv2.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | qrCode = cv2.QRCodeDetector() 4 | cap = cv2.VideoCapture(0) 5 | 6 | if not cap.isOpened(): 7 | print("No se puede abrir la camara") 8 | else: 9 | print("Camara disponible") 10 | 11 | while True: 12 | ret, frame = cap.read() 13 | 14 | if ret: 15 | ret_qr, decoded_info, points, _ = qrCode.detectAndDecodeMulti(frame) 16 | if ret_qr: 17 | for info, point in zip(decoded_info, points): 18 | if info: 19 | color = (0, 255, 0) 20 | print(info) 21 | else: 22 | color = (0, 0, 255) 23 | frame = cv2.polylines(frame, [point.astype(int)], True, color, 8) 24 | else: 25 | print("No se puede recibir fotograma....") 26 | break 27 | 28 | cv2.imshow('Detector de codigos QR',frame) 29 | 30 | if cv2.waitKey(1) & 0xFF == ord('q'): 31 | break 32 | 33 | cap.release() 34 | cv2.destroyAllWindows() 35 | -------------------------------------------------------------------------------- /QtDigital_Clock.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel 3 | from PyQt5.QtGui import QFont 4 | from PyQt5.QtCore import QTimer, QTime, Qt 5 | 6 | class AppDemo(QWidget): 7 | def __init__(self): 8 | super().__init__() 9 | 10 | #CREAMOS VENTANA. 11 | self.resize(250,150) 12 | self.setWindowTitle("Reloj digital con PyQt5") 13 | 14 | layout = QVBoxLayout() 15 | fnt = QFont('Open Sans', 120, QFont.Bold) 16 | 17 | self.lbl = QLabel() 18 | self.lbl.setAlignment(Qt.AlignCenter) 19 | self.lbl.setFont(fnt) 20 | layout.addWidget(self.lbl) 21 | 22 | self.setLayout(layout) 23 | 24 | #CREAMOS EL 'TIMER' 25 | timer = QTimer(self) 26 | 27 | timer.timeout.connect(self.displayTime) 28 | timer.start(1000) 29 | 30 | #FUNCIÓN PARA MOSTRAR HORA. 31 | def displayTime(self): 32 | currentTime = QTime.currentTime() 33 | 34 | displayText = currentTime.toString('hh:mm:ss') 35 | 36 | self.lbl.setText(displayText) 37 | 38 | #EJECUTAMOS APLICACIÓN. 39 | if __name__ == "__main__": 40 | app = QApplication(sys.argv) 41 | demo = AppDemo() 42 | demo.show() 43 | sys.exit(app.exec_()) 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ejercicios-python 2 | -------------------------------------------------------------------------------- /ROC.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader.data as web 2 | import yfinance as yfin 3 | import datetime as dt 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | 7 | start = dt.datetime(2022, 1, 1) 8 | end = dt.datetime.today() 9 | 10 | yfin.pdr_override() 11 | 12 | ticker = 'AAPL' 13 | 14 | df = web.DataReader(ticker, start, end) 15 | 16 | #df.tail() 17 | # Define the time period for calculating the ROC 18 | n = 10 19 | 20 | # Calculate the ROC indicator 21 | df['ROC'] = df['Adj Close'].pct_change(periods=n) 22 | 23 | # Generate buy signals when the ROC becomes above its signal line (0) 24 | df['Buy'] = (df['ROC'] > 0) & (df['ROC'].shift(1) < 0) 25 | 26 | # Generate sell signals when the ROC becomes below its signal line (0) 27 | df['Sell'] = (df['ROC'] < 0) & (df['ROC'].shift(1) > 0) 28 | 29 | # Buy securities when a buy signal is generated and sell them when a sell signal is generated 30 | # 1 for Buy, -1 for Sell, 0 for Hold 31 | df['Signal'] = np.where(df['Buy']==True, 1, np.where(df['Sell']==True,-1,0)) 32 | 33 | #print(df.tail(20)) 34 | 35 | # Calculate the daily returns of the strategy 36 | df['Returns'] = df['Signal'].shift(1) * df['Adj Close'].pct_change() 37 | df['Returns+1'] = 1 + df['Returns'] 38 | 39 | # Calculate the cumulative returns of the strategy 40 | df['Cumulative_Returns'] = (1+df['Returns']).cumprod() 41 | 42 | # Print the final cumulative return 43 | print('Final Cumulative Return Over The Whole Period: ', df['Cumulative_Returns'][-1]-1) 44 | 45 | df[['Returns+1','Cumulative_Returns']].plot(figsize=(8,4)) 46 | plt.title("Price Rate of Change (ROC)") 47 | plt.show() 48 | 49 | df[['Signal']].plot(figsize=(8,4)) 50 | plt.show() 51 | -------------------------------------------------------------------------------- /Sprites.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/Sprites.zip -------------------------------------------------------------------------------- /Year_Calendar.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | from tkinter import * 3 | 4 | def showCalender(): 5 | gui = Tk() 6 | gui.config(background='grey') 7 | gui.title("Calender for the year") 8 | gui.geometry("550x600") 9 | year = int(year_field.get()) 10 | gui_content = calendar.calendar(year) 11 | calYear = Label(gui,text=gui_content,font="Consolas 10 bold") 12 | calYear.grid(row=5,column=1,padx=20) 13 | gui.mainloop() 14 | 15 | if __name__=='__main__': 16 | new = Tk() 17 | new.config(background='grey') 18 | new.title("Calender") 19 | new.geometry("250x140") 20 | cal = Label(new, text="Calender",bg='grey',font=("times", 28, "bold")) 21 | #Label for enter year 22 | year = Label(new, text="Enter year", bg='dark grey') 23 | #text box for year input 24 | year_field=Entry(new) 25 | button = Button(new, text='Show Calender',fg='Black',bg='Blue',command=showCalender) 26 | #adjusting widgets in position 27 | cal.grid(row=1, column=1) 28 | year.grid(row=2, column=1) 29 | year_field.grid(row=3, column=1) 30 | button.grid(row=4, column=1) 31 | #Exit.grid(row=6, column=1) 32 | new.mainloop() 33 | -------------------------------------------------------------------------------- /_poli.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import math 3 | from itertools import cycle, islice 4 | 5 | ee = 0.05 6 | _OuterDia = 300 7 | _width = 800 8 | _height = 600 9 | _vertices = 6 10 | 11 | def get_coords(od,cx,cy,vertices=3,offset=0): 12 | angle = 2*math.pi/vertices 13 | return [[math.cos((angle*i)+(offset*math.pi/180))*od/2+cx, 14 | math.sin((angle*i)+(offset*math.pi/180))*od/2+cy]for i in 15 | range(0,vertices)] 16 | 17 | def spiral_viral(points,color,_range): 18 | points.append(points[0]) 19 | for i in range(0,_range): 20 | r = [draw(j,points,color[j%_vertices])for j in range(0,len(points)-1)] 21 | points = [[ee*points[i][0]+(1-ee)*points[i+1][0],ee*points[i][1]+ 22 | (1-ee)*points[i+1][1]]for i in range(0,len(points)-1)] 23 | points.append(points[0]) 24 | color.append(color.pop(0)) 25 | 26 | draw = lambda i,p,c : canvas.create_line(p[i][0],p[i][1],p[i+1] 27 | [0],p[i+1][1],fill=c) 28 | 29 | root = Tk() 30 | root.title("POLI") 31 | canvas = Canvas(width=_width,height=_height,bg='black') 32 | 33 | color = ['yellow','white','red','pink','green','light blue'] 34 | pt = get_coords(_OuterDia,_width/2,_height/2,_vertices,0) 35 | spiral_viral(pt,color,50) 36 | 37 | canvas.pack() 38 | mainloop() 39 | -------------------------------------------------------------------------------- /ajuste_retornos.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | from scipy.stats import norm 6 | from fitter import Fitter, get_common_distributions, get_distributions 7 | 8 | ticker = ['^IBEX'] 9 | returns = yf.download(ticker, '2015-01-01', progress=False)['Close'].pct_change()[1:].rename(ticker[0]) 10 | print(returns) 11 | 12 | returns.plot(kind="hist",bins=150,title=f"Variación de los retornos de {str(ticker[0])}", 13 | xlabel="Retornos",ylabel="Frecuencia") 14 | plt.axvline(returns.mean(),linestyle="--",linewidth=2,color="y") 15 | plt.axvline(returns.std(),linestyle="--",linewidth=2,color="r") 16 | plt.axvline(-1*returns.std(),linestyle="--",linewidth=2,color="r") 17 | plt.axvline(-2*returns.std(),linestyle="--",linewidth=2,color="r") 18 | plt.axvline(2*returns.std(),linestyle="--",linewidth=2,color="r") 19 | plt.show() 20 | 21 | # Distribucion normal 22 | returns.plot(kind='hist',bins=200,density=True,alpha=0.6,color='b') 23 | 24 | xmin, xmax = plt.xlim() 25 | x = np.linspace(xmin, xmax, 100) 26 | p = norm.pdf(x, returns.mean(), returns.std()) 27 | plt.plot(x, p, linewidth=2, color='r', linestyle='--') 28 | plt.show() 29 | 30 | # Distribuciones posibles 31 | print(get_common_distributions()) 32 | print(get_distributions()) 33 | 34 | f = Fitter(returns,distributions=['cauchy','norm','levy','laplace','johnsonsu',]) 35 | f.fit() 36 | f.summary() 37 | plt.show() 38 | -------------------------------------------------------------------------------- /anger_square.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/anger_square.png -------------------------------------------------------------------------------- /async_audioPlay.py: -------------------------------------------------------------------------------- 1 | import sounddevice as sd 2 | import soundfile as sf 3 | import time 4 | 5 | #FUNCIÓN DE REPRODUCCIÓN. 6 | def async_playback(filename): 7 | data, fs = sf.read(filename) 8 | sd.play(data,fs) 9 | return data, fs 10 | 11 | #INICIO DE EJECUCIÓN. 12 | file = 'audioFile.wav' 13 | data, fs = async_playback(file) 14 | 15 | #ESTE BLOQUE SE EJECUTA MIENTRAS SUENA EL AUDIO. 16 | print('Este texto se está mostrando mientras se reproduce el audio') 17 | time.sleep(5) 18 | print('hi, this is cool!') 19 | time.sleep(5) 20 | print('REPRODUCIENDO: ',file) 21 | time.sleep(5) 22 | response = input("Escribe STOP para finalizar reproducción: ") 23 | 24 | if response == "STOP": 25 | sd.stop() 26 | print("STOPPED BY THE USER.") 27 | else: 28 | print("Escribiste otra cosa, lo pararé de todos modos en 3,2,1..") 29 | time.sleep(3) 30 | sd.stop() 31 | print('STOPPED BY THE PROGRAM.') 32 | -------------------------------------------------------------------------------- /async_record.py: -------------------------------------------------------------------------------- 1 | import sounddevice as sd 2 | import soundfile as sf 3 | import time 4 | 5 | #EJECUCION SIMULTANEA 6 | def printstuff(number): 7 | for i in range(number): 8 | time.sleep(1) 9 | print(i) 10 | print("ESPERA MIENTRAS TERMINO DE GRABAR...") 11 | 12 | #FUNCIÓN DE GRABACIÓN 13 | def async_record(filename,duration,fs,channels): 14 | print('recording') 15 | myrecording = sd.rec(int(duration * fs),samplerate=fs,channels=channels) 16 | print("IMPRIMIENDO HASTA 15 MIENTRAS GRABO.") 17 | #EJECUTAR FUNCIÓN DE CUENTA 18 | printstuff(16) 19 | #ESPERAR A QUE TERMINE DE GRABAR 20 | sd.wait() 21 | #CREAR ARCHIVO CON "soundfile". 22 | sf.write(filename,myrecording,fs) 23 | print("GRABACIÓN TERMINADA") 24 | 25 | 26 | #EJECUTAR PROGRAMA. 27 | async_record('async_record.wav',20,16000,1) 28 | -------------------------------------------------------------------------------- /audio_book.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | import PyPDF2 3 | from tkinter.filedialog import * 4 | 5 | book = askopenfilename() 6 | pdfreader = PyPDF2.PdfFileReader(book) 7 | pages = pdfreader.numPages 8 | 9 | for num in range(0,pages): 10 | page = pdfreader.getPage(num) 11 | print(num) 12 | text = page.extractText() 13 | print(text) 14 | player = pyttsx3.init() 15 | player.setProperty('rate',172) 16 | player.say(text) 17 | player.runAndWait() 18 | -------------------------------------------------------------------------------- /automate_boringStuff.py: -------------------------------------------------------------------------------- 1 | import pyautogui 2 | import time 3 | from VALID import OKI, ns 4 | 5 | #DELETING FILES FROM "Python" FOLDER. 6 | while True: 7 | num =(OKI(input("Número de archivos: ")))+1 8 | for i in range(0,num): 9 | pyautogui.moveTo(241,132) 10 | time.sleep(0.3) 11 | pyautogui.click() 12 | time.sleep(0.5) 13 | pyautogui.click(button='right') 14 | time.sleep(0.6) 15 | pyautogui.moveTo(274,699) 16 | time.sleep(0.3) 17 | pyautogui.click() 18 | conti = ns(input("¿Continuar?: ")) 19 | if conti == "n": 20 | break 21 | 22 | -------------------------------------------------------------------------------- /bezier.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | 5 | x = np.random.random_sample((3,)) 6 | y = np.random.random_sample((3,)) 7 | z = np.random.random_sample((3,)) 8 | 9 | CELLS = 10 10 | nCPTS = np.size(x, 0) 11 | n = nCPTS - 1 # numero total de segmentos 12 | i = 0 13 | t = np.linspace(0, 1, CELLS) # VARIABLE PARAMETRICA 14 | B = [] 15 | 16 | xBezier = np.zeros((1, CELLS)) 17 | yBezier = np.zeros((1, CELLS)) 18 | zBezier = np.zeros((1, CELLS)) 19 | 20 | def Ni(n, i): 21 | return np.math.factorial(n) / (np.math.factorial(i) * np.math.factorial(n - i)) 22 | 23 | def basisFunction(n, i, t): 24 | J = np.array(Ni(n, i) * (t ** i) * (1 - t) ** (n - i)) 25 | return J 26 | 27 | for k in range(0, nCPTS): 28 | B.append(basisFunction(n, i, t)) 29 | 30 | xBezier = basisFunction(n, i, t) * x[k] + xBezier 31 | yBezier = basisFunction(n, i, t) * y[k] + yBezier 32 | zBezier = basisFunction(n, i, t) * z[k] + zBezier 33 | 34 | i += 1 35 | 36 | '''for line in B: 37 | plt.plot(t, line)''' 38 | 39 | fig1 = plt.figure(figsize=(4, 4)) 40 | ax1 = fig1.add_subplot(111,projection='3d') 41 | ax1.scatter(x, y, z, c='black') 42 | ax1.plot(xBezier[0], yBezier[0], zBezier[0], c='blue') 43 | 44 | plt.show() 45 | -------------------------------------------------------------------------------- /bezier_latest.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from scipy.special import comb # Para calcular coeficientes binomiales de forma eficiente 4 | 5 | # Definición de puntos de control 6 | x = np.random.random_sample((3,)) 7 | y = np.random.random_sample((3,)) 8 | z = np.random.random_sample((3,)) 9 | 10 | CELLS = 10 11 | nCPTS = len(x) # Número de puntos de control 12 | n = nCPTS - 1 # Número total de segmentos 13 | t = np.linspace(0, 1, CELLS) # Variable paramétrica 14 | B = [] 15 | 16 | # Inicialización de las curvas de Bezier 17 | xBezier = np.zeros(CELLS) 18 | yBezier = np.zeros(CELLS) 19 | zBezier = np.zeros(CELLS) 20 | 21 | # Función que calcula el coeficiente binomial 22 | def Ni(n, i): 23 | return comb(n, i) 24 | 25 | # Función base de Bezier 26 | def basisFunction(n, i, t): 27 | return Ni(n, i) * (t ** i) * (1 - t) ** (n - i) 28 | 29 | # Cálculo de las curvas de Bezier 30 | for k in range(nCPTS): 31 | B_k = basisFunction(n, k, t) 32 | B.append(B_k) 33 | 34 | xBezier += B_k * x[k] 35 | yBezier += B_k * y[k] 36 | zBezier += B_k * z[k] 37 | 38 | # Gráfica en 3D 39 | fig1 = plt.figure(figsize=(4, 4)) 40 | ax1 = fig1.add_subplot(111, projection='3d') 41 | ax1.scatter(x, y, z, c='black', label="Puntos de control") 42 | ax1.plot(xBezier, yBezier, zBezier, c='blue', label="Curva de Bezier") 43 | 44 | ax1.set_xlabel('X') 45 | ax1.set_ylabel('Y') 46 | ax1.set_zlabel('Z') 47 | 48 | plt.legend() 49 | plt.show() 50 | -------------------------------------------------------------------------------- /bezier_surface.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from mpl_toolkits.mplot3d import Axes3D 4 | import math 5 | 6 | def bernstein(n, i, t): 7 | coeff = math.factorial(n) / (math.factorial(i) * math.factorial(n - i)) 8 | return coeff * (t ** i) * ((1 - t) ** (n - i)) 9 | 10 | def bezier_surface(control_points, u_steps=20, v_steps=20): 11 | n = len(control_points) - 1 12 | m = len(control_points[0]) - 1 13 | u = np.linspace(0, 1, u_steps) 14 | v = np.linspace(0, 1, v_steps) 15 | surface = np.zeros((u_steps, v_steps, 3)) 16 | 17 | for i in range(n + 1): 18 | for j in range(m + 1): 19 | bern_u = bernstein(n, i, u) 20 | bern_v = bernstein(m, j, v) 21 | for k in range(u_steps): 22 | for l in range(v_steps): 23 | surface[k, l] += bern_u[k] * bern_v[l] * control_points[i][j] 24 | 25 | return surface 26 | 27 | control_points = np.array([ 28 | [[0, 0, 0], [1, 0, 2], [2, 0, 0]], 29 | [[0, 1, 3], [1, 1, 4], [2, 1, 3]], 30 | [[0, 2, 0], [1, 2, 2], [2, 2, 0]] 31 | ]) 32 | 33 | surface = bezier_surface(control_points, u_steps=30, v_steps=30) 34 | 35 | # Separar las coordenadas de la superficie 36 | x = surface[:, :, 0] 37 | y = surface[:, :, 1] 38 | z = surface[:, :, 2] 39 | 40 | # Crear la figura y el gráfico 3D 41 | fig = plt.figure(figsize=(8, 6)) 42 | ax = fig.add_subplot(111, projection='3d') 43 | 44 | # Dibujar la superficie 45 | ax.plot_surface(x, y, z, color='skyblue', rstride=1, cstride=1, alpha=0.7, edgecolor='k') 46 | 47 | # Dibujar los puntos de control 48 | for row in control_points: 49 | ax.plot([p[0] for p in row], [p[1] for p in row], [p[2] for p in row], 'ro-') 50 | 51 | # Configurar etiquetas y título 52 | ax.set_title("Superficie de Bézier") 53 | ax.set_xlabel('X') 54 | ax.set_ylabel('Y') 55 | ax.set_zlabel('Z') 56 | 57 | # Mostrar el gráfico 58 | plt.show() 59 | -------------------------------------------------------------------------------- /blurring_faces_images.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | # load the input image and convert it to grayscale 4 | image = cv2.imread("jp13.png") 5 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 6 | 7 | # load the face detector 8 | face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") 9 | 10 | # detect the faces in the grayscale image 11 | '''face_rects = face_detector.detectMultiScale(gray, 1.04, 5, minSize=(30, 30)) 12 | 13 | # go through the face bounding boxes 14 | for (x, y, w, h) in face_rects: 15 | 16 | # draw a rectangle around the face on the input image 17 | cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) 18 | 19 | cv2.imshow("Image", image) 20 | cv2.waitKey(0)''' 21 | 22 | face_rects = face_detector.detectMultiScale(gray, 1.04, 5, minSize=(30, 30)) 23 | 24 | # go through the face bounding boxes 25 | for (x, y, w, h) in face_rects: 26 | # get the region of the face 27 | face_roi = image[y:y + h, x:x + w] 28 | 29 | # apply blurring to the part of the face 30 | blurred = cv2.medianBlur(face_roi, 99) 31 | # replace the part of the face with the blurred image 32 | image[y:y+h, x:x+w] = blurred 33 | 34 | cv2.imshow("Image", image) 35 | cv2.waitKey(0) 36 | -------------------------------------------------------------------------------- /bollinger_bands.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import matplotlib.pyplot as plt 3 | import pandas as pd 4 | 5 | def get_rolling_mean(values, window): 6 | return pd.Series(pd.Series.rolling(values,window).mean())#,name='Rolling Mean') 7 | 8 | def get_rolling_std(values,window): 9 | return pd.Series(pd.Series.rolling(values,window).std())#,name='Std Dev') 10 | 11 | def get_bollinger_bands(rm,rstd): 12 | upper_band = rm + rstd * 2 13 | lower_band = rm - rstd * 2 14 | return upper_band, lower_band 15 | 16 | def test_run(): 17 | spy = yf.Ticker("BTC-USD") 18 | df = spy.history(start='2021-01-01',end='2022-1-6')["Close"] 19 | 20 | rm_SPY = get_rolling_mean(df,window=20) 21 | rstd_SPY = get_rolling_std(df,window=20) 22 | 23 | upper_band, lower_band = get_bollinger_bands(rm_SPY,rstd_SPY) 24 | 25 | ax = df.plot() 26 | ax.set_ylabel("PRICE") 27 | rm_SPY.plot(label='Rolling mean',ax=ax).legend() 28 | upper_band.plot(label='Upper band',ax=ax).legend() 29 | lower_band.plot(label='Lower band',ax=ax).legend() 30 | plt.grid() 31 | 32 | plt.show() 33 | 34 | test_run() 35 | -------------------------------------------------------------------------------- /bollinger_bands_ex2.py: -------------------------------------------------------------------------------- 1 | import ta 2 | #import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import yfinance as yf 5 | import warnings 6 | warnings.filterwarnings("ignore") 7 | 8 | df = yf.Ticker("BTC-USD").history(period="max").reset_index()[["Date","Close"]] 9 | print(df.head()) 10 | 11 | bol = ta.volatility.BollingerBands(df["Close"], window=20)#14 12 | 13 | df['M-AVG'] = bol.bollinger_mavg()#banda media movil 14 | df['Low Band'] = bol.bollinger_lband()#banda inferior 15 | #df['hband'] = bol.bollinger_hband()#banda superior 16 | df['High Band'] = bol.bollinger_hband()#banda superior 17 | 18 | plt.grid() 19 | plt.title("BTC-USD") 20 | plt.plot(df["Date"],df["Close"]) 21 | plt.plot(df["Date"],df["M-AVG"], color="red") 22 | plt.plot(df["Date"],df["Low Band"], color="orange") 23 | plt.plot(df["Date"],df["High Band"], color="orange") 24 | plt.fill_between(df["Date"],df["Low Band"],df["High Band"], alpha=0.2, color="orange") 25 | plt.xlabel("Date") 26 | plt.ylabel("Price") 27 | plt.legend(loc="best") 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /borel_cantelli.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import scipy 4 | from scipy.stats import skew, kurtosis, chi2 5 | 6 | ''' 7 | Goal: Generate 'Borel-Cantellí' simulation. 8 | ''' 9 | 10 | # SIMULATE RANDOM VARIABLES 11 | times = input("Enter max times: ") 12 | is_normal = True 13 | counter = 0 14 | 15 | ### Borel-Cantellí: P[all test are normal = True] = 0 16 | while is_normal == True and counter < int(times): 17 | x_size = 10**6 18 | degrees_freedom = 1 19 | # GENERATE DISTRIBUTION 20 | x = np.random.standard_normal(x_size) 21 | 22 | print(" ") 23 | # COMPUTE RISK METRICS 24 | x_mean = np.mean(x) 25 | s_stdev = np.std(x) 26 | x_skew = skew(x) 27 | x_kurt = kurtosis(x) 28 | x_median = np.percentile(x,95) 29 | x_VaR95 = np.percentile(x,5) 30 | x_cvar95 = np.mean(x[x <= x_VaR95]) 31 | x_jb = x_size/6*(x_skew**2 + 1/4*x_kurt**2) 32 | p_value = 1 - chi2.cdf(x_jb,df=degrees_freedom) 33 | is_normal = (p_value > 0.05) 34 | 35 | print("MEAN: ",x_mean) 36 | print("STD_DEV: ",s_stdev) 37 | print("SKEWNESS: ",x_skew) 38 | print("KURTOSIS: ",x_kurt) 39 | print("MEDIAN: ",x_median) 40 | print("VaR95: ",x_VaR95) 41 | print("CVaR95: ",x_cvar95) 42 | print("JARQUE-BERA: ",x_jb) 43 | print("P-VALUE: ",p_value) 44 | print("IS NORMAL: ",str(is_normal)) 45 | 46 | counter+=1 47 | print('COUNTER ' + str(counter)) 48 | print('------') 49 | -------------------------------------------------------------------------------- /calcula_factorial.py: -------------------------------------------------------------------------------- 1 | from VALID import ns, OKI 2 | import subprocess 3 | 4 | def factorial(n): 5 | if n == 0 or n == 1: 6 | resultado = 1 7 | elif n > 1: 8 | resultado = n * (factorial(n-1)) 9 | return resultado 10 | 11 | while True: 12 | num=OKI(input("Introduce número: ")) 13 | factorial_de_n=factorial(num) 14 | print(factorial_de_n) 15 | 16 | conti=ns(input("¿Desea continuar?: ")) 17 | if conti=="n": 18 | break 19 | subprocess.call(["cmd.exe","/C","cls"]) 20 | -------------------------------------------------------------------------------- /calculo_interes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from VALID import ns #OK 3 | import subprocess 4 | 5 | def entradaNumero(texto, tipo): 6 | numero = -1 7 | while numero < 0: 8 | try: 9 | if tipo=="float": 10 | numero = float(input(texto)) 11 | else: 12 | numero = int(input(texto)) 13 | except: 14 | print("\tError, no es un valor correcto") 15 | return numero 16 | 17 | while True: 18 | cantidad=entradaNumero("Indica la cantidad: ", "float") 19 | interes=entradaNumero("Indica el interes: ", "float") 20 | anos=entradaNumero("Indica los años: ", "int") 21 | 22 | print("\n--------------------------------------------------") 23 | for i in range(anos): 24 | print("año {0} capital {1:.2f} interes {2:.2f} total {3:.2f}".format(i+1, cantidad, cantidad*interes/100, cantidad + cantidad*interes/100)) 25 | cantidad+=cantidad*(interes/100) 26 | conti = ns(input("\n¿Desea continuar?(n/s): ")) 27 | if conti == "n": 28 | break 29 | subprocess.call(["cmd.exe","/C","cls"]) 30 | -------------------------------------------------------------------------------- /calculo_interesB.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from VALID import ns, OK, OKI 3 | import subprocess 4 | 5 | while True: 6 | print("\n---------------CALCULO DE INTERESES---------------") 7 | cantidad=OK(input("Indica la cantidad: ")) 8 | interes=OK(input("Indica el interes: ")) 9 | anos=OKI(input("Indica los años: ")) 10 | 11 | print("\n--------------------------------------------------") 12 | for i in range(anos): 13 | print("año {0} capital {1:.2f} interes {2:.2f} total {3:.2f}".format(i+1, cantidad, cantidad*interes/100, cantidad + cantidad*interes/100)) 14 | cantidad+=cantidad*(interes/100) 15 | conti = ns(input("\n¿Desea continuar?(n/s): ")) 16 | if conti == "n": 17 | break 18 | subprocess.call(["cmd.exe","/C","cls"]) 19 | -------------------------------------------------------------------------------- /calculo_retornos.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import matplotlib.pyplot as plt 3 | from datetime import datetime 4 | from pandas_datareader import data as wb 5 | 6 | # Define los símbolos de las acciones de las compañías 7 | symbol1 = 'NVDA' # NVDA. 8 | 9 | # Define el rango de fechas para los datos históricos 10 | start_date = '2020-01-01' 11 | end_date = datetime.today().strftime('%Y-%m-%d') # Fecha actual 12 | 13 | # Descarga los datos históricos de las acciones usando yfinance 14 | data1 = yf.download(symbol1, start=start_date, end=end_date) 15 | 16 | # Calculo retornos 17 | returns = data1['Adj Close'].pct_change() 18 | 19 | print(returns.tail()) 20 | 21 | # Graficar la evolución del precio de las acciones 22 | plt.figure(figsize=(14, 7)) 23 | plt.plot(data1.index, returns, label=symbol1, linewidth=1.0) 24 | 25 | # Añadir títulos y etiquetas 26 | plt.title(f'Evolución de los retornos de {symbol1} ({start_date} - {end_date})') 27 | plt.grid() 28 | plt.xlabel('Fecha') 29 | plt.ylabel('Retornos') 30 | plt.legend() 31 | 32 | # Mostrar la gráfica 33 | plt.show() 34 | -------------------------------------------------------------------------------- /car_detector.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import cv2 4 | print(cv2.__version__) 5 | 6 | cascade_src = 'cars.xml' 7 | #video_src = 'traffic.mp4' 8 | video_src = 'dataset/video1.avi' 9 | #video_src = 'dataset/video2.avi' 10 | 11 | cap = cv2.VideoCapture(video_src) 12 | car_cascade = cv2.CascadeClassifier(cascade_src) 13 | 14 | while True: 15 | ret, img = cap.read() 16 | if (type(img) == type(None)): 17 | break 18 | 19 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 20 | 21 | cars = car_cascade.detectMultiScale(gray, 1.1, 1) 22 | 23 | for (x,y,w,h) in cars: 24 | cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) 25 | cv2.putText(img,'a car',(x, y),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),1) 26 | 27 | cv2.imshow('video', img) 28 | 29 | if cv2.waitKey(33) == 27: 30 | print("END") 31 | break 32 | 33 | cv2.destroyAllWindows() 34 | -------------------------------------------------------------------------------- /celsius_2_farenheit.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | root = Tk() 4 | 5 | c_entry = Entry(root, width=4) 6 | c_entry.pack(side='left') 7 | Cunit_label = Label(root, text='Celsius') 8 | Cunit_label.pack(side='left') 9 | 10 | def compute(): 11 | C = float(c_entry.get()) 12 | F = (9./5)*C + 32 13 | F_label.configure(text='%g' % F) 14 | 15 | compute = Button(root, text=' is ',command=compute) 16 | compute.pack(side='left', padx=4) 17 | 18 | F_label = Label(root, width=4) 19 | F_label.pack(side="left") 20 | Funit_label = Label(root, text="Fahrenheit") 21 | Funit_label.pack(side="left") 22 | 23 | root.mainloop() 24 | -------------------------------------------------------------------------------- /cesar_hack.py: -------------------------------------------------------------------------------- 1 | #USO DE "fuerza bruta" PARA DESCIFRAR CIFRADO CESAR. 2 | texto=input("Mensaje: ") 3 | 4 | caracts='ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuwxyz0123456789' 5 | 6 | for key in range(len(caracts)): 7 | traducido='' 8 | 9 | for elem in texto: 10 | if elem in caracts: 11 | elemIndex=caracts.find(elem) 12 | tradIndex=elemIndex-key 13 | 14 | if tradIndex<0: 15 | tradIndex=tradIndex+len(caracts) 16 | traducido=traducido+caracts[tradIndex] 17 | else: 18 | traducido=traducido+elem 19 | 20 | if len(traducido)==len(texto): 21 | print('key #%s: %s' % (key, traducido)) 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /chat.py: -------------------------------------------------------------------------------- 1 | #IMPORTAR LIBRERIA 2 | import openai 3 | import time 4 | import os 5 | import sys 6 | from colorama import Fore, init 7 | 8 | init() 9 | 10 | # INTRODUCIR CLAVE 11 | key = "" 12 | openai.api_key = key 13 | 14 | def typewriter(message): 15 | print(Fore.GREEN) 16 | for i in message: 17 | sys.stdout.write(i) 18 | sys.stdout.flush() 19 | time.sleep(0.01) 20 | print(Fore.RESET) 21 | 22 | # BUCLE 23 | while True: 24 | 25 | # INTRODUCIR PREGUNTA A ENVIAR 26 | prompt = input("\nPROMPT> ") 27 | 28 | # CONDICIÓN PARA FINALIZAR BUCLE 29 | if prompt == "END": 30 | break 31 | 32 | # OBTENER RESPUESTA 33 | completion = openai.Completion.create(engine="text-davinci-003", 34 | prompt=prompt, 35 | max_tokens=2048) 36 | 37 | # MOSTAR RESPUESTA EN PANTALLA 38 | response = str(completion.choices[0].text) 39 | 40 | typewriter(response) 41 | print("") 42 | -------------------------------------------------------------------------------- /check_vid_audio.py: -------------------------------------------------------------------------------- 1 | from moviepy.editor import VideoFileClip 2 | 3 | def video_contains_audio(file_path): 4 | try: 5 | video_clip = VideoFileClip(file_path) 6 | audio = video_clip.audio 7 | return audio 8 | except Exception as e: 9 | print(f"Error: {str(e)}") 10 | return None 11 | 12 | # Ruta al archivo de video que deseas verificar 13 | video_path = file-path 14 | 15 | audio_info = video_contains_audio(video_path) 16 | 17 | if audio_info: 18 | print("El video contiene audio.") 19 | print("Información del audio:") 20 | print(f"Duración: {audio_info.duration} segundos") 21 | print(f"Frecuencia de muestreo: {audio_info.fps} Hz") 22 | print(f"Número de canales: {audio_info.nchannels}") 23 | else: 24 | print("El video no contiene audio.") 25 | -------------------------------------------------------------------------------- /cifrado_cesar.py: -------------------------------------------------------------------------------- 1 | #CIFRADO CESAR 2 | 3 | texto=input("Tu texto: ") 4 | 5 | abc="ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuwxyz0123456789" 6 | 7 | k=int(input("Valor de desplazamiento: ")) 8 | cifrad="" 9 | 10 | for c in texto: 11 | if c in abc: 12 | cifrad += abc[(abc.index(c)+k)%(len(abc))] 13 | else: 14 | cifrad+=c 15 | 16 | print("Texto cifrado: ",cifrad) 17 | -------------------------------------------------------------------------------- /cifrado_vigenere.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | LETRAS = ("ABCDEFGHIJKLMNÑOPQRSTUVWXYZ") 4 | 5 | def main(): 6 | mensaje=input("Mensaje: ") 7 | myKey="MINOMBREESANTONIOALFONSO" 8 | accion=input("Mode: ") 9 | 10 | if accion=='encriptar': 11 | traducido=cifrar_mensaje(myKey,mensaje) 12 | elif accion=='descifrar': 13 | traducido=descifrar_mensaje(myKey,mensaje) 14 | print(traducido) 15 | 16 | def cifrar_mensaje(clave,mensa): 17 | return traductor_mensaje(clave,mensa,'encriptar') 18 | 19 | def descifrar_mensaje(clave,mensa): 20 | return traductor_mensaje(clave,mensa,'descifrar') 21 | 22 | def traductor_mensaje(clave,mensa,accion): 23 | traducido=[] 24 | indice_clave=0 25 | clave=clave.upper() 26 | 27 | for symbol in mensa: 28 | num=LETRAS.find(symbol.upper()) 29 | if num!=-1: 30 | if accion=='encriptar': 31 | num+=LETRAS.find(clave[indice_clave]) 32 | elif accion=='descifrar': 33 | num-=LETRAS.find(clave[indice_clave]) 34 | num%=len(LETRAS) 35 | if symbol.isupper(): 36 | traducido.append(LETRAS[num]) 37 | elif symbol.islower(): 38 | traducido.append(LETRAS[num].lower()) 39 | indice_clave+=1 40 | if indice_clave==len(clave): 41 | indice_clave=0 42 | 43 | else: 44 | traducido.append(symbol) 45 | return ('').join(traducido) 46 | 47 | if __name__ == '__main__': 48 | main() 49 | -------------------------------------------------------------------------------- /clahe.py: -------------------------------------------------------------------------------- 1 | # IMPORTAR LIBRERIAS Y RECURSOS 2 | import cv2 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | 6 | # FUNCIÓN PARA HISTOGRAMA 7 | def show_hist(title,img): 8 | media_valores = np.mean(img) # MEDIA DE LAS INTENSIDADES 9 | hist = cv2.calcHist([img],[0],None,[256],[0,256]) 10 | plt.figure() 11 | plt.title(title) 12 | plt.xlabel('Intensidades') 13 | plt.ylabel('Pixels') 14 | plt.plot(hist) 15 | plt.axvline(x=media_valores, color="r", label="media") 16 | plt.legend() 17 | plt.xlim([0,256]) 18 | plt.show() 19 | 20 | # CARGAR IMAGEN Y CONVERTIRLA A ESCALA DE GRISES 21 | image = cv2.imread("image.jpg") 22 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 23 | 24 | # MOSTRAR IMAGEN 25 | cv2.imshow("Original",gray) 26 | cv2.waitKey(0) 27 | 28 | # MOSTRAR HISTOGRAMA 29 | show_hist('Original',gray) 30 | 31 | # ECUALIZAR HISTOGRAMA 32 | equalized = cv2.equalizeHist(gray) 33 | 34 | # MOSTRAR IMAGEN RESULTADO 35 | cv2.imshow("Equalized",equalized) 36 | cv2.waitKey(0) 37 | 38 | # HISTOGRAMA 39 | show_hist('Equalized',equalized) 40 | 41 | # ALGORITMO CLAHE 42 | clip = 2.0 # UMBRAL LIMITE 43 | 44 | tile = 8 # TAMAÑO CELDA 45 | 46 | clahe = cv2.createCLAHE(clipLimit=clip,tileGridSize=(tile, tile)) 47 | equalized_new = clahe.apply(gray) 48 | 49 | # MOSTRAR IMAGEN 50 | cv2.imshow("Equaelized (CLAHE)",equalized_new) 51 | cv2.waitKey(0) 52 | 53 | # MOSTRAR HISTOGRAMA 54 | show_hist('Equalized (CLAHE)',equalized_new) 55 | 56 | cv2.destroyAllWindows() 57 | -------------------------------------------------------------------------------- /clasifc_sectores_sp500.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import pandas as pd 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import warnings 6 | #import pandas_ta as ta 7 | 8 | # Ignorar todos los warnings 9 | warnings.filterwarnings("ignore") 10 | 11 | data = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0][['Symbol','GICS Sector', 12 | 'GICS Sub-Industry']].set_index(['Symbol']) 13 | 14 | sectores = list(set(data['GICS Sector'])) 15 | #print(sectores) 16 | sub_sectores = list(set(data['GICS Sub-Industry'])) 17 | #print(sub_sectores) 18 | 19 | df = yf.download(list(data.index),start='2023-01-01',progress=False)['Close'] 20 | #print(df) 21 | 22 | df = df.reindex(columns=data.index) 23 | mean = df.rolling(150).mean() 24 | 25 | df1 = pd.DataFrame(np.where(df.iloc[-1]>mean.iloc[-1],1,0), index=df.columns) 26 | data['>mean(150)'] = df1[0] 27 | print(data) 28 | 29 | #clasificar 30 | suma = pd.DataFrame() 31 | for i in range(len(sectores)): 32 | x = pd.DataFrame(data['>mean(150)'][data['GICS Sector'] == str(sectores[i])]).sum() 33 | suma = pd.concat([suma,x],axis=1) 34 | 35 | suma.columns = sectores 36 | suma = suma.T 37 | print(suma) 38 | 39 | suma.plot(kind='bar',figsize=(15,10),title="Empresas del SP500 por encima de la media de los 150p", 40 | ylim=(0,len(data.index)), ylabel="Nª de empresas", 41 | xlabel="Sectores",legend=False,rot=30) 42 | 43 | plt.show() 44 | -------------------------------------------------------------------------------- /client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | HOST = "localhost"#"127.0.0.1" #IP DEL SERVIDOR 4 | PORT = 65123 #PUERTO DE ENVIO 5 | 6 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 7 | 8 | s.connect((HOST, PORT)) # SOLICITUD DE CONEXIÓN CON SERVIDOR 9 | 10 | s.sendall(b"Hola mundo") # ENVIAR DATOS AL SERVIDOR 11 | data = s.recv(1024) # ESPERA A RECEPCIÓN DE INFORMACIÓN DEL SERVIDOR 12 | 13 | print("Recibida", repr(data)) 14 | 15 | -------------------------------------------------------------------------------- /clipboard_copy.py: -------------------------------------------------------------------------------- 1 | import time 2 | import sys 3 | import pyperclip 4 | 5 | ultima_copia = pyperclip.paste().strip() 6 | 7 | while True: 8 | time.sleep(0.1) 9 | copia = pyperclip.paste().strip() 10 | if copia != ultima_copia: 11 | try: 12 | with open('clipboard.txt', 'a') as f: 13 | f.write('{}\n$\n'.format(copia)) 14 | ultima_copia = copia 15 | except Exception as e: 16 | sys.stderr.write("Error: {}".format(e)) 17 | break 18 | -------------------------------------------------------------------------------- /cmd_plot.py: -------------------------------------------------------------------------------- 1 | import plotext 2 | import numpy as np 3 | 4 | '''X = np.random.random(100) 5 | y = np.random.random(100) 6 | 7 | plotext.scatter(X,y) 8 | plotext.title("Random Data Points") 9 | plotext.show() 10 | 11 | plotext.clear_plot() 12 | 13 | y = plotext.sin() 14 | plotext.plot(y) 15 | plotext.title("SIN") 16 | plotext.show() 17 | 18 | --------------------------------------- 19 | 20 | X = np.arange(0, 10, 0.1) 21 | y = np.sin(X) 22 | y2 = np.cos(X) 23 | 24 | plotext.plot(X, y, label="Sin") 25 | plotext.plot(X, y2, label="Cos") 26 | plotext.title("Sin & Cos") 27 | plotext.show()''' 28 | 29 | ############## sin function animation on cmd ################ 30 | l = 1000 31 | x = range(1, l+1) 32 | frames = 50 33 | 34 | plotext.title("Sine Animation") 35 | plotext.clc() 36 | 37 | for i in range(frames): 38 | plotext.clt() 39 | plotext.cld() 40 | 41 | y = plotext.sin(1, 4, l, 2 * i / frames) 42 | plotext.xlim(0, 400) 43 | plotext.plot(x, y, marker="dot", color="red") 44 | plotext.sleep(0.001) 45 | plotext.show() 46 | 47 | plotext.clear_plot() 48 | -------------------------------------------------------------------------------- /cmd_sine.py: -------------------------------------------------------------------------------- 1 | import plotext 2 | import argparse 3 | import numpy as np 4 | from pynput import keyboard 5 | 6 | stop = False 7 | 8 | def main(): 9 | parser = argparse.ArgumentParser(prog="CMD-SIN",description="Sine function simulations on CMD") 10 | #parser.add_argument('-fms','--frames',type=int,default=100,help="Number of frames for the animation.") 11 | parser.add_argument('-amp','--amplitude',type=float,default=1,help="Amplitude for sine waves.") 12 | #parser.add_argument('-per','--periods',type=int,default=4,help="Number of periods.") 13 | parser.add_argument('-freq','--frequency',type=float,default=1,help="Sine frequency value") 14 | parser.add_argument('-tm','--time',type=int,default=40,help="Time elapsed in seconds") 15 | 16 | args = parser.parse_args() 17 | sine_anim(args) 18 | 19 | def on_press(key): 20 | global stop 21 | if key == keyboard.Key.space: 22 | stop = True 23 | return False 24 | 25 | def sine_anim(args): 26 | amplitude = args.amplitude 27 | frequency = args.frequency 28 | length = 1000 29 | #frames = args.frames 30 | 31 | listener = keyboard.Listener(on_press=on_press) 32 | listener.start() 33 | 34 | plotext.title("Sine Animation -PRESS SPACE BAR TO SCAPE-") 35 | plotext.clc() 36 | 37 | #for i in range(frames): 38 | i = 0 39 | while True: 40 | plotext.clt() 41 | plotext.cld() 42 | 43 | x = np.linspace(0, 10, length) 44 | phase = 2 * np.pi * i / args.time ### 45 | 46 | y = amplitude * np.sin(frequency * x + phase) 47 | 48 | plotext.plot(x, y, marker="braille", color="red") 49 | plotext.ylim(-amplitude,amplitude) 50 | plotext.xlim(0, 10) 51 | plotext.sleep(0.01) 52 | plotext.show() 53 | i += 1 54 | 55 | if stop == True: 56 | print("Animation interrupted by user") 57 | listener.stop() 58 | break 59 | 60 | if __name__=='__main__': 61 | main() 62 | 63 | 64 | -------------------------------------------------------------------------------- /cmd_sineplot.py: -------------------------------------------------------------------------------- 1 | import plotext 2 | import argparse 3 | 4 | def main(): 5 | 6 | parser = argparse.ArgumentParser(prog="CMD-SIN",description="Sine function simulations on CMD") 7 | parser.add_argument('-fms','--frames',type=int,default=100,help="Number of frames for the animation.") 8 | parser.add_argument('-amp','--amplitude',type=int,default=1,help="Amplitude for sine waves.") 9 | parser.add_argument('-per','--periods',type=int,default=4,help="Number of periods.") 10 | parser.add_argument('-pha','--phase',type=int,default=2,help="Phase.") 11 | 12 | args = parser.parse_args() 13 | sine_anim(args) 14 | 15 | def sine_anim(args): 16 | l = 1000 17 | x = range(1, l+1) 18 | frames = args.frames 19 | 20 | plotext.title("Sine Animation") 21 | plotext.clc() 22 | 23 | for i in range(frames): 24 | plotext.clt() 25 | plotext.cld() 26 | 27 | y = plotext.sin(args.amplitude, args.periods, l, args.phase * i / frames) 28 | plotext.xlim(0, 400) 29 | plotext.plot(x, y, marker="dot", color="red") 30 | plotext.sleep(0.001) 31 | plotext.show() 32 | 33 | plotext.clear_plot() 34 | 35 | if __name__=='__main__': 36 | main() 37 | -------------------------------------------------------------------------------- /cmd_sineplotB.py: -------------------------------------------------------------------------------- 1 | import plotext 2 | import argparse 3 | 4 | def main(): 5 | 6 | parser = argparse.ArgumentParser(prog="CMD-SIN",description="Sine function simulations on CMD") 7 | parser.add_argument('-fms','--frames',type=int,default=100,help="Number of frames for the animation.") 8 | parser.add_argument('-amp','--amplitude',type=int,default=1,help="Amplitude for sine waves.") 9 | parser.add_argument('-per','--periods',type=int,default=4,help="Number of periods.") 10 | parser.add_argument('-pha','--phase',type=int,default=2,help="Phase.") 11 | 12 | args = parser.parse_args() 13 | sine_anim(args) 14 | 15 | def sine_anim(args): 16 | l = 1000 17 | x = range(1, l+1) 18 | frames = args.frames 19 | 20 | #plotext.title(f"Sine Animation (amp:{args.amplitude} periods:{args.periods})") 21 | plotext.clc() 22 | c=0 23 | for i in range(frames): 24 | c+=1 25 | plotext.clt() 26 | plotext.cld() 27 | 28 | y = plotext.sin(args.amplitude, args.periods, l, args.phase * i / frames) 29 | plotext.title(f"Sine Animation (amp:{args.amplitude}, periods:{args.periods}, frame:{c}/{frames})") 30 | plotext.xlim(0, 400) 31 | plotext.plot(x, y, marker="dot", color="red") 32 | plotext.sleep(0.001) 33 | plotext.show() 34 | 35 | plotext.clear_plot() 36 | 37 | if __name__=='__main__': 38 | main() 39 | -------------------------------------------------------------------------------- /coloumb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from VALID import ns, OK 3 | 4 | print("\n--------------------LEY DE COLOUMB-------------------") 5 | print("----------------Formula F=K*(Q*Q'/d*d)--------------\n") 6 | 7 | while True: 8 | c1 = OK(input("Digite carga1 Q : ")) 9 | c2 = OK(input("Digite carga2 Q' : ")) 10 | d = OK(input("Digite distancia entre las cargas d: ")) 11 | k=9000000000 12 | f=k*(c1*c2/d*d) 13 | 14 | print("La Fuerza de Atraccion o repulsion F es ",f,"Newtons") 15 | 16 | conti = ns(input("¿Desea continuar?(n/s): ")) 17 | if conti == "n": 18 | break 19 | -------------------------------------------------------------------------------- /compara_imagenes.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import os 4 | from VALID import ns 5 | 6 | while True: 7 | d = input("Introduce dirección: ") 8 | if os.path.isdir(d): 9 | os.chdir(d) 10 | break 11 | else: 12 | print("Dirección no válida: ") 13 | 14 | def busca_imagen(): 15 | while True: 16 | im = input("Introduzca nombre de la imagen: ") 17 | if im in os.listdir(): 18 | return im 19 | break 20 | else: 21 | print("NO SE ENCONTRÓ LA IMAGEN ", im) 22 | 23 | 24 | while True: 25 | 26 | imagen1 = cv2.imread(busca_imagen()) 27 | imagen2 = cv2.imread(busca_imagen()) 28 | 29 | try: 30 | diferencia = cv2.subtract(imagen1, imagen2) 31 | resul = not np.any(diferencia) 32 | except: 33 | resul = False 34 | 35 | if resul is True: 36 | print("Las imagenes son iguales") 37 | else: 38 | print("Las imagenes son diferentes") 39 | 40 | conti = ns(input("¿Continuar?: ")) 41 | if conti == "n": 42 | break 43 | -------------------------------------------------------------------------------- /compare_image.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/compare_image.zip -------------------------------------------------------------------------------- /copiador.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from shutil import copyfile 4 | from sys import exit 5 | 6 | def ns(c): 7 | while c!=("s") and c!=("n"): 8 | print(chr(7));c=input("Escribe solo \'n\' o \'s\' según su opción: ") 9 | return(c) 10 | 11 | 12 | origen = input("Introduce ruta del archivo a copiar: ") 13 | destino = input("Introduce ruta de la carpeta de destino: ") 14 | 15 | try: 16 | copyfile(origen, destino) 17 | except IOError as e: 18 | print("No se pudo copiar el archivo. %s" % e) 19 | exit(1) 20 | except: 21 | print("Error:", sys.exc_info()) 22 | exit(1) 23 | 24 | print("\nCopia realizada con exito\n") 25 | 26 | while True: 27 | comprobar=ns(input("Desea visualizar el archivo copiado?: ")) 28 | if comprobar ==("n"): 29 | break 30 | elif comprobar == 's': 31 | archivo = open(origen, "r") 32 | print("\nContenido:\n") 33 | print(archivo.read()) 34 | archivo.close() 35 | print() 36 | break 37 | else: 38 | continue 39 | -------------------------------------------------------------------------------- /crazy_text.py: -------------------------------------------------------------------------------- 1 | import time 2 | import curses 3 | import random 4 | 5 | stdscr=curses.initscr() 6 | 7 | curses.curs_set(0) 8 | curses.noecho() 9 | curses.cbreak() 10 | stdscr.keypad(True) 11 | 12 | for i in ["Este","es","un","sencillo","ejemplo","de", 13 | "prueba","espero","que","te","guste"]: 14 | try: 15 | n=random.randint(1,28)#25 16 | m=random.randint(1,116)#125 17 | stdscr.addstr(n,m,i) 18 | except: 19 | stdscr.addstr(5,15,"We have a problem here")#15,5 20 | 21 | stdscr.refresh() 22 | time.sleep(1) 23 | stdscr.clear() 24 | 25 | curses.curs_set(1) 26 | curses.echo() 27 | curses.nocbrek() 28 | stdscr.keypad(False) 29 | 30 | curses.endwin() 31 | -------------------------------------------------------------------------------- /crea_excel.py: -------------------------------------------------------------------------------- 1 | #CREANDO DATA FRAMES CON "python" Y "pandas". 2 | 3 | #IMPORTAMOS LIBRERIA. 4 | import pandas as pd 5 | 6 | #CREAMOS DATA FRAME. 7 | df_demografia = pd.DataFrame({ 8 | 'CAPITALES':['MADRID','LONDRES','PARIS'], 9 | 'Población':[3207247,8787892,2206488], 10 | 'Densidad':[5266,5590,21258] 11 | 12 | }) 13 | 14 | #AÑADIMOS NUEVO DATA FRAME 15 | df_natur = pd.DataFrame({ 16 | 'CAPITALES':['MADRID','LONDRES','PARIS'], 17 | 'Extensión':[604.45,105.4,1572], 18 | 'Clima':['Transi','Oceánico','Oceánico'] 19 | 20 | }) 21 | 22 | 23 | #CREAMOS ARCHIVO EXCEL. 24 | with pd.ExcelWriter('capitales_datos.xls') as writer: 25 | df_demografia.to_excel(writer,sheet_name="demografia") 26 | #AÑADIMOS LA NUEVA HOJA AL EXCEL. 27 | df_natur.to_excel(writer,"fisica") 28 | 29 | 30 | -------------------------------------------------------------------------------- /crt_image_effect.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | def apply_crt_effect(image): 5 | # Cambiar el tamaño de la imagen para simular el efecto CRT 6 | resized = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR) 7 | 8 | # Aplicar un efecto de desenfoque 9 | blur = cv2.GaussianBlur(resized, (5,5), 0) 10 | 11 | # Añadir efecto de distorsión con líneas horizontales y verticales 12 | num_iterations = 5 13 | for _ in range(num_iterations): 14 | for i in range(0, len(blur), 2): 15 | blur[i] = np.roll(blur[i], 1) 16 | 17 | for i in range(0, len(blur[0]), 2): 18 | blur[:, i] = np.roll(blur[:, i], 1) 19 | 20 | return blur 21 | 22 | # Cargar la imagen 23 | input_image = cv2.imread('source_image') 24 | 25 | # Aplicar el efecto CRT 26 | crt_effect = apply_crt_effect(input_image) 27 | cv2.imwrite('effect_ima.jpg',crt_effect) 28 | 29 | # Mostrar la imagen original y la imagen con efecto CRT 30 | cv2.imshow('Original', input_image) 31 | cv2.imshow('CRT Effect', crt_effect) 32 | cv2.waitKey(0) 33 | cv2.destroyAllWindows() 34 | -------------------------------------------------------------------------------- /cursesControl_demo.py: -------------------------------------------------------------------------------- 1 | import curses 2 | import time 3 | from curses import textpad 4 | 5 | stdscr = curses.initscr() 6 | curses.curs_set(0) 7 | curses.noecho() 8 | curses.cbreak() 9 | stdscr.keypad(True) 10 | 11 | def main(stdscr): 12 | texto="CENTRE" 13 | sh, sw = stdscr.getmaxyx() 14 | posicion1=sh//2 15 | posicion2=sw//2 16 | #def main(stdscr): 17 | stdscr.addstr(posicion1,(posicion2)-((len(texto))//2),texto) 18 | 19 | while True: 20 | key=stdscr.getch() 21 | if key==curses.KEY_RIGHT: 22 | posicion2=posicion2+1 23 | texto="RIGHT" 24 | elif key==curses.KEY_DOWN: 25 | posicion1=posicion1+1 26 | texto="DOWN" 27 | elif key==curses.KEY_LEFT: 28 | posicion2=posicion2-1 29 | texto="LEFT" 30 | elif key==curses.KEY_UP: 31 | posicion1=posicion1-1 32 | texto="UP" 33 | stdscr.clear() 34 | stdscr.addstr(posicion1,(posicion2)-((len(texto))//2),texto) 35 | 36 | main(stdscr) 37 | 38 | stdscr.refresh() 39 | time.sleep(1) 40 | stdscr.clear() 41 | 42 | curses.curs_set(1) 43 | curses.echo() 44 | curses.nocbrek() 45 | stdscr.keypad(False) 46 | 47 | 48 | curses.endwin() 49 | -------------------------------------------------------------------------------- /daily_return.py: -------------------------------------------------------------------------------- 1 | import ta 2 | import matplotlib.pyplot as plt 3 | import yfinance as yf 4 | from ta.utils import dropna 5 | import warnings 6 | warnings.filterwarnings("ignore") 7 | 8 | ticker = "GOGL" 9 | 10 | df = yf.Ticker(ticker).history(period="max").reset_index()[["Date","Close"]] 11 | 12 | df = dropna(df) 13 | print(df.head()) 14 | 15 | #bol = ta.volatility.BollingerBands(df["Close"], window=20)#14 16 | 17 | df['dlr'] = ta.others.DailyLogReturnIndicator(df["Close"]).daily_log_return() 18 | 19 | print(df["dlr"].head()) 20 | 21 | plt.grid() 22 | plt.title(ticker+ " DAILY RETURN" ) 23 | plt.plot(df["Date"],df["dlr"], color="green") 24 | 25 | #plt.fill_between(df["Date"],df["Low Band"],df["High Band"], alpha=0.2, color="orange") 26 | plt.xlabel("Date") 27 | plt.ylabel("Price") 28 | plt.legend(loc="best") 29 | 30 | plt.show() 31 | -------------------------------------------------------------------------------- /data_extractor.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import tkinter.scrolledtext as scrolledtext 3 | from PIL import Image 4 | from PIL.ExifTags import TAGS 5 | 6 | class App: 7 | def __init__(self): 8 | self.ventana = Tk() 9 | self.ventana.title("DATA EXTRACTOR") 10 | #self.ventana.geometry("630x200") 11 | 12 | self.canvas = Canvas(self.ventana,bg='black',width=200,height=100) 13 | self.canvas.pack() 14 | 15 | self.ventana.mainloop() 16 | 17 | if __name__=="__main__": 18 | App() 19 | -------------------------------------------------------------------------------- /datos_google.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader as pdr 2 | import matplotlib.pyplot as plt 3 | import datetime 4 | 5 | googl = pdr.get_data_yahoo('GOOGL',start=datetime.datetime(2009,10,1)) 6 | 7 | column = googl['Close'][-10:] 8 | 9 | print(column) 10 | 11 | #VER GRAFICA. 12 | column.plot(grid=True) 13 | plt.show() 14 | -------------------------------------------------------------------------------- /detector_contornos.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import matplotlib.pyplot as plt 3 | 4 | # LEER IMAGEN 5 | image = cv2.imread(imagen) 6 | # CONVERTIR A 'RGB' 7 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 8 | # CONVERTIR A ESCALA DE GRISES 9 | gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) 10 | # IMAGEN BINARIA 11 | _, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV) 12 | # MOSTRAR 13 | plt.imshow(binary, cmap="gray") 14 | plt.show() 15 | # DETECTAR CONTORNOS EN IMAHEN BINARIA 16 | contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 17 | # DIBUJAR CONTORNOS 18 | image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2) 19 | # MOSTRAR CONTORNOS SOBRE LA IMAGEN ORIGINAL 20 | plt.imshow(image) 21 | plt.show() 22 | -------------------------------------------------------------------------------- /dibujar_poligonos.py: -------------------------------------------------------------------------------- 1 | import pygame, sys 2 | from pygame.locals import * 3 | 4 | #CREAMOS VENTANA. 5 | pygame.init() 6 | DISPLAYGAME=pygame.display.set_mode((500,400),0,32) 7 | pygame.display.set_caption("Dibujando figuras") 8 | 9 | #DEFINIMOS LOS COLORES QUE VAMOS A EMPLEAR. 10 | negro=(0,0,0) 11 | blanco=(255,255,255) 12 | rojo=(255,0,0) 13 | verde=(0,255,0) 14 | azul=(0,0,255) 15 | 16 | #ESCOJEMOS EL COLOR DEL FONDO 17 | DISPLAYGAME.fill(blanco) 18 | 19 | #DIBUJAMOS POLIGONO. 20 | pygame.draw.polygon(DISPLAYGAME, verde, ((146,0),(291,106),(236,277), 21 | (26,277),(0,106))) 22 | #DIBUJAMOS LINEA. 23 | pygame.draw.line(DISPLAYGAME, azul, (120,60), (60,120)) 24 | #DIBUJAMOS LINEA ESPECIFICANDO GROSOR. 25 | pygame.draw.line(DISPLAYGAME, azul, (60,60), (120,60), 20) 26 | #DIBUJAMOS CIRCULO. 27 | pygame.draw.circle(DISPLAYGAME, rojo, (300,50),20,0) 28 | #DIBUJAMOS ELIPSE. 29 | pygame.draw.ellipse(DISPLAYGAME, azul, (300,250,40,80), 1) 30 | #DIBUJAMOS RECTANGULO. 31 | pygame.draw.rect(DISPLAYGAME, rojo, (200, 150, 100, 50)) 32 | 33 | #GENERAMOS CICLO PARA LA VENTANA. 34 | while True: 35 | for event in pygame.event.get(): 36 | if event.type==QUIT: 37 | pygame.quit() 38 | sys.exit() 39 | pygame.display.update() 40 | -------------------------------------------------------------------------------- /direct_text_to_speech.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | 3 | # Inicializar el motor de pyttsx3 4 | engine = pyttsx3.init() 5 | 6 | # Establecer el idioma (si es compatible con tu sistema) 7 | engine.setProperty('voice', 'spanish') # Algunas configuraciones pueden necesitar ajuste según el sistema 8 | engine.setProperty('rate',200) 9 | 10 | while True: 11 | texto = input("> ") 12 | engine.say(texto) 13 | engine.runAndWait() 14 | 15 | if texto == "": 16 | print("Programa terminado") 17 | break 18 | 19 | -------------------------------------------------------------------------------- /distributions.py: -------------------------------------------------------------------------------- 1 | import matplotlib as mpl 2 | import scipy 3 | import matplotlib.pyplot as plt 4 | from scipy.stats import skew, kurtosis, chi2 5 | import numpy as np 6 | 7 | #inputs 8 | coeff = 5 # df in student, scale in exponential 9 | size = 10**6 10 | random_variable_type = 'uniform' 11 | decimals = 5 12 | 13 | # code 14 | str_title = random_variable_type 15 | if random_variable_type == 'normal': 16 | x = np.random.standard_normal(size=size) 17 | elif random_variable_type == 'student': 18 | x = np.random.standard_t(df=coeff,size=size) 19 | str_title = str_title + ' df=' + str(coeff) 20 | elif random_variable_type == 'uniform': 21 | x = np.random.uniform(size=size) 22 | elif random_variable_type == 'exponential': 23 | x = np.random.exponential(scale=coeff, size=size) 24 | str_title += ' scale=' + str(coeff) 25 | elif random_variable_type == 'chi-squared': 26 | x = np.random.chisquare(df=coeff, size=size) 27 | str_title += ' df=' + str(coeff) 28 | 29 | mu = np.mean(x) 30 | sigma = np.std(x) 31 | skew = skew(x) 32 | kurt = kurtosis(x) 33 | 34 | str_title += '\n' + 'mean=' + str(np.round(mu,decimals)) \ 35 | + '\n' + 'volatility=' + str(np.round(sigma,decimals)) \ 36 | + '\n' + 'skewness=' + str(np.round(skew,decimals)) \ 37 | + '\n' + 'kurtosis=' + str(np.round(kurt,decimals)) 38 | 39 | plt.figure() 40 | plt.hist(x,bins=100) 41 | plt.title(str_title) 42 | plt.show() 43 | -------------------------------------------------------------------------------- /dob.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/dob.jpg -------------------------------------------------------------------------------- /drake.py: -------------------------------------------------------------------------------- 1 | from VALID import ny 2 | 3 | def se(q): 4 | while True: 5 | p = input(q) 6 | try: 7 | r = float(p) 8 | break 9 | except Exception as e: 10 | r = str(e) 11 | print(r) 12 | return r 13 | 14 | while True: 15 | print("----------------------------------------DRAKE EQUATION----------------------------------------") 16 | print("----------------------------N = R* x fp x ne x fl x fi x fc x L-------------------------------") 17 | 18 | R = se("Average rate of star formation in the galaxy (new stars per year): ") 19 | fp = se("Fraction of stars with planets: ") 20 | ne = se("Stars with planets, the average number of planets with an environment suitable for life: ") 21 | fl = se("Fraction of planets that develop life: ") 22 | fi = se("Fraction of life­bearing planets with intelligent, civilized life: ") 23 | fc = se("Fraction of civilizations that release detectable signs of their existence into space: ") 24 | L = se("Length of time (in years) over which the civilizations release the detectable signals: ") 25 | 26 | N = R*fp*ne*fl*fi*fc*L 27 | print("\n{} Civilitations.".format(N)) 28 | 29 | conti = ny(input("Continue(n/y)?: ")) 30 | if conti == "n": 31 | break 32 | 33 | -------------------------------------------------------------------------------- /ejemRegresion_lineal.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import random 3 | from sklearn import linear_model 4 | from sklearn.metrics import mean_squared_error, r2_score 5 | import matplotlib.pyplot as plt 6 | #%matplotlib inline 7 | 8 | # Generador de distribución de datos para regresión lineal simple 9 | def generador_datos_simple(beta, muestras, desviacion): 10 | # Genero n (muestras) valores de x aleatorios entre 0 y 100 11 | x = np.random.random(muestras) * 100 12 | # Genero un error aleatorio gaussiano con desviación típica (desviacion) 13 | e = np.random.randn(muestras) * desviacion 14 | # Obtengo el y real como x*beta + error 15 | y = x * beta + e 16 | return x.reshape((muestras,1)), y.reshape((muestras,1)) 17 | 18 | # Parámetros de la distribución 19 | desviacion = 200 20 | beta = 10 21 | n = 50 22 | x, y = generador_datos_simple(beta, n, desviacion) 23 | 24 | # Represento los datos generados 25 | #plt.scatter(x, y) 26 | #plt.show() 27 | 28 | # Creo un modelo de regresión lineal 29 | modelo = linear_model.LinearRegression() 30 | 31 | # Entreno el modelo con los datos (X,Y) 32 | modelo.fit(x, y) 33 | # Ahora puedo obtener el coeficiente b_1 34 | print (u'Coeficiente beta1: ', modelo.coef_[0]) 35 | 36 | # Podemos predecir usando el modelo 37 | y_pred = modelo.predict(x) 38 | 39 | # Por último, calculamos el error cuadrático medio y el estadístico R^2 40 | print (u'Error cuadrático medio: %.2f' % mean_squared_error(y, y_pred)) 41 | print (u'Estadístico R_2: %.2f' % r2_score(y, y_pred)) 42 | 43 | # Representamos el ajuste (rojo) y la recta Y = beta*x (verde) 44 | plt.scatter(x, y) 45 | plt.plot(x, y_pred, color='red') 46 | x_real = np.array([0, 100]) 47 | y_real = x_real*beta 48 | plt.plot(x_real, y_real, color='green') 49 | plt.show() 50 | -------------------------------------------------------------------------------- /ejem_clases.py: -------------------------------------------------------------------------------- 1 | 2 | # CLASE "Persona" 3 | class Persona: 4 | def __init__(self, nombre, edad): 5 | self.nombre = nombre 6 | self.edad = edad 7 | 8 | def saludar(self): 9 | print(f"Hola, mi nombre es {self.nombre} y tengo {self.edad} años.") 10 | 11 | # CREAMOS OBJETOS DE LA CLASE "Persona" 12 | persona1 = Persona("Juan", 25) 13 | persona2 = Persona("Maria", 30) 14 | 15 | # LLAMAMOS AL MÉTODO "saludar" DE AMBOS OBJETOS. 16 | persona1.saludar() 17 | persona2.saludar() 18 | 19 | 20 | # DECLARAMOS CLASE 21 | class Estudiante(Persona): 22 | def __init__(self, nombre, edad, curso): 23 | super().__init__(nombre, edad) 24 | self.curso = curso 25 | 26 | def presentarse(self): 27 | print(f"Soy {self.nombre}, tengo {self.edad} años y estoy en el curso {self.curso}.") 28 | 29 | 30 | # CREAMOS OBJETO DE LA CLASE "Estudiante" 31 | estudiante1 = Estudiante("Pedro", 20, "Matemáticas") 32 | 33 | # LLAMAMOS A LOS MÉTODOS HEREDADOS DE LA CALSE "Persona" 34 | estudiante1.saludar() 35 | 36 | # LLAMAMOS EL MÉTODO "presentarse" DE LA CLASE "Estudiante" 37 | estudiante1.presentarse() 38 | -------------------------------------------------------------------------------- /ejem_clases2.py: -------------------------------------------------------------------------------- 1 | 2 | # DECLARAMOS CLASE "CuentaBancaria" 3 | class CuentaBancaria: 4 | def __init__(self, titular, saldo): 5 | self.titular = titular 6 | self.__saldo = saldo # Atributo privado 7 | 8 | def depositar(self, cantidad): 9 | self.__saldo += cantidad 10 | 11 | def retirar(self, cantidad): 12 | if cantidad <= self.__saldo: 13 | self.__saldo -= cantidad 14 | else: 15 | print("Saldo insuficiente.") 16 | 17 | def obtener_saldo(self): 18 | return self.__saldo 19 | 20 | # CREAMOS OBJETO DE LA CLASE "CuentaBancaria" 21 | cuenta = CuentaBancaria("Juan", 1000) 22 | 23 | # ACCEDEMOS AL ATRIBUTO PRIVADO "saldo" A TRAVÉS DE MÉTODO PÚBLICO 24 | print(cuenta.obtener_saldo()) 25 | 26 | # SI IENTENTAMOS ACCEDER DIRECTAMENTE AL ATRIBUTO PRIVADO SE GEBERARÁ 27 | # UN ERROR 28 | print(cuenta.__saldo) 29 | -------------------------------------------------------------------------------- /ejemplo1_amp.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS LIBRERIAS. 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import animatplot as amp 5 | 6 | #INTRODUCIMOS DATOS. 7 | x = np.linspace(0, 1, 50) 8 | t = np.linspace(0, 1, 20) 9 | 10 | X, T = np.meshgrid(x, t) 11 | Y = np.sin(2*np.pi*(X+T)) 12 | 13 | #CREAMOS OBJETO "timeline". 14 | timeline = amp.Timeline(t, units='s', fps=20) 15 | 16 | #GENERAMOS ANIMACIÓN. 17 | block = amp.blocks.Line(X, Y, marker=".", linestyle="-", color="r") 18 | anim = amp.Animation([block],timeline) 19 | 20 | #DEFINICIÓN DE ETIQUETAS PARA TITULO Y EJES. 21 | plt.title("Sine Wave") 22 | plt.xlabel("x") 23 | plt.ylabel("y") 24 | 25 | #GUARDAMOS ANIMACIÓN. 26 | anim.save_gif('graph_anim.gif') 27 | 28 | #INTRODUCIMOS LÍNEA DE TIEMPO 29 | #Y BOTÓN PAUSE/PLAY 30 | anim.controls() 31 | 32 | #REPRESENTAMOS GRÁFICA. 33 | plt.show() 34 | -------------------------------------------------------------------------------- /ejemplo1_opencv.py: -------------------------------------------------------------------------------- 1 | #IMPORTAR "opencv2". 2 | import cv2 3 | 4 | #CARGAR IMAGEN 5 | img = cv2.imread('Honda_goldwing_1500.jpg',0) 6 | 7 | #MOSTRAR IMAGEN EN ESCALA DE GRISES. 8 | cv2.imshow('image',img) 9 | k = cv2.waitKey(0) 10 | 11 | #CONTROL DE VENTANA POR TECLADO. 12 | if k == 27: 13 | cv2.destroyAllWindows() 14 | elif k == ord('s'): 15 | cv2.imwrite('Honda_goldwing_gray.jpg',img) 16 | cv2.destroyAllWindows() 17 | -------------------------------------------------------------------------------- /ejemplo_cola.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS "deque". 2 | from collections import deque 3 | 4 | class Cola(object): 5 | def __init__(self): 6 | self.items=deque() 7 | 8 | #AÑADE ELEMENTOS A LA COLA POR LA IZQUIERDA 9 | def encolar(self,x): 10 | self.items.appendleft(x) 11 | 12 | #MUESTRA COLA 13 | def muestra_cola(self): 14 | print(self.items) 15 | 16 | #VERIFICA SI LA COLA ESTA VACIA 17 | def esta_vacia(self): 18 | if len(self.items)==0: 19 | return True 20 | else: 21 | return False 22 | 23 | #DEVUELVE ELEMENTO DE LA COLA POR LA DERECHA 24 | def desencolar(self): 25 | if self.esta_vacia(): 26 | return None 27 | else: 28 | return self.items.pop() 29 | -------------------------------------------------------------------------------- /ejemplo_con_map.py: -------------------------------------------------------------------------------- 1 | def cuadrado(x): 2 | return x * x 3 | 4 | resultado = map(cuadrado, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 5 | 6 | print(list(resultado)) 7 | -------------------------------------------------------------------------------- /ejemplo_grafbarras3d.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS MÓDULOS NECESARIOS. 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | from mpl_toolkits.mplot3d import axes3d 5 | 6 | #CREAMOS FIGURA. 7 | fig = plt.figure() 8 | ax1 = fig.add_subplot(111, projection='3d') 9 | 10 | #COORDENADA DE CADA BARRA 11 | x = [1,2,3,4,2,6,7,8,9,10] 12 | y = [3,4,6,7,1,2,5,9,10,5] 13 | z = np.zeros(10) 14 | 15 | dx = np.ones(10) #ANCHURA DE CADA BARRA 16 | dy = np.ones(10) #PROFUNDIDAD DE CADA BARRA 17 | dz = [2,3,4,3,4,5,3,7,8,2] #ALTURA DE CADA BARRA 18 | 19 | #REPRESENTACION DE LOS DATOS 20 | ax1.bar3d(x, y, z, dx, dy, dz) 21 | 22 | plt.show() 23 | -------------------------------------------------------------------------------- /ejemplo_listbox.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS TKINTER 2 | from tkinter import * 3 | 4 | #FUNCIÓN PARA AÑADIR ELEMENTOS. 5 | def añadir(): 6 | lista_elementos.insert(END, entrada.get()) 7 | 8 | 9 | #CREAMOS VENTANA 10 | ventana=Tk() 11 | ventana.geometry("700x600") 12 | ventana.title("Lista") 13 | 14 | #CREAMOS LISTBOX 15 | lista_elementos=Listbox(ventana,width=50) 16 | 17 | #AÑADIMOS ELEMENTOS 18 | lista_elementos.insert(0,"Elemento 1") 19 | lista_elementos.insert(1,"Elemento 2") 20 | lista_elementos.insert(2,"Elemento 3") 21 | lista_elementos.insert(3,"Elemento 4") 22 | 23 | #UBICAMOS LA LISTA 24 | lista_elementos.place(x=100,y=120) 25 | lista_etiq=Label(ventana,text="Lista de Elementos").place(x=100,y=100) 26 | 27 | #ENTRADA NUEVOS ELEMENTOS 28 | entrada=StringVar() 29 | entrada_elementos=Entry(ventana,textvariable=entrada,width=40).place(x=150,y=20) 30 | 31 | #BOTON DE AÑADIR ELEMENTOS 32 | boton_añadir=Button(ventana,text="añadir",heigh=2,width=18,command=añadir).place(x=400,y=20) 33 | 34 | ventana.mainloop() 35 | -------------------------------------------------------------------------------- /ejemplo_pila.py: -------------------------------------------------------------------------------- 1 | #IMPLEMENTACION DE UNA PILA EN PYTHON. 2 | 3 | class Pila(object): 4 | 5 | def __init__(self): 6 | self.items=[] 7 | 8 | def apilar(self, dato): #REALIZA ACCIÓN DE APILAR 9 | self.items.append(dato) 10 | 11 | def desapilar(self): #SACA ELEMENTOS DE LA PILA 12 | if self.esta_vacia(): 13 | return None 14 | else: 15 | return self.items.pop() 16 | 17 | def esta_vacia(self): #VERIFICA SI LA PILA ESTÁ VACIA 18 | if len(self.items)==0: 19 | return True 20 | else: 21 | return False 22 | 23 | def ver_pila(self): #VER ELEMENTOS DE LA PILA 24 | print(self.items) 25 | -------------------------------------------------------------------------------- /ejemplo_reduce.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | def suma(a, b): 4 | print(f'a={a}, b={b}') 5 | return a + b 6 | 7 | res = reduce(suma, [1, 2, 3, 4, 5]) 8 | print(res) 9 | -------------------------------------------------------------------------------- /ejemplo_thread.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | #FUNCIÓN A EJECUTAR 4 | def cuenta(n, name): 5 | count=n 6 | while count<10: 7 | print("") 8 | print(count) 9 | count+=1 10 | 11 | #CREAMOS PROCESOS A EJECUTAR EN PARALELO. 12 | t = threading.Thread(target = cuenta, args =(1, 'thread1') ) 13 | t2 = threading.Thread(target = cuenta, args =(2, 'thread2') ) 14 | t3 = threading.Thread(target = cuenta, args =(3, 'thread3') ) 15 | 16 | #INICIAMOS PROCESOS. 17 | t.start() 18 | t2.start() 19 | t3.start() 20 | -------------------------------------------------------------------------------- /ejemplo_thread2.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import time 3 | 4 | def print_time(name, n): 5 | count = 0 6 | while count < 5: 7 | time.sleep(n) 8 | count+=1 9 | print("%s: %s" % ( name, time.ctime(time.time()) )) 10 | 11 | try: 12 | t1 = threading.Thread(target=print_time, args=("Thread-1", 2, ) ) 13 | t2 = threading.Thread(target=print_time, args=("Thread-2", 4, ) ) 14 | 15 | except: 16 | print("No se pudo ejecutar el thread") 17 | 18 | t1.start() 19 | t2.start() 20 | -------------------------------------------------------------------------------- /ejemplo_timeit.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS MODULO "timeit". 2 | import timeit 3 | 4 | #CREAMOS LA CADENA "dias". 5 | dias=['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'] 6 | 7 | #UNIMOS LOS ELEMENTOS SIN ESPACIOS: 8 | 9 | #MEDINATE CICLO "for". 10 | def cadena_sim(dias): 11 | cadena_final = '' 12 | for i in dias: 13 | cadena_final += i 14 | return cadena_final 15 | 16 | #MEDIANTE FORMATO. 17 | def cadena_formato(dias): 18 | cadena_final = "%s%s%s%s%s%s%s" % (dias[0], dias[1], 19 | dias[2], dias[3], 20 | dias[4], dias[5], 21 | dias[6]) 22 | return cadena_final 23 | 24 | #MEDIANTE FUNCIÓN ".join". 25 | def join_cadena(dias): 26 | return ('').join(dias) 27 | 28 | #VISUALIZAMOS TIEMPO DE EJECUCIÓN (EN MILESIMAS DE SEGUNDO) PARA CADA FUNCIÓN. 29 | print('join_cadena() Tiempo de ejecución: ' + str(timeit.timeit('join_cadena(dias)', setup='from __main__ import join_cadena, dias'))) 30 | print('cadena_formato() Tiempo de ejecución: '+ str(timeit.timeit('cadena_formato(dias)', setup='from __main__ import cadena_formato, dias'))) 31 | print('cadena_sim() Tiempo de ejecución: ' + str(timeit.timeit('cadena_sim(dias)', setup='from __main__ import cadena_sim, dias'))) 32 | 33 | -------------------------------------------------------------------------------- /ejemplo_wordcloud.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS RECURSOS. 2 | import wikipedia 3 | from wordcloud import WordCloud 4 | import matplotlib.pyplot as plt 5 | 6 | #OBTENEMOS TEXTO DE "wikipedia". 7 | info = wikipedia.summary("Python") 8 | print(info) 9 | 10 | #GENERAR NUBE 11 | wordCloud = WordCloud().generate(info) 12 | 13 | #MOSTRAR NUBE. 14 | plt.imshow(wordCloud,interpolation='bilinear') 15 | plt.axis("off") 16 | plt.show() 17 | 18 | image = wordCloud.to_image() 19 | image.save("wordcloud.png") 20 | image.show() 21 | -------------------------------------------------------------------------------- /ejemplo_zip.py: -------------------------------------------------------------------------------- 1 | cursos = ['Java', 'Python', 'Git'] 2 | asistentes = [15, 20, 4] 3 | 4 | demo = zip(cursos, asistentes) 5 | 6 | print(list(demo)) 7 | -------------------------------------------------------------------------------- /ejercicio_hash.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | from PIL import Image 3 | 4 | #CALCULA VALOR HASH DE LOS ARCHIVOS USANDO EL ALGORITMO 'SHA256' 5 | def calcular_hash(nombre_archivo, algoritmo='sha256'): 6 | hash_obj = hashlib.new(algoritmo) 7 | with open(nombre_archivo, 'rb') as archivo: 8 | while True: 9 | bloque = archivo.read(65536) # Leer en bloques de 64 KB 10 | if not bloque: 11 | break 12 | hash_obj.update(bloque) 13 | return hash_obj.hexdigest() 14 | 15 | #COMPARA 2 ARCHIVOS DE IMAGEN USANDO SUS HASHES 16 | def comparar_imagenes(imagen1, imagen2): 17 | hash1 = calcular_hash(imagen1) 18 | hash2 = calcular_hash(imagen2) 19 | print(f"El hash de '{imagen1}' es {hash1}.") 20 | print(f"El hash de '{imagen2}' es {hash2}.") 21 | 22 | if hash1 == hash2: 23 | return True 24 | else: 25 | return False 26 | 27 | # COMPARACION DE IMAGENES 28 | imagen1 = 'portrait.jpg' 29 | imagen2 = 'portrait_copia.jpg' 30 | 31 | if comparar_imagenes(imagen1, imagen2): 32 | print(f"\nLas imágenes '{imagen1}' y '{imagen2}' son idénticas.") 33 | else: 34 | print(f"\nLas imágenes '{imagen1}' y '{imagen2}' son diferentes.") 35 | -------------------------------------------------------------------------------- /email_sender.py: -------------------------------------------------------------------------------- 1 | from yagmail import SMTP 2 | 3 | def Email_Sender(subject, body): 4 | mail = SMTP(user='username', password='password') 5 | mail.send("reciever@mail.com", subject = subject, contents = body) 6 | mail.close() 7 | print("Email Sent") 8 | 9 | def Email_With_Attachment(subject, attachment): 10 | mail = SMTP(user='username', password='password') 11 | mail.send("reciever@mail.com", subject = subject, attachments = attachment) 12 | print("Email Sent") 13 | 14 | # main 15 | Email_Sender("Subject101", "Hello from Medium") 16 | Email_With_Attachment("Subject102", ["img1.png", "img2.png"]) 17 | -------------------------------------------------------------------------------- /encryption.py: -------------------------------------------------------------------------------- 1 | from cryptography.fernet import Fernet 2 | 3 | def genera_clave(): 4 | clave = Fernet.generate_key() 5 | with open("clave.key","wb") as archivo_clave: 6 | archivo_clave.write(clave) 7 | 8 | def cargar_clave(): 9 | return open("clave.key","rb").read() 10 | 11 | genera_clave() 12 | clave = cargar_clave() 13 | mensaje = "Mi mensaje".encode() 14 | 15 | f = Fernet(clave) 16 | encriptado = f.encrypt(mensaje) 17 | print(encriptado) 18 | 19 | dessen = f.decrypt(encriptado) 20 | print(dessen) 21 | -------------------------------------------------------------------------------- /encuentra_duplicados.py: -------------------------------------------------------------------------------- 1 | import os 2 | import hashlib 3 | 4 | def calcular_hash_sha256(nombre_archivo): 5 | """Calcula el hash SHA-256 de un archivo.""" 6 | sha256 = hashlib.sha256() 7 | with open(nombre_archivo, "rb") as archivo: 8 | while True: 9 | bloque = archivo.read(65536) # Lee en bloques de 64 KB 10 | if not bloque: 11 | break 12 | sha256.update(bloque) 13 | return sha256.hexdigest() 14 | 15 | def encontrar_duplicados(directorio): 16 | """Encuentra archivos duplicados en un directorio basándose en sus hash SHA-256.""" 17 | hash_dict = {} 18 | duplicados = [] 19 | 20 | # Itera sobre todos los archivos en el directorio 21 | for raiz, directorios, archivos in os.walk(directorio): 22 | for archivo in archivos: 23 | ruta_completa = os.path.join(raiz, archivo) 24 | hash = calcular_hash_sha256(ruta_completa) 25 | 26 | # Si el hash ya existe en el diccionario, se encuentra un duplicado 27 | if hash in hash_dict: 28 | duplicados.append((hash, ruta_completa)) 29 | else: 30 | hash_dict[hash] = ruta_completa 31 | 32 | return duplicados 33 | 34 | if __name__ == "__main__": 35 | directorio_busqueda = "/ruta/a/tu/directorio" # Reemplaza esto con la ruta de tu directorio 36 | resultados = encontrar_duplicados(directorio_busqueda) 37 | 38 | if resultados: 39 | print("Archivos duplicados encontrados:") 40 | for hash, ruta in resultados: 41 | print(f"Hash: {hash}\nRuta: {ruta}\n") 42 | else: 43 | print("No se encontraron archivos duplicados en el directorio.") 44 | -------------------------------------------------------------------------------- /escribe_fichero.py: -------------------------------------------------------------------------------- 1 | 2 | #CREAR FICHERO 3 | fichero = open('miFicheroNuevo.txt', 'x') 4 | fichero.close() 5 | 6 | #ESCRIBIR EN FICHERO 7 | fichero = open('miFicheroNuevo.txt', 'w') 8 | lineas = [ 9 | 'Linea1\n', 10 | 'Linea2\n', 11 | 'Linea3\n', 12 | 'Linea4\n' 13 | ] 14 | 15 | fichero.writelines(lineas) 16 | fichero.close() 17 | -------------------------------------------------------------------------------- /estimacion_pi.py: -------------------------------------------------------------------------------- 1 | #IMPORTAR MÓDULO "RANDOM". 2 | import random 3 | 4 | #RANGO 5 | INTERVAL= 2000 6 | 7 | circle_points= 0 #PUNTOS DENTRO DEL CÍRCULO 8 | square_points= 0 #PUNTOS DENTRO DEL CUADRADO 9 | 10 | for i in range(INTERVAL**2): 11 | 12 | #GENERACIÓN DE PUNTOS 13 | rand_x= random.uniform(-1, 1) 14 | rand_y= random.uniform(-1, 1) 15 | 16 | #DISTANCIA DE CADA PUNTO DEL ORIGEN 17 | origin_dist= (rand_x**2 + rand_y**2)**0.5 18 | 19 | #COMPROBAR SI EL PUNTO ESTÁ DENTRO DEL CÍRCULO. 20 | if origin_dist<= 1: 21 | circle_points+= 1 22 | 23 | square_points+= 1 24 | 25 | #OBTENCIÓN DEL VALOR DE PI. 26 | pi = 4* circle_points/ square_points 27 | 28 | #ESTIMACIÓN FINAL. 29 | print("PI ESTIMATION: ", pi) 30 | print('TOTAL POINTS: ',square_points) 31 | -------------------------------------------------------------------------------- /etf.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /etf_rand.py: -------------------------------------------------------------------------------- 1 | from yahooquery import Screener 2 | import yfinance as yf 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | import pandas as pd 6 | 7 | s = Screeners() 8 | '''screeners = s.available_screeners 9 | 10 | for i in screeners: 11 | is 'us' in i: 12 | print(i)''' 13 | 14 | data =s.get_screeners('top_etfs_us',count=250) 15 | etf_data = data['top_etfs_us']['quotes'] 16 | ticker_list = [etf['symbol'] for etf in etf_data] 17 | 18 | df = yf.download(ticker_list,start='2018-01-01',progress=False)['Close'] 19 | 20 | returns = df.pct_change()[1:] 21 | 22 | corr = returns.corr(method='pearson') 23 | 24 | upper = corr.where(np.triu(np.ones(corr.shape),k=1).astype(np.bool8)) 25 | upper = upper.unstack().dropna() 26 | upper = upper.sort_values(ascending=False) 27 | 28 | up = upper[:100] 29 | up = [item for t in up.index for item in t] 30 | 31 | down = upper[-100:] 32 | down = [item for t in down.index for item in t] 33 | 34 | cagr = pd.DataFrame(index=df.index) 35 | -------------------------------------------------------------------------------- /exchanges.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup as bs 3 | from dateutil.parser import parse 4 | from pprint import pprint 5 | 6 | def get_exchange_list_xrates(currency, amount=1): 7 | #ACCEDER AL CONTENIDO DE LA PÁGINA. 8 | content = requests.get(f"https://www.x-rates.com/table/?from={currency}&amount={amount}").content 9 | #INICIAR 'BeautifulSoup'. 10 | soup = bs(content, "html.parser") 11 | #OBTENER PRECIOS ACTUALIZADOS. 12 | price_datetime = parse(soup.find_all("span", attrs={"class": "ratesTimestamp"})[1].text) 13 | #OBTENER TABLA DE CAMBIOS. 14 | exchange_tables = soup.find_all("table") 15 | exchange_rates = {} 16 | for exchange_table in exchange_tables: 17 | for tr in exchange_table.find_all("tr"): 18 | tds = tr.find_all("td") 19 | if tds: 20 | currency = tds[0].text 21 | exchange_rate = float(tds[1].text) 22 | exchange_rates[currency] = exchange_rate 23 | return price_datetime, exchange_rates 24 | 25 | #LLAMADA A FUNCIÓN. 26 | if __name__ == "__main__": 27 | import sys 28 | source_currency = 'EUR' 29 | amount = 1 30 | price_datetime, exchange_rates = get_exchange_list_xrates(source_currency, amount) 31 | print("Last updated:", price_datetime) 32 | pprint(exchange_rates) 33 | -------------------------------------------------------------------------------- /extract_imagemetadata.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from PIL.ExifTags import TAGS 3 | import os 4 | 5 | imagename = 'dob.jpg' 6 | image = Image.open(imagename) 7 | exifdata = image._getexif() 8 | 9 | if exifdata is not None: 10 | for tag_id in exifdata: 11 | tag = TAGS.get(tag_id, tag_id) 12 | data = exifdata.get(tag_id) 13 | if isinstance(data, bytes): 14 | data = data.decode() 15 | print('{} {}'.format(tag,data)) 16 | -------------------------------------------------------------------------------- /fileType_searcher.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | count = 0 4 | 5 | file_type = raw_input("Introduce tipo de archivo a buscar:") 6 | 7 | for (nombredir, dirs, ficheros) in os.walk('.'): 8 | for nombrefichero in ficheros: 9 | if nombrefichero.endswith(file_type): 10 | count = count+1 11 | 12 | print(count) 13 | 14 | -------------------------------------------------------------------------------- /file_compressor.py: -------------------------------------------------------------------------------- 1 | # Compress folders and files 2 | import zipfile as zf 3 | import os 4 | 5 | # compress files 6 | def compress_files(files): 7 | with zf.ZipFile("compress", 'w') as myzip: 8 | for file in files: 9 | myzip.write(file) 10 | 11 | # compress folders 12 | def compress_folders(folders): 13 | with zf.ZipFile("compress", 'w') as myzip: 14 | for folder in folders: 15 | for root, dirs, files in os.walk(folder): 16 | for file in files: 17 | myzip.write(os.path.join(root, file)) 18 | 19 | # main 20 | compress_files(["video1.mp4", "video2.mp4"]) 21 | compress_folders(["folder1", "folder2"]) 22 | -------------------------------------------------------------------------------- /file_explorer.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | from PyQt5.QtWidgets import QApplication, QWidget, QTreeView, QFileSystemModel, QVBoxLayout, QPushButton, QFileDialog, QLabel 4 | from PyQt5.QtCore import QModelIndex 5 | 6 | class FileSystemView(QWidget): 7 | def __init__(self, dir_path): 8 | super().__init__() 9 | 10 | # TITULO Y DIMENSIONES DE LA VENTANA. 11 | self.setWindowTitle('File System Viewer') 12 | self.setGeometry(300, 300, 800, 300) 13 | 14 | # DEFINIR DIRECTORIO. 15 | self.model = QFileSystemModel() 16 | self.model.setRootPath(dir_path) 17 | 18 | # RUTA DEL DIRECTORIO ACTUAL 19 | self.currentDirLabel = QLabel() 20 | self.currentDirLabel.setText(f"Directorio actual: {dir_path}") 21 | 22 | # GENERAR VISTA DE ARCHIVOS Y CARPETAS. 23 | self.tree = QTreeView() 24 | self.tree.setModel(self.model) 25 | self.tree.setRootIndex(self.model.index(dir_path)) 26 | self.tree.setColumnWidth(200, 250) 27 | self.tree.setAlternatingRowColors(True) 28 | 29 | # BOTÓN PARA CAMBIAR EL DIRECTORIO. 30 | self.changeDirButton = QPushButton("Cambiar Directorio") 31 | self.changeDirButton.clicked.connect(self.changeDirectory) 32 | 33 | # MOSTRAR VENTANA CON LA VISTA, LA RUTA ACTUAL Y EL BOTÓN. 34 | layout = QVBoxLayout() 35 | layout.addWidget(self.currentDirLabel) 36 | layout.addWidget(self.tree) 37 | layout.addWidget(self.changeDirButton) 38 | 39 | self.setLayout(layout) 40 | 41 | def changeDirectory(self): 42 | dirPath = QFileDialog.getExistingDirectory(self, "Seleccionar directorio", os.getcwd()) 43 | if dirPath: 44 | self.tree.setRootIndex(self.model.index(dirPath)) 45 | self.currentDirLabel.setText(f"Directorio actual: {dirPath}") 46 | 47 | 48 | if __name__ == '__main__': 49 | app = QApplication(sys.argv) 50 | 51 | # DIRECTORIO BASE. 52 | dirPath = os.getcwd() 53 | 54 | demo = FileSystemView(dirPath) 55 | demo.show() 56 | sys.exit(app.exec_()) 57 | 58 | -------------------------------------------------------------------------------- /frames_to_video.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import os 4 | from os.path import isfile, join 5 | 6 | 7 | def convertToVideo(pathIn, pathOut, fps, time): 8 | frame_array = [] 9 | files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))] 10 | files.sort(key=lambda x: int((x.split(".")[0]).split(" ")[1]))#REORDENA FRAMES 11 | for i in range(len(files)): 12 | filename = pathIn+files[i] 13 | print(filename) 14 | img=cv2.imread(filename) 15 | height, width, layers = img.shape 16 | size = (width,height) 17 | 18 | for k in range (time): 19 | frame_array.append(img) 20 | 21 | out = cv2.VideoWriter(pathOut, cv2.VideoWriter_fourcc(*'mp4v'), fps, size) 22 | for i in range(len(frame_array)): 23 | out.write(frame_array[i]) 24 | out.release() 25 | print("TASK COMPLETED") 26 | 27 | #EJECUTAMOS FUNCIÓN. 28 | directory = #RUTA A LA COLECCIÓN DE FRAMES ej:'C:/Users/Antonio/Documents/Mis programas/frames' 29 | pathIn = directory + '/' 30 | pathOut=pathIn + 'video.avi' 31 | fps = 20 32 | time = 5 33 | convertToVideo(pathIn, pathOut, fps, time) 34 | -------------------------------------------------------------------------------- /func_parametrica.py: -------------------------------------------------------------------------------- 1 | import matplotlib as mpl 2 | from mpl_toolkits.mplot3d import Axes3D 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | mpl.rcParams['legend.fontsize'] = 10 7 | 8 | fig = plt.figure() 9 | ax = fig.gca(projection='3d') 10 | theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) 11 | z = np.linspace(-2, 2, 100) 12 | r = z**2 + 1 13 | x = r * np.sin(theta) 14 | y = r * np.cos(theta) 15 | ax.plot(x, y, z, label='parametric curve') 16 | ax.legend() 17 | 18 | plt.show() 19 | -------------------------------------------------------------------------------- /funci.py: -------------------------------------------------------------------------------- 1 | import time 2 | #CREAMOS DECORADOR 3 | def decorador(funci): 4 | def div_text(*args, **kwargs): 5 | t1=time.time() 6 | print("Efectuando división") 7 | resultado=funci(*args, **kwargs) 8 | t2=time.time() 9 | print('La función tardó {0} segundos en ejecutarse'.format(t2-t1)) 10 | return resultado 11 | return div_text 12 | 13 | #APLICAMOS DECORADOR A UNA FUNCIÓN CON ARGUMENTOS 14 | @decorador 15 | def division(num, num2): 16 | return num/num2 17 | 18 | #VISUALIZAMOS RESULTADO 19 | resultado=division(12, 7) 20 | print(resultado) 21 | -------------------------------------------------------------------------------- /game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | 4 | SIZE = WIDTH, HEIGHT = 600, 400 5 | BACKGROUND_COLOR = pygame.Color('white') 6 | FPS = 10 7 | 8 | class MySprite(pygame.sprite.Sprite): 9 | def __init__(self): 10 | super(MySprite, self).__init__() 11 | 12 | self.images = [] 13 | self.images.append(pygame.image.load('images/walk1.png')) 14 | self.images.append(pygame.image.load('images/walk2.png')) 15 | self.images.append(pygame.image.load('images/walk3.png')) 16 | self.images.append(pygame.image.load('images/walk4.png')) 17 | self.images.append(pygame.image.load('images/walk5.png')) 18 | self.images.append(pygame.image.load('images/walk6.png')) 19 | self.images.append(pygame.image.load('images/walk7.png')) 20 | self.images.append(pygame.image.load('images/walk8.png')) 21 | self.images.append(pygame.image.load('images/walk9.png')) 22 | self.images.append(pygame.image.load('images/walk10.png')) 23 | 24 | self.index = 0 25 | 26 | self.image = self.images[self.index] 27 | 28 | self.rect = pygame.Rect(5, 5, 150, 198) 29 | 30 | def update(self): 31 | self.index += 1 32 | 33 | if self.index >= len(self.images): 34 | self.index = 0 35 | 36 | self.image = self.images[self.index] 37 | 38 | def main(): 39 | pygame.init() 40 | screen = pygame.display.set_mode(SIZE) 41 | my_sprite = MySprite() 42 | my_group = pygame.sprite.Group(my_sprite) 43 | clock = pygame.time.Clock() 44 | 45 | while True: 46 | for event in pygame.event.get(): 47 | if event.type == pygame.QUIT: 48 | pygame.quit() 49 | quit() 50 | 51 | my_group.update() 52 | screen.fill(BACKGROUND_COLOR) 53 | my_group.draw(screen) 54 | pygame.display.update() 55 | clock.tick(10) 56 | 57 | if __name__ == '__main__': 58 | main() 59 | -------------------------------------------------------------------------------- /gbm_plot.py: -------------------------------------------------------------------------------- 1 | # Python code for the plot 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | mu = 1 6 | n = 50 7 | dt = 0.1 8 | x0 = 100 9 | np.random.seed(1) 10 | 11 | sigma = np.arange(0.8, 2, 0.2) 12 | 13 | x = np.exp( 14 | (mu - sigma ** 2 / 2) * dt 15 | + sigma * np.random.normal(0, np.sqrt(dt), size=(len(sigma), n)).T 16 | ) 17 | x = np.vstack([np.ones(len(sigma)), x]) 18 | x = x0 * x.cumprod(axis=0) 19 | 20 | plt.plot(x) 21 | plt.legend(np.round(sigma, 2)) 22 | plt.xlabel("$t$") 23 | plt.ylabel("$x$") 24 | plt.title( 25 | "Realizations of Geometric Brownian Motion with different variances\n $\mu=1$" 26 | ) 27 | plt.show() 28 | -------------------------------------------------------------------------------- /gbm_simulator.py: -------------------------------------------------------------------------------- 1 | from random import gauss, seed 2 | from math import sqrt, exp 3 | from VALID import OKI 4 | 5 | def create_GBM(s0, mu, sigma): 6 | st = s0 7 | def generate_value(): 8 | nonlocal st 9 | 10 | st *= exp((mu - 0.5 * sigma ** 2) * (1. / 365.) + sigma * sqrt(1./365.) * gauss(mu=0, sigma=1)) 11 | return st 12 | 13 | return generate_value 14 | 15 | if __name__ == "__main__": 16 | seed(1234) 17 | #INPUTS 18 | initial = OKI(input("Initial price: ")) 19 | target = OKI(input("Target: ")) 20 | rang = OKI(input("Range: ")) 21 | 22 | gbm = create_GBM(initial, 0.1, 0.05)#100 23 | 24 | for _ in range(rang):#1000 25 | st = gbm() 26 | print(st) 27 | if st >= target:#130. 28 | print("Target reached, take profit.") 29 | break 30 | else: 31 | print("Did not reach target price.") 32 | 33 | print(st) 34 | -------------------------------------------------------------------------------- /get_folder_size.py: -------------------------------------------------------------------------------- 1 | import os 2 | import matplotlib.pyplot as plt 3 | 4 | 5 | #OBTENER TAMAÑO DE CARPETA 6 | def get_directory_size(directory): 7 | total = 0 8 | try: 9 | for entry in os.scandir(directory): 10 | if entry.is_file(): 11 | total += entry.stat().st_size 12 | elif entry.is_dir(): 13 | total += get_directory_size(entry.path) 14 | except NotADirectoryError: 15 | return os.path.getsize(directory) 16 | except PermissionError: 17 | return 0 18 | return total 19 | 20 | #OBTENER FORMATO 21 | def get_size_format(b, factor=1024, suffix="B"): 22 | 23 | for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: 24 | if b < factor: 25 | return f"{b:.2f}{unit}{suffix}" 26 | b /= factor 27 | 28 | return f"{b:.2f}Y{suffix}" 29 | 30 | size=get_size_format(get_directory_size(b'C:\Users\Antonio\Documents\docs')) 31 | print("SIZE: ",size) 32 | 33 | 34 | #GRAFICA CIRCULAR 35 | def plot_pie(sizes, names): 36 | plt.pie(sizes, labels=names, autopct=lambda pct: f"{pct:.2f}%") 37 | plt.title("Different Sub-directory sizes in bytes") 38 | plt.show() 39 | 40 | if __name__ == "__main__": 41 | import sys 42 | folder_path = b'C:\Users\Antonio\Documents\docs' 43 | 44 | directory_sizes = [] 45 | names = [] 46 | for directory in os.listdir(folder_path): 47 | directory = os.path.join(folder_path, directory) 48 | directory_size = get_directory_size(directory) 49 | if directory_size == 0: 50 | continue 51 | directory_sizes.append(directory_size) 52 | names.append(str(os.path.basename(directory)) + ": " + str(get_size_format(directory_size))) 53 | 54 | print("[+] Total directory size:", get_size_format(sum(directory_sizes))) 55 | plot_pie(directory_sizes, names) 56 | -------------------------------------------------------------------------------- /get_foldersize.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def get_directory_size(directory): 4 | total = 0 5 | try: 6 | for entry in os.scandir(directory): 7 | if entry.is_file(): 8 | total += entry.stat().st_size 9 | elif entry.is_dir(): 10 | total += get_directory_size(entry.path) 11 | except NotADirectoryError: 12 | #SI LA RUTA ES A UN ARCHIVO 13 | return os.path.getsize(directory) 14 | except PermissionError: 15 | return 0 16 | print (total) 17 | return total 18 | 19 | def get_size_format(b, factor=1024, suffix="B"): 20 | 21 | for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: 22 | if b < factor: 23 | return f"{b:.2f}{unit}{suffix}" 24 | b /= factor 25 | 26 | return f"{b:.2f}Y{suffix}" 27 | 28 | size=get_size_format(get_directory_size(drectory)) 29 | print("SIZE: ",size) 30 | -------------------------------------------------------------------------------- /get_worldbank_info.py: -------------------------------------------------------------------------------- 1 | 2 | from pandas_datareader import wb 3 | 4 | matches = wb.search('total.*population') 5 | print(matches[["id","name"]]) 6 | -------------------------------------------------------------------------------- /getting_indian_cities.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | import pandas as pd 4 | from prettytable import PrettyTable 5 | 6 | url = "https://en.wikipedia.org/wiki/List_of_cities_in_India_by_population" 7 | 8 | page = requests.get(url) 9 | html_content = page.content 10 | soup = BeautifulSoup(html_content, "html.parser") 11 | table_soup = soup.find_all("table") 12 | header_tag = soup.find_all("th") 13 | head = [header.text.strip() for header in header_tag] 14 | #print(head) 15 | row = [] 16 | table = soup.find("table") 17 | data_rows = table.find_all("tr") 18 | for rows in data_rows: 19 | value = rows.find_all("td") 20 | value2 = [dp.text.strip() for dp in value] 21 | #print(value2) 22 | if len(value2) == 0: 23 | continue 24 | 25 | row.append(value2) 26 | x = PrettyTable() 27 | x.field_names = ['Rank','City','Population(2011)', 28 | 'Population(2001)','State or union territory'] 29 | x.add_rows(row) 30 | print(x) 31 | #print(row) 32 | 33 | data = pd.DataFrame(row) 34 | data.columns = ['Rank','City','Popukation(2011)', 35 | 'Population(2001)','State or union territory'] 36 | data.to_csv("indian_population.csv", index=0) 37 | -------------------------------------------------------------------------------- /grabadora_sonido.py: -------------------------------------------------------------------------------- 1 | #EJEMPLO DE GRABADORA DE SONIDO CON "pyaudio". 2 | #IMPORTAMOS LIBRERIAS NECESARIAS 3 | import pyaudio 4 | import wave 5 | 6 | #DEFINIMOS PARAMETROS 7 | FORMAT=pyaudio.paInt16 8 | CHANNELS=2 9 | RATE=44100 10 | CHUNK=1024 11 | duracion=10 12 | archivo="grabacion.wav" 13 | 14 | #INICIAMOS "pyaudio" 15 | audio=pyaudio.PyAudio() 16 | 17 | #INICIAMOS GRABACIÓN 18 | stream=audio.open(format=FORMAT,channels=CHANNELS, 19 | rate=RATE, input=True, 20 | frames_per_buffer=CHUNK) 21 | 22 | print("grabando...") 23 | frames=[] 24 | 25 | for i in range(0, int(RATE/CHUNK*duracion)): 26 | data=stream.read(CHUNK) 27 | frames.append(data) 28 | print("grabación terminada") 29 | 30 | #DETENEMOS GRABACIÓN 31 | stream.stop_stream() 32 | stream.close() 33 | audio.terminate() 34 | 35 | #CREAMOS/GUARDAMOS EL ARCHIVO DE AUDIO 36 | waveFile = wave.open(archivo, 'wb') 37 | waveFile.setnchannels(CHANNELS) 38 | waveFile.setsampwidth(audio.get_sample_size(FORMAT)) 39 | waveFile.setframerate(RATE) 40 | waveFile.writeframes(b''.join(frames)) 41 | waveFile.close() 42 | 43 | 44 | -------------------------------------------------------------------------------- /grafica_barras.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | fig = plt.figure("CALIFICACIONES") 5 | grupo1 = fig.add_subplot(211) 6 | grupo2 = fig.add_subplot(212) 7 | 8 | alums1 = ["Jorge", "Ana", "Juan", "Diana", "Pedro"] 9 | calif1 = np.array([7.8, 5.9, 8.0, 10, 6.6]) 10 | 11 | alums2 = ["Pablo", "David", "Jose", "Carlos", "Sofia"] 12 | calif2 = np.array([9.0, 5.0, 8.3, 7.7, 9.5]) 13 | 14 | grupo1.bar(alums1, calif1, align="center") 15 | grupo1.set_xticks(alums1) 16 | grupo1.set_xticklabels(alums1) 17 | #grupo1.set_yticklabels(calif1) 18 | grupo1.set_ylabel("CALIFICACIONES GRUPO 1") 19 | 20 | grupo2.bar(alums2, calif2, color="g", align="center") 21 | grupo2.set_xticks(alums2) 22 | grupo2.set_xticklabels(alums2) 23 | #grupo2.set_yticklabels(calif2) 24 | grupo2.set_ylabel("CALIFICACIONES GRUPO 2") 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /grafica_circular.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS "matplotlib". 2 | import matplotlib.pyplot as plt 3 | 4 | #DEFINIMOS ETIQUETAS 5 | etiquetas = ['A', 'B', 'C', 'D', 'E', 'F'] #labels 6 | 7 | #PORCENTAJE DE CADA PORCIÓN. 8 | porcentas = [14,3,8,6,9,7] 9 | 10 | #DEFIMIMOS COLORES 11 | colores = ['#1abc9c', '#f1c40f', '#8e44ad', '#e74c3c', '#34495e', '#3498db'] #LabelColor 12 | 13 | #DIBUJAMOS GRÁFICA. 14 | plt.pie(porcentas, labels = etiquetas, colors=colores, 15 | startangle=90, explode = (0.1, 0.1, 0.1, 0.1, 0.1, 0.1), 16 | radius = 1.2, autopct = '%1.2f%%') 17 | 18 | #TITULO 19 | plt.title('Gráfica Circular') 20 | 21 | #MOSTRAMOS GRÁFICA. 22 | plt.show() 23 | -------------------------------------------------------------------------------- /grafica_superficie.py: -------------------------------------------------------------------------------- 1 | #GRAFICA SUPERFICIE 3D 2 | from mpl_toolkits.mplot3d import Axes3D 3 | import matplotlib.pyplot as plt 4 | from matplotlib import cm 5 | from matplotlib.ticker import LinearLocator, FormatStrFormatter 6 | import numpy as np 7 | 8 | 9 | fig = plt.figure() 10 | ax = fig.gca(projection='3d') 11 | 12 | # DATOS 13 | X = np.arange(-5, 5, 0.25) 14 | Y = np.arange(-5, 5, 0.25) 15 | X, Y = np.meshgrid(X, Y) 16 | R = np.sqrt(X**2 + Y**2) 17 | Z = np.sin(R) 18 | 19 | # EPRESENTAR SUPERFICIE 20 | surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, 21 | linewidth=0, antialiased=False) 22 | 23 | ax.set_zlim(-1.01, 1.01) 24 | ax.zaxis.set_major_locator(LinearLocator(10)) 25 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) 26 | 27 | # AÑADIR COLORES 28 | fig.colorbar(surf, shrink=0.5, aspect=5) 29 | 30 | plt.show() 31 | -------------------------------------------------------------------------------- /handwritting_digits_recognizer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | import matplotlib.pyplot as plt 4 | import tensorflow as tf 5 | tf.__version__ 6 | 7 | mnist = tf.keras.datasets.mnist 8 | 9 | (x_train, y_train), (x_test, y_test) = mnist.load_data() 10 | 11 | #normalize 12 | x_train = tf.keras.utils.normalize(x_train, axis=1) 13 | x_test = tf.keras.utils.normalize(x_test, axis=1) 14 | 15 | print(x_train.shape) 16 | 17 | plt.imshow(x_train[0], cmap=plt.cm.binary) 18 | plt.show() 19 | print(x_train[0]) 20 | 21 | #define model 22 | model = tf.keras.models.Sequential() 23 | model.add(tf.keras.layers.Flatten()) 24 | model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) 25 | model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) 26 | model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax)) 27 | 28 | model.compile(optimizer='adam', 29 | loss='sparse_categorical_crossentropy', 30 | metrics=['accuracy']) 31 | 32 | #training the model 33 | model.fit(x_train, y_train, epochs=5)#3 34 | 35 | #evaluar modelo 36 | val_loss, val_acc = model.evaluate(x_test, y_test) 37 | 38 | #save the model 39 | model.save('my_model') 40 | 41 | #use model 42 | new_model = tf.keras.models.load_model('my_model') 43 | predictions = new_model.predict([x_test]) 44 | print(predictions) 45 | 46 | #prediction 47 | import numpy as np 48 | 49 | np.argmax(predictions[200]) 50 | 51 | 52 | #check 53 | plt.imshow(x_test[200]) 54 | plt.show() 55 | 56 | #IN JUPYTER NOTEBOOK 57 | #for i in range(120): 58 | #predicted_number = np.argmax(predictions[i]) 59 | #plt.imshow(x_test[i]) 60 | #plt.title("This is a {}".format(predicted_number)) 61 | #plt.show() 62 | -------------------------------------------------------------------------------- /hash_maker_CLI.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import hashlib 4 | from colorama import Fore, Back, init 5 | 6 | class HASH: 7 | def generateHash(h): 8 | digest=h.hexdigest() 9 | return digest 10 | 11 | init() 12 | algoritmos = ["md5","sha1","sha224","sha256","sha384","sha512"] 13 | 14 | print(Back.BLUE+"-"*56+"HASH CLI"+"-"*56+Back.RESET) 15 | while True: 16 | print(Fore.GREEN+"Elija número de opción deseada:") 17 | print("1-Genererar hash usando algoritmo MD5") 18 | print("2-Genererar hash usando algoritmo SHA1") 19 | print("3-Genererar hash usando algoritmo SHA224") 20 | print("4-Genererar hash usando algoritmo SHA256") 21 | print("5-Genererar hash usando algoritmo SHA384") 22 | print("6-Genererar hash usando algoritmo SHA512") 23 | print("7-Finalizar programa.") 24 | 25 | try: 26 | nAlgoritmo = int(input("Introducir opción: ")) 27 | 28 | if nAlgoritmo > 0 and nAlgoritmo < 8: 29 | 30 | if nAlgoritmo != 7: 31 | datos=input("Introducir información a hashear: ") 32 | algoritmo = algoritmos[nAlgoritmo-1] 33 | bdatos = bytes(datos, 'utf-8') 34 | h = hashlib.new(algoritmo,bdatos) 35 | hash1=HASH.generateHash(h) 36 | print(Fore.BLUE+f"\nALGORITMO: {algoritmo.upper()}"+Fore.RESET) 37 | print(Fore.YELLOW+hash1+Fore.RESET+"\n") 38 | else: 39 | break 40 | else: 41 | print("\n"+Back.RED+Fore.BLACK+"VALOR FUERA DE RANGO."+Fore.RESET+Back.RESET+"\n") 42 | 43 | except Exception as e: 44 | print("\n"+Back.RED+Fore.BLACK+str(e)+Fore.RESET+Back.RESET+"\n") 45 | 46 | print("PROGRAM FINISHED") 47 | -------------------------------------------------------------------------------- /hexa_bin.py: -------------------------------------------------------------------------------- 1 | #CONVERSOR HEXADECIMAL-BINARIO (MÉTODO LARGO) 2 | import subprocess 3 | 4 | def ns(c): 5 | while c!=("s") and c!=("n"): 6 | print(chr(7));c=input("Escribe solo \'n\' o \'s\' según su opción: ") 7 | return(c) 8 | 9 | 10 | lista_hex=['0','1','2','3','4','5','6','7' 11 | ,'8','9','A','B','C','D','E','F'] 12 | 13 | while True: 14 | print("****************TRADUCTOR HEXADECIMAL-BINARIO****************") 15 | print("") 16 | hexa=input("Introduce hexadecimal: ") 17 | 18 | binario=[] 19 | 20 | for i in hexa: 21 | if i in lista_hex: 22 | indice=lista_hex.index(i) 23 | num_binar=(bin(indice)).lstrip("0b") 24 | longi=(abs(len(num_binar)-4)) 25 | n='0'*longi 26 | n_cadena=n+num_binar 27 | binario.append(n_cadena) 28 | else: 29 | print("El carater",i,"no es hexadecimal, por lo que ha sido ignorado.") 30 | 31 | binario_final=str(("").join(binario)) 32 | 33 | print("") 34 | print("TRADUCCIÓN BINARIA:",binario_final) 35 | print("") 36 | 37 | conti=ns(input("¿Desea continuar?: ")) 38 | if conti=="n": 39 | break 40 | subprocess.call(["cmd.exe","/C","cls"]) 41 | 42 | -------------------------------------------------------------------------------- /hexa_to_binar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | def ns(c): 5 | while c!=("s") and c!=("n"): 6 | print(chr(7));c=input("Escribe solo \'n\' o \'s\' según su opción: ") 7 | return(c) 8 | 9 | #CORRESPONDENCIA HEXADECIMAL-BINARIO 10 | dic_hex={'0':'0000','1':'0001','2':'0010','3':'0011','4':'0100','5':'0101', 11 | '6':'0110','7':'0111','8':'1000','9':'1001','A':'1010','B':'1011', 12 | 'C':'1100','D':'1101','E':'1110','F':'1111'} 13 | 14 | while True: 15 | print("****************CONVERSOR HEXADECIMAL-BINARIO****************\n") 16 | hexa=input("Introduce hexadecimal: ") 17 | 18 | binario="" 19 | 20 | for i in hexa: 21 | if i in dic_hex: 22 | binario=binario+dic_hex[i] 23 | else: 24 | print("El carater",i,"no es hexadecimal, por lo que ha sido ignorado.") 25 | 26 | 27 | print("\nTRADUCCIÓN BINARIA:",binario) 28 | 29 | conti=ns(input("\n¿Desea continuar?(n/s): ")) 30 | if conti=="n": 31 | break 32 | 33 | -------------------------------------------------------------------------------- /hexabin.py: -------------------------------------------------------------------------------- 1 | #CONVERSOR HEXADECIMAL-BINARIO (MÉTODO CORTO). 2 | import subprocess 3 | 4 | def ns(c): 5 | while c!=("s") and c!=("n"): 6 | print(chr(7));c=input("Escribe solo \'n\' o \'s\' según su opción: ") 7 | return(c) 8 | 9 | 10 | dic_hex={'0':'0000','1':'0001','2':'0010','3':'0011','4':'0100','5':'0101', 11 | '6':'0110','7':'0111','8':'1000','9':'1001','A':'1010','B':'1011', 12 | 'C':'1100','D':'1101','E':'1110','F':'1111'} 13 | 14 | while True: 15 | print("****************TRADUCTOR HEXADECIMAL-BINARIO****************") 16 | print("") 17 | hexa=input("Introduce hexadecimal: ") 18 | 19 | binario=[] 20 | 21 | for i in hexa: 22 | if i in dic_hex: 23 | binario.append(dic_hex[i]) 24 | else: 25 | print("El carater",i,"no es hexadecimal, por lo que ha sido ignorado.") 26 | 27 | binario_final=("").join(binario) 28 | 29 | print("") 30 | print("TRADUCCIÓN BINARIA:",binario_final) 31 | print("") 32 | 33 | conti=ns(input("¿Desea continuar?: ")) 34 | if conti=="n": 35 | break 36 | subprocess.call(["cmd.exe","/C","cls"]) 37 | 38 | -------------------------------------------------------------------------------- /histogram.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import cv2 3 | import numpy as np 4 | 5 | image = cv2.imread("lenna.jpg",cv2.IMREAD_GRAYSCALE) 6 | plt.figure(figsize=(10,10)) 7 | plt.imshow(image,cmap="gray") 8 | plt.show() 9 | 10 | hist = cv2.calcHist([image],[0], None, [256], [0,256]) 11 | intensity_values = np.array([x for x in range(hist.shape[0])]) 12 | plt.bar(intensity_values, hist[:,0], width=5) 13 | plt.title("Bar histogram·") 14 | plt.show() 15 | 16 | PMF = hist / (image.shape[0] * image.shape[1]) 17 | plt.plot(intensity_values,hist) 18 | plt.title("Histogram") 19 | plt.grid() 20 | plt.show() 21 | 22 | #histograma para cada canal 23 | image = cv2.imread("lenna.jpg",cv2.COLOR_BGR2RGB) 24 | color = ('blue', 'green', 'red') 25 | for i, col in enumerate(color): 26 | histr = cv2.calcHist([image],[i], None, [256], [0,256]) 27 | plt.plot(intensity_values,histr,color = col,label=col+" channel") 28 | plt.xlim([0,256]) 29 | plt.legend() 30 | plt.title("Histogram Channels") 31 | plt.grid() 32 | plt.show() 33 | -------------------------------------------------------------------------------- /hora_salida.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import time 3 | 4 | def main(): 5 | hora_actual = time.strftime('%H:%M:%S', time.localtime()) 6 | print("La hora actual es: ",hora_actual) 7 | if hora_actual == '19:00:00': 8 | print("Es hora de salir.") 9 | else: 10 | t1 = datetime.strptime(hora_actual,"%H:%M:%S") 11 | t2 = datetime.strptime('19:00:00',"%H:%M:%S") 12 | tiem_res = str(t2 - t1).split(":") 13 | print("Quedan {} horas, {} minutos y {} segundos, para la salida.".format(tiem_res[0],tiem_res[1],tiem_res[2])) 14 | 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/image.jpg -------------------------------------------------------------------------------- /image_drawing.py: -------------------------------------------------------------------------------- 1 | from PIL import Image, ImageDraw, ImageFont 2 | 3 | #CARGAR IMAGEN DE BASE 4 | base = Image.open('earth.png').convert('RGBA') 5 | 6 | # CREAR CAPA PARA SUPERPONER 7 | txt = Image.new('RGBA', base.size, (255,255,255,0)) 8 | 9 | #DEFINIR FUENTE 10 | fnt = ImageFont.truetype('arial.ttf', 40) 11 | #CONTESTO DE DIBUJADO 12 | d = ImageDraw.Draw(txt) 13 | 14 | # DIBUJAR TEXTO CON TRANSPARENCIA 128 15 | d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128)) 16 | # DIBUJAR TEXTO SIN TRANSPARENCIA 17 | d.text((10,60), "World", font=fnt, fill=(255,255,255,255)) 18 | 19 | #SUPERPONER 20 | out = Image.alpha_composite(base, txt) 21 | 22 | #MOSTRAR 23 | out.show() 24 | 25 | #GUARDAR 26 | out.save("new.png") 27 | -------------------------------------------------------------------------------- /image_extractor.py: -------------------------------------------------------------------------------- 1 | import fitz # PyMuPDF 2 | import io 3 | import os 4 | from PIL import Image 5 | 6 | #ESTABLECER DIRECTORIO DE TRABAJO. 7 | #os.chdir(r'C:\Users\Antonio\Documents\Mis programas\pdf_images') 8 | 9 | #NOMBRE ARCHIVO PDF. 10 | file = "1710.05006.pdf" 11 | #ABRIR PDF. 12 | pdf_file = fitz.open(file) 13 | #RECORRER PÁGINAS DEL PDF. 14 | for page_index in range(len(pdf_file)): 15 | #LEER PÁGINA 16 | page = pdf_file[page_index] 17 | image_list = page.getImageList() 18 | #MOSTRAR NÚMERO DE IMÁGENES ENCONTRADAS 19 | if image_list: 20 | print(f"[+] Se encontraron {len(image_list)} imágenes en la página {page_index}") 21 | else: 22 | print("[!] No se encontraron imágenes en la página", page_index) 23 | for image_index, img in enumerate(page.getImageList(), start=1): 24 | #REFERENCIAS EXTERNAS DE LA IMAGEN. 25 | xref = img[0] 26 | #BYTES DE LA IMAGEN 27 | base_image = pdf_file.extractImage(xref) 28 | image_bytes = base_image["image"] 29 | #EXTENSION DE LA IMAGEN. 30 | image_ext = base_image["ext"] 31 | #ABRIR CON PIL. 32 | image = Image.open(io.BytesIO(image_bytes)) 33 | #ALMACENAR ARCHIVO DE IMÁGEN. 34 | image.save(open(f"image{page_index+1}_{image_index}.{image_ext}", "wb")) 35 | -------------------------------------------------------------------------------- /image_pixelator.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | from PIL import Image 3 | 4 | # CREATE A PIXELATED VERSIÓN OF A IMAGE. 5 | 6 | # Open image file 7 | img = Image.open("image.png") 8 | 9 | # Resize smoothly down to 16x16 pixels 10 | imgSmall = img.resize((16,16),resample=Image.BILINEAR) 11 | 12 | # Scale back up using NEAREST to original size 13 | result = imgSmall.resize(img.size,Image.NEAREST) 14 | 15 | # Save 16 | result.save('result.png') 17 | -------------------------------------------------------------------------------- /inserta_grafica.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS LIBRERIAS NECESARIAS. 2 | import tkinter 3 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk 4 | from matplotlib.figure import Figure 5 | import numpy as np 6 | 7 | #------------------------------CREAR VENTANA--------------------------------- 8 | root = tkinter.Tk() 9 | root.wm_title("Grafica insertada en Tkinter") 10 | 11 | 12 | #------------------------------CREAR GRAFICA--------------------------------- 13 | fig = Figure(figsize=(5, 4), dpi=100) 14 | t = np.arange(0, 3, .01) 15 | fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))#AÑADIR "subbplot" 16 | 17 | canvas = FigureCanvasTkAgg(fig, master=root) # CREAR AREA DE DIBUJO DE TKINTER. 18 | canvas.draw() 19 | canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) 20 | 21 | #-----------------------AÑADIR BARRA DE HERRAMIENTAS-------------------------- 22 | toolbar = NavigationToolbar2Tk(canvas, root)# barra de iconos 23 | toolbar.update() 24 | canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) 25 | 26 | #-----------------------------BOTÓN "cerrar"---------------------------------- 27 | def cerrar(): 28 | root.quit() 29 | root.destroy() 30 | 31 | button = tkinter.Button(master=root, text="cerrar", command=cerrar) 32 | button.pack(side=tkinter.BOTTOM) 33 | 34 | tkinter.mainloop() 35 | -------------------------------------------------------------------------------- /insertion_sort.py: -------------------------------------------------------------------------------- 1 | #EXAMPLE OF DATA SORTING USING INSERTION SORT ALGORITHM. 2 | 3 | def insertion_sort(data): 4 | l = len(data) 5 | if l > 1: 6 | for i in range(1,l): 7 | for j in range(i, 0, -1): 8 | if data[j] < data[j-1]: 9 | data[j], data[j-1] = data[j-1], data[j] 10 | print(data) 11 | else: 12 | print(data) 13 | break 14 | return data 15 | else: 16 | return data 17 | 18 | data = [56,234,123,6,23,1231,1] 19 | i_sort = insertion_sort(data) 20 | print("DATA SORTED: {}".format(i_sort)) 21 | -------------------------------------------------------------------------------- /intercala_silencios.py: -------------------------------------------------------------------------------- 1 | from pydub import AudioSegment 2 | from pydub.playback import play 3 | 4 | # Cargar archivos de sonido 5 | sound1 = AudioSegment.from_file("new_audio.wav", format="wav") 6 | sound2 = AudioSegment.from_file("new_audio.wav", format="wav") 7 | sound3 = AudioSegment.from_file("new_audio.wav", format="wav") 8 | 9 | # Crear un segmento de silencio de 2 segundos 10 | silence = AudioSegment.silent(duration=2000) # 2000 ms = 2 segundos 11 | 12 | # Concatenar sonidos intercalando silencios 13 | combined = sound1 + silence + sound2 + silence + sound3 + silence 14 | 15 | # Exportar el resultado a un nuevo archivo 16 | combined.export("landline_phone_loop.wav", format="wav") 17 | 18 | # (Opcional) Reproducir el resultado 19 | #play(combined) 20 | -------------------------------------------------------------------------------- /koch_snowflake.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | import time 3 | 4 | # Set up Constants 5 | ANGLES = [60, -120, 60, 0] 6 | SIZE_OF_SNOWFLAKE = 300 7 | 8 | def get_input_depth(): 9 | message = "Please provide the depht (0 or positive integer): " 10 | value_as_string = input(message) 11 | while not value_as_string.isnumeric(): 12 | print("The input must be an integer!") 13 | value_as_string = input(message) 14 | return int(value_as_string) 15 | 16 | def setup_screen(title, background='white', screen_size_x=640,screen_size_y=320, tracer_size=800): 17 | print('Set up Screen') 18 | turtle.title(title) 19 | turtle.setup(screen_size_x, screen_size_y) 20 | turtle.hideturtle() 21 | turtle.penup() 22 | turtle.backward(240) 23 | # Batch drawing to the screen for faster rendering 24 | turtle.tracer(tracer_size) 25 | turtle.bgcolor(background) # Set the background colour of the screen 26 | 27 | def draw_koch(size, depth): 28 | if depth > 0: 29 | for angle in ANGLES: 30 | draw_koch(size / 3, depth - 1) 31 | turtle.left(angle) 32 | else: 33 | turtle.forward(size) 34 | 35 | depth = get_input_depth() 36 | 37 | setup_screen('Koch Snowflake (depth ' + str(depth) + ')', 38 | background='black', screen_size_x=420, 39 | screen_size_y=420) 40 | 41 | turtle.color('sky blue') 42 | 43 | turtle.penup() 44 | turtle.setposition(-180,0) 45 | turtle.left(30) 46 | turtle.pendown() 47 | 48 | # Draw three sides of snowflake 49 | for _ in range(3): 50 | draw_koch(SIZE_OF_SNOWFLAKE, depth) 51 | turtle.right(120) 52 | 53 | # Ensure that all the drawing is rendered 54 | turtle.update() 55 | print('Done') 56 | turtle.done() 57 | -------------------------------------------------------------------------------- /lena.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/lena.jpg -------------------------------------------------------------------------------- /lenna.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonioam82/ejercicios-python/6c81fec6a3f60cb66483e5404730537aca8c5d00/lenna.jpg -------------------------------------------------------------------------------- /letra_dni.py: -------------------------------------------------------------------------------- 1 | from VALID import ns,OKI 2 | import subprocess 3 | 4 | termi=["T","R","W","A","G","M","Y","F","P","D","X", 5 | "B","N","J","Z","S","Q","V","H","L","C","K","E"] 6 | 7 | while True: 8 | num=OKI(input("Introduzca número: ")) 9 | indice=num%23 10 | print("Letra: ",termi[indice]) 11 | conti=ns(input("¿Desea continuar?: ")) 12 | if conti=="n": 13 | break 14 | subprocess.call(["cmd.exe","/C","cls"]) 15 | 16 | 17 | -------------------------------------------------------------------------------- /librosa_display_waveplot.py: -------------------------------------------------------------------------------- 1 | # Plot a monophonic waveform 2 | import librosa.display 3 | import matplotlib.pyplot as plt 4 | y, sr = librosa.load(librosa.util.example_audio_file(), duration=10) 5 | plt.figure() 6 | plt.subplot(3, 1, 1) 7 | librosa.display.waveplot(y, sr=sr) 8 | plt.title('Monophonic') 9 | 10 | # Or a stereo waveform 11 | 12 | y, sr = librosa.load(librosa.util.example_audio_file(), 13 | mono=False, duration=10) 14 | plt.subplot(3, 1, 2) 15 | librosa.display.waveplot(y, sr=sr) 16 | plt.title('Stereo') 17 | 18 | # Or harmonic and percussive components with transparency 19 | 20 | y, sr = librosa.load(librosa.util.example_audio_file(), duration=10) 21 | y_harm, y_perc = librosa.effects.hpss(y) 22 | plt.subplot(3, 1, 3) 23 | librosa.display.waveplot(y_harm, sr=sr, alpha=0.25) 24 | librosa.display.waveplot(y_perc, sr=sr, color='r', alpha=0.5) 25 | plt.title('Harmonic + Percussive') 26 | plt.tight_layout() 27 | plt.show() 28 | -------------------------------------------------------------------------------- /live_graph.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as animation 3 | from matplotlib import style 4 | 5 | style.use('fivethirtyeight') 6 | 7 | fig = plt.figure() 8 | ax1 = fig.add_subplot(111) 9 | 10 | def animate(i): 11 | graph_data = open('ejemplo.txt','r').read() 12 | lines = graph_data.split('\n') 13 | xs = [] 14 | ys = [] 15 | for line in lines: 16 | if len(line) > 1: 17 | x, y = line.split(',') 18 | xs.append(x) 19 | ys.append(y) 20 | 21 | 22 | ax1.clear() 23 | ax1.plot(xs, ys) 24 | 25 | 26 | ani = animation.FuncAnimation(fig, animate, interval=1000) 27 | plt.show() 28 | 29 | -------------------------------------------------------------------------------- /logistic_regression.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | from sklearn.linear_model import LogisticRegression 4 | 5 | #sample dataset 6 | credit_scores = np.random.randint(300, 850, size=1000) 7 | loan_approved = np.random.binomial(1, p=1 / (1 + np.exp(-0.02 * (credit_scores - 700))), size=1000) 8 | 9 | data = pd.DataFrame({ 10 | 'credit_score': credit_scores, 11 | 'loan_approved': loan_approved 12 | }) 13 | 14 | #print(data.head(20)) 15 | 16 | model = LogisticRegression() 17 | model.fit(data[['credit_score']], data['loan_approved']) 18 | 19 | try: 20 | new_customer_credit_score = input("Enter your credit score: ") 21 | new_customer_data = pd.DataFrame({'credit_score': [new_customer_credit_score]}) 22 | predicted_class = model.predict(new_customer_data[['credit_score']])[0] 23 | 24 | # print the predicted class 25 | if predicted_class == 0: 26 | print(f'A loan is not approved for a customer with a credit score of {new_customer_credit_score}.') 27 | else: 28 | print(f'A loan is approved for a customer with a credit score of {new_customer_credit_score}.') 29 | 30 | except Exception as e: 31 | print('ERROR: ' + str(e)) 32 | -------------------------------------------------------------------------------- /lorenzAnimation_creator.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | from matplotlib import animation 3 | from mpl_toolkits.mplot3d import Axes3D 4 | import numpy as np 5 | from scipy.integrate import odeint 6 | 7 | fig = plt.figure() 8 | 9 | ax = fig.add_subplot(111,projection='3d') 10 | 11 | ax.azim = 45 12 | ax.elev = 45 13 | 14 | ax.set_xlabel('Eje X') 15 | ax.set_ylabel('Eje Y') 16 | ax.set_zlabel('Eje Z') 17 | 18 | ax.set_xticklabels("") 19 | ax.set_yticklabels("") 20 | ax.set_zticklabels("") 21 | 22 | linea, = ax.plot([],[],[],label = 'Lorenz', lw = 0.5) 23 | ax.legend() 24 | 25 | ax.set_xlim(-20.20) 26 | ax.set_ylim(-30,30) 27 | ax.set_zlim(0,50) 28 | 29 | def integra(ccii,t): 30 | x = ccii[0] 31 | y = ccii[1] 32 | z = ccii[2] 33 | sigma = 10 34 | rho = 28 35 | beta = 8.0/3 36 | dx = sigma*(y-x) 37 | dy = x*(rho-z) 38 | dz = x*y-beta*z 39 | return [dx,dy,dz] 40 | 41 | def anima(i,x0,y0,z0): 42 | t = np.arange(0,(i+1)/10.,0.01) 43 | ccii = [x0,y0,z0] 44 | soluc = odeint(integra,ccii,t) 45 | x = soluc[:,0] 46 | y = soluc[:,1] 47 | z = soluc[:,2] 48 | ax.elev = 45+i/2 49 | ax.azim = 45+i/2 50 | linea.set_data(x,y) 51 | linea.set_3d_properties(z) 52 | return linea 53 | 54 | anim = animation.FuncAnimation(fig,anima,frames=500,fargs=(0,1,1.05), 55 | interval=5) 56 | try: 57 | anim.save('Atractor_de_Lorenz(pybonacci).mp4', fps = 10) 58 | except: 59 | print("Va ser que no") 60 | -------------------------------------------------------------------------------- /merge_sort.py: -------------------------------------------------------------------------------- 1 | 2 | # Función de ordenación 3 | def merge_sort(arr): 4 | if len(arr) > 1: 5 | mid = len(arr) // 2 6 | left_half = arr[:mid] 7 | right_half = arr[mid:] 8 | 9 | merge_sort(left_half) 10 | merge_sort(right_half) 11 | 12 | # Fusionar las dos mitades ordenadas 13 | i = j = k = 0 14 | while i < len(left_half) and j < len(right_half): 15 | if left_half[i] < right_half[j]: 16 | arr[k] = left_half[i] 17 | i += 1 18 | else: 19 | arr[k] = right_half[j] 20 | j += 1 21 | k += 1 22 | 23 | while i < len(left_half): 24 | arr[k] = left_half[i] 25 | i += 1 26 | k += 1 27 | 28 | while j < len(right_half): 29 | arr[k] = right_half[j] 30 | j += 1 31 | k += 1 32 | 33 | return arr 34 | 35 | 36 | # Elementos desordenados 37 | lista_elementos = [23, 6, 33, 1, 9, 4, 55, 82, 11, 3] 38 | 39 | # Elementos ordenados 40 | lista_ordenada = merge_sort(lista_elementos) 41 | print(lista_ordenada) 42 | -------------------------------------------------------------------------------- /minimizer.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | import scipy.optimize as spo 5 | 6 | def f(x): 7 | Y = (x - 1.5)**2 + 0.5 8 | print("X = {}, Y = {}".format(x,Y)) 9 | return Y 10 | 11 | def test_run(): 12 | Xguess = 2.0 13 | min_result = spo.minimize(f, Xguess, method='SLSQP',options={'disp':True}) 14 | print("Minima found at:") 15 | print("X = {}, Y = {}".format(min_result,min_result.fun)) 16 | 17 | Xplot = np.linspace(0.5, 2.5, 21) 18 | Yplot = f(Xplot) 19 | plt.plot(Xplot, Yplot) 20 | plt.plot(min_result.x, min_result.fun, 'ro') 21 | plt.title("Minima of an objective function") 22 | plt.show() 23 | 24 | 25 | if __name__ == "__main__": 26 | test_run() 27 | -------------------------------------------------------------------------------- /minimos_cuadrados.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader.data as wb 2 | import matplotlib.pyplot as plt 3 | import statsmodels.formula.api as smf 4 | import numpy as np 5 | 6 | tickers = ['PCEC', 'GDP'] 7 | data = wb.DataReader(tickers, 'fred', '2010-1-1') 8 | 9 | plt.plot(data.index,data,lw=1.5) 10 | plt.legend(data.columns) 11 | plt.show() 12 | 13 | 14 | plt.scatter(data['PCEC'],data['GDP']) 15 | plt.show() 16 | 17 | mod = smf.ols('PCEC ~ GDP', np.log(data)).fit() 18 | print(mod.summary(), mod.params) 19 | 20 | plt.plot(data.index, data.diff(), lw=1.5) 21 | plt.legend(data.columns) 22 | plt.show() 23 | -------------------------------------------------------------------------------- /mod_voice.py: -------------------------------------------------------------------------------- 1 | import pyaudio 2 | import wave 3 | import sounddevice as sd 4 | import numpy as np 5 | from pynput import keyboard 6 | 7 | def apply_modulation(audio, modulation_frequency, fs): 8 | t = np.linspace(0, len(audio) / fs, len(audio), endpoint=False) 9 | modulation_signal = np.sin(2 * np.pi * modulation_frequency * t) 10 | return audio * (1 + 0.5 * modulation_signal) 11 | 12 | def grabar_audio(): 13 | CHUNK = 1024 14 | FORMAT = pyaudio.paInt16 15 | CHANNELS = 1 16 | RATE = 44100 17 | WAVE_OUTPUT_FILENAME = "grabacion_modulada.wav" 18 | MODULATION_FREQUENCY = 5 19 | 20 | audio = pyaudio.PyAudio() 21 | 22 | stream = audio.open(format=FORMAT, channels=CHANNELS, 23 | rate=RATE, input=True, 24 | frames_per_buffer=CHUNK) 25 | 26 | frames = [] 27 | 28 | print("Grabando... Presiona la barra espaciadora para detener la grabación.") 29 | 30 | def on_press(key): 31 | if key == keyboard.Key.space: 32 | return False # Detiene el listener 33 | 34 | listener = keyboard.Listener(on_press=on_press) 35 | listener.start() 36 | 37 | while True: 38 | data = stream.read(CHUNK) 39 | frames.append(data) 40 | 41 | if not listener.running: 42 | break 43 | 44 | print("Grabación detenida.") 45 | 46 | stream.stop_stream() 47 | stream.close() 48 | audio.terminate() 49 | 50 | audio_np = np.frombuffer(b''.join(frames), dtype=np.int16) 51 | 52 | modulated_audio = apply_modulation(audio_np, MODULATION_FREQUENCY, RATE) 53 | 54 | sd.play(modulated_audio, RATE) 55 | sd.wait() # Esperar hasta que la reproducción termine completamente 56 | 57 | '''with wave.open(WAVE_OUTPUT_FILENAME, 'wb') as wf: 58 | wf.setnchannels(CHANNELS) 59 | wf.setsampwidth(audio.get_sample_size(FORMAT)) 60 | wf.setframerate(RATE) 61 | wf.writeframes(modulated_audio.tobytes())''' 62 | 63 | grabar_audio() 64 | -------------------------------------------------------------------------------- /modula2.py: -------------------------------------------------------------------------------- 1 | import sounddevice as sd 2 | from scipy.io.wavfile import write 3 | import numpy as np 4 | 5 | # Configuración de la grabación 6 | duration = 5 # Duración de la grabación en segundos 7 | fs = 44100 # Frecuencia de muestreo (puedes ajustarla si es necesario) 8 | 9 | # Función para grabar audio 10 | def record_audio(duration, fs): 11 | print("Comenzando la grabación...") 12 | recording = sd.rec(int(duration * fs), samplerate=fs, channels=1) 13 | sd.wait() 14 | print("Grabación finalizada.") 15 | return recording 16 | 17 | # Función para aplicar una modulación intensa al audio 18 | def apply_modulation(audio, modulation_frequency, fs): 19 | t = np.linspace(0, len(audio) / fs, len(audio), endpoint=False) 20 | modulation_signal = np.sin(2 * np.pi * modulation_frequency * t) 21 | return audio * (1 + 1.5 * modulation_signal) # Ajusta el factor de modulación según sea necesario 22 | 23 | # Función para reproducir audio 24 | def play_audio(audio, fs): 25 | print("Reproduciendo audio...") 26 | sd.play(audio, fs) 27 | sd.wait() 28 | 29 | # Grabar audio durante la duración especificada 30 | audio_recording = record_audio(duration, fs) 31 | 32 | # Aplicar modulación intensa al audio grabado 33 | modulated_audio = apply_modulation(audio_recording[:, 0], 10, fs) # Frecuencia de modulación de 10 Hz 34 | 35 | 36 | 37 | # Sobremodulación para aumentar la distorsión 38 | modulated_audio = np.tanh(modulated_audio * 5) # Ajusta el factor para controlar la distorsión 39 | 40 | # Reproducir el audio modulado 41 | play_audio(modulated_audio, fs) 42 | 43 | # Guardar la grabación original y la modulada como archivos WAV 44 | write("grabacion_original.wav", fs, audio_recording) 45 | write("grabacion_distorsionada.wav", fs, modulated_audio) 46 | 47 | print("Grabación original guardada como 'grabacion_original.wav'.") 48 | print("Grabación distorsionada guardada como 'grabacion_distorsionada.wav'.") 49 | -------------------------------------------------------------------------------- /modula_am_graf.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | A_m = 5 #amplitud de la moduladora 5 | f_m = 4000 #frecuaencia de la moduladora 6 | A_p = 5 #amplitud de la portadora 7 | f_p = 40000#40000 #frecuencia de la portadora 8 | ka = 3 #indice de modulacion 9 | t = np.linspace(0, 1, 1000) 10 | 11 | moduladora = A_m*np.cos(2*np.pi*f_m*t) 12 | portadora = A_p*np.cos(2*np.pi*f_p*t) 13 | modulacion_AM = A_p*(1+ka*np.cos(2*np.pi*f_m*t))*np.cos(2*np.pi*f_p*t) 14 | 15 | # señal moduladora 16 | plt.subplot(3,1,1) 17 | plt.title("Señal de Mensaje o Moduladora") 18 | plt.plot(moduladora,'g') 19 | plt.ylabel('Amplitud') 20 | 21 | # señal portadora 22 | plt.subplot(3,1,2) 23 | plt.title("Señal Portadora") 24 | plt.plot(portadora,'r') 25 | plt.ylabel('Amplitud') 26 | 27 | # señal AM 28 | plt.subplot(3,1,3) 29 | plt.title("Modulacion AM") 30 | plt.plot(modulacion_AM, color='purple') 31 | plt.ylabel('Amplitud') 32 | plt.xlabel('Señal AM') 33 | 34 | plt.show() 35 | -------------------------------------------------------------------------------- /modula_audio.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.io import wavfile 3 | 4 | # Parámetros de la señal de audio 5 | duration = 3 # Duración en segundos 6 | sample_rate = 44100 # Frecuencia de muestreo en Hz 7 | frequency = 440 # Frecuencia base en Hz 8 | modulation_rate = 5 # Frecuencia de modulación en Hz 9 | 10 | # Crear la señal base (portadora) 11 | t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False) 12 | carrier_wave = np.sin(2 * np.pi * frequency * t) 13 | 14 | # Señal de modulación 15 | modulation_wave = np.sin(2 * np.pi * modulation_rate * t) 16 | 17 | # Modulación de la señal base 18 | modulated_wave = np.sin(2 * np.pi * (frequency + modulation_rate * modulation_wave) * t) 19 | 20 | # Normalizar para asegurarse de que esté en el rango de -1 a 1 21 | modulated_wave /= np.max(np.abs(modulated_wave), axis=0) 22 | 23 | # Guardar la señal modulada en un archivo de audio 24 | wavfile.write('modulated_audio.wav', sample_rate, np.int16(modulated_wave * 32767)) 25 | 26 | print("Señal de audio modulada guardada correctamente.") 27 | -------------------------------------------------------------------------------- /modulacion_am_grafica.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # Configuración de parámetros 5 | fs = 400 # Frecuencia de muestreo 6 | Ec = 5 # Voltaje pico de la portadora 7 | fc = 20 # Frecuencia de la portadora 8 | fm = 1 # Frecuencia de la moduladora 9 | m = 0.8 # Índice de modulación 10 | 11 | Nc = 2 # Número de ciclos que se mostrará en la gráfica 12 | t = np.arange(0, Nc/fm, 1/fs) # Vector de tiempo 13 | 14 | # Generación de señales 15 | Vc = m * Ec * np.sin(2 * np.pi * fc * t) # Señal portadora 16 | Vmod = m * Ec * np.sin(2 * np.pi * fm * t) # Señal moduladora 17 | Vam = (1 + m * np.sin(2 * np.pi * fm * t)) * Ec * np.sin(2 * np.pi * fc * t) # Señal AM 18 | 19 | # Creación de la figura y los ejes 20 | fig, ax = plt.subplots(figsize=(15, 7)) 21 | ax.set_title('Modulación AM') 22 | ax.set_xlabel('Tiempo') 23 | ax.set_ylabel('Amplitud') 24 | ax.grid(True) 25 | 26 | # Graficar las señales 27 | ax.plot(t, Vc + 15, label='Portadora', color='b') # Desplazar la portadora para visualizar mejor 28 | ax.plot(t, Vmod + 5, label='Moduladora', color='r') # Desplazar la moduladora para visualizar mejor 29 | ax.plot(t, Vam, label='Señal AM', color='k') 30 | 31 | # Configuración de leyenda 32 | ax.legend() 33 | 34 | # Mostrar la gráfica 35 | plt.show() 36 | -------------------------------------------------------------------------------- /motion_filtering.py: -------------------------------------------------------------------------------- 1 | import cv2 as cv 2 | 3 | video = cv.VideoCapture("video1.avi") 4 | subtractor = cv.createBackgroundSubtractorMOG2(300, 100) 5 | 6 | while True: 7 | 8 | ret,frame = video.read() 9 | 10 | 11 | if ret: 12 | mask = subtractor.apply(frame) 13 | cv.imshow('Mask', mask) 14 | 15 | if cv.waitKey(5) == ord('x'): 16 | break 17 | else: 18 | video = cv.VideoCapture('video1.avi') 19 | 20 | cv.destroyAllWindows() 21 | video.release() 22 | -------------------------------------------------------------------------------- /move_tk.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter.ttk import * 3 | 4 | class GFG: 5 | def __init__(self, master = None): 6 | self.master = master 7 | 8 | #CORDENADAS INICIALES. 9 | self.x = 1 10 | self.y = 0 11 | 12 | #CREAR FIGURA 13 | self.canvas = Canvas(master) 14 | #CREAR RECTANGULO 15 | self.rectangle = self.canvas.create_rectangle( 16 | 5, 5, 25, 25, fill = "black") 17 | #COLOR FONDO. 18 | self.canvas['bg'] = 'green' 19 | 20 | self.canvas.pack() 21 | 22 | 23 | #LLAMADA A LA FUNCION "movimiento" 24 | self.movimiento() 25 | 26 | def movimiento(self): 27 | #MOVER FIGURA 28 | self.canvas.move(self.rectangle, self.x, self.y) 29 | 30 | self.canvas.after(100, self.movimiento) 31 | 32 | #MOVIMIENTO A LA IZQUIERDA 33 | def izquierda(self, event): 34 | print(event.keysym) 35 | self.x = -5 36 | self.y = 0 37 | 38 | #MOVIMIENTO A LA DERECHA 39 | def derecha(self, event): 40 | print(event.keysym) 41 | self.x = 5 42 | self.y = 0 43 | 44 | #MOVIMIENTO HACIA ARRIBA 45 | def arriba(self, event): 46 | print(event.keysym) 47 | self.x = 0 48 | self.y = -5 49 | 50 | #MOVIMIENTO HACIA ABAJO 51 | def abajo(self, event): 52 | print(event.keysym) 53 | self.x = 0 54 | self.y = 5 55 | 56 | if __name__ == "__main__": 57 | 58 | #MOSTRAR VENTANA 59 | master = Tk() 60 | master.title("Move_tk") 61 | master.configure(bg="green") 62 | gfg = GFG(master) 63 | 64 | #CONTROLAR MOVIMIENTO POR TECLADO 65 | master.bind("", lambda e: gfg.izquierda(e)) 66 | master.bind("", lambda e: gfg.derecha(e)) 67 | master.bind("", lambda e: gfg.arriba(e)) 68 | master.bind("", lambda e: gfg.abajo(e)) 69 | mainloop() 70 | -------------------------------------------------------------------------------- /muestra_foto.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS RECUROS NECESARIOS. 2 | from PyQt5.QtWidgets import (QWidget, QHBoxLayout, 3 | QLabel, QApplication) 4 | from PyQt5.QtGui import QPixmap 5 | import sys 6 | 7 | class Example(QWidget): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | #INICIAR FUNCIÓN. 13 | self.muestra_foto() 14 | 15 | 16 | def muestra_foto(self): 17 | 18 | #CREAMOS LAYOUT 19 | hbox = QHBoxLayout(self) 20 | pixmap = QPixmap("Honda_Goldwing.jpg") 21 | 22 | #CREAMOS ETIQUETA 23 | lbl = QLabel(self) 24 | lbl.setPixmap(pixmap) 25 | 26 | #AÑADIMOS ETIQUETA AL LAYOUT. 27 | hbox.addWidget(lbl) 28 | self.setLayout(hbox) 29 | 30 | #UBICACIÓN Y TÍTULO DE LA VENTANA. 31 | self.move(400,100) 32 | self.setWindowTitle('My photo') 33 | self.show() 34 | 35 | 36 | #EJECUTAMOS CLASE "Example". 37 | if __name__ == '__main__': 38 | 39 | app = QApplication(sys.argv) 40 | ex = Example() 41 | sys.exit(app.exec_()) 42 | -------------------------------------------------------------------------------- /multiple_lineal_regression.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import pandas as pd 3 | import numpy as np 4 | from sklearn import linear_model 5 | from sklearn.metrics import r2_score 6 | 7 | df = pd.read_csv('FuelConsumption.csv') 8 | 9 | print(df.head(10)) 10 | 11 | cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY','FUELCONSUMPTION_COMB','CO2EMISSIONS']] 12 | print(cdf.head(9)) 13 | 14 | plt.scatter(cdf.ENGINESIZE,cdf.CO2EMISSIONS,color='blue') 15 | plt.xlabel("Engine size") 16 | plt.ylabel("Emissions") 17 | plt.show() 18 | 19 | msk = np.random.rand(len(df)) < 0.8 20 | train = cdf[msk] 21 | test = cdf[~msk] 22 | 23 | plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue') 24 | plt.xlabel("Engine size") 25 | plt.ylabel("Emission") 26 | plt.show() 27 | 28 | regr = linear_model.LinearRegression() 29 | train_x = np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']]) 30 | train_y = np.asanyarray(train[['CO2EMISSIONS']]) 31 | regr.fit(train_x, train_y) 32 | print('Coefficients: ', regr.coef_) 33 | print('Intercept: ', regr.intercept_) 34 | 35 | # Prediction 36 | y_hat = regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']]) 37 | x = np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']]) 38 | y = np.asanyarray(test[['CO2EMISSIONS']]) 39 | print("Mean Squared Error (MSE) : %.2f" 40 | % np.mean((y_hat - y) ** 2)) 41 | 42 | print("Variance score: %.2f" % regr.score(x, y)) 43 | -------------------------------------------------------------------------------- /multiple_shares_dfs.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader as pdr 2 | import matplotlib.pyplot as plt 3 | import matplotlib.ticker as ticker 4 | 5 | companies = ['AAPL', 'MSFT', 'GE'] 6 | shares_multiple_df = pdr.DataReader(companies, 'yahoo', start='2021-01-01', end='2021-12-31') 7 | print(shares_multiple_df) 8 | 9 | def plot_timeseries_df(df, attrib, ticker_loc=1, title='Timeseries', legend=''): 10 | "General routine for plotting time series data" 11 | fig = plt.figure(figsize=(15,7)) 12 | plt.plot(df[attrib], 'o-') 13 | _ = plt.xticks(rotation=90) 14 | plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(ticker_loc)) 15 | plt.title(title) 16 | plt.gca().legend(legend) 17 | plt.show() 18 | 19 | plot_timeseries_df(shares_multiple_df.loc["2021-04-01":"2021-06-30"], "Close", 20 | ticker_loc=3, title="Close price", legend=companies) 21 | -------------------------------------------------------------------------------- /noise_redux.py: -------------------------------------------------------------------------------- 1 | import ffmpeg 2 | 3 | input_video = 'input_video.mp4' 4 | output_video = 'output_video6.mp4' 5 | 6 | # Aplicar filtro de reducción de ruido 7 | denoise_filter = "hqdn3d=6:7:6:6" 8 | 9 | # Comando de ffmpeg para aplicar el filtro de reducción de ruido 10 | command = [ 11 | 'ffmpeg', '-i', input_video, '-vf', denoise_filter, '-c:a', 'copy', output_video 12 | ] 13 | 14 | # Ejecutar el comando de ffmpeg 15 | subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 16 | 17 | print("Reducción de ruido aplicada correctamente.") 18 | -------------------------------------------------------------------------------- /noisedFrames_generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | import numpy as np 3 | import cv2 4 | import os 5 | 6 | for i in range(0,34): 7 | img = np.zeros((900,1600,3),np.uint8) 8 | 9 | for x in range(900): 10 | for y in range(1600): 11 | img[x,y] = [random.randint(225,240),random.randint(0,256),random.randint(0,256)]#(0,256)(0,256) 12 | 13 | name = "ima "+str(i)+".png" 14 | cv2.imwrite(name,img) 15 | print("DONE: ",name) 16 | print("FINISH") 17 | -------------------------------------------------------------------------------- /ogl_Bezier.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.locals import * 3 | from OpenGL.GL import * 4 | from OpenGL.GLU import * 5 | import numpy as np 6 | 7 | def init(): 8 | glClearColor(0.0, 0.0, 0.0, 0.0) 9 | glColor3f(1.0, 1.0, 1.0) 10 | glPointSize(5.0) 11 | glEnable(GL_MAP1_VERTEX_3) 12 | 13 | def draw_curve(): 14 | # Definir los puntos de control de la curva de Bézier 15 | control_points = np.array([ 16 | [-4.0, -4.0, 0.0], 17 | [-2.0, 4.0, 0.0], 18 | [ 2.0, -4.0, 0.0], 19 | [ 4.0, 4.0, 0.0] 20 | ], dtype='float32') 21 | 22 | # Configurar el evaluator para la curva de Bézier de grado 3 23 | glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, control_points) 24 | 25 | # Dibujar la curva de Bézier utilizando el evaluator 26 | glBegin(GL_LINE_STRIP) 27 | for i in range(101): 28 | t = i / 100.0 29 | glEvalCoord1f(t) # Evaluar la curva para el valor de t 30 | glEnd() 31 | 32 | # Dibujar los puntos de control 33 | glColor3f(1.0, 0.0, 0.0) # Color rojo para los puntos de control 34 | glBegin(GL_POINTS) 35 | for point in control_points: 36 | glVertex3fv(point) 37 | glEnd() 38 | 39 | def main(): 40 | pygame.init() 41 | screen = pygame.display.set_mode((800, 600), DOUBLEBUF | OPENGL) 42 | pygame.display.set_caption('Bezier Curve using Evaluators in OpenGL') 43 | 44 | gluOrtho2D(-5.0, 5.0, -5.0, 5.0) 45 | init() 46 | 47 | running = True 48 | while running: 49 | for event in pygame.event.get(): 50 | if event.type == QUIT: 51 | running = False 52 | 53 | glClear(GL_COLOR_BUFFER_BIT) 54 | draw_curve() 55 | pygame.display.flip() 56 | 57 | pygame.quit() 58 | 59 | if __name__ == '__main__': 60 | main() 61 | -------------------------------------------------------------------------------- /openGL_triangle.py: -------------------------------------------------------------------------------- 1 | import glfw 2 | from OpenGL.GL import * 3 | import numpy as np 4 | 5 | class Window: 6 | def __init__(self, width:int, height:int, title:str): 7 | if not glfw.init(): 8 | raise Exception("glfw can not be initialized") 9 | 10 | self._win = glfw.create_window(width, height, title, None, None) 11 | 12 | if not self._win: 13 | glfw.terminate() 14 | raise Exception("glfw window can not be created") 15 | 16 | glfw.set_window_pos(self._win, 400, 200) 17 | glfw.make_context_current(self._win) 18 | 19 | vertices = [-0.5, -0.5, 0.0, 20 | 0.5, -0.5, 0.0, 21 | 0.0, 0.5, 0.0] 22 | 23 | colors = [1.0, 0.0, 0.0, 24 | 0.0, 1.0, 0.0, 25 | 0.0, 0.0, 1.0] 26 | 27 | vertices = np.array(vertices, dtype=np.float32) 28 | colors = np.array(colors, dtype=np.float32) 29 | 30 | glEnableClientState(GL_VERTEX_ARRAY) 31 | glVertexPointer(3, GL_FLOAT, 0, vertices) 32 | 33 | glEnableClientState(GL_COLOR_ARRAY) 34 | glColorPointer(3, GL_FLOAT, 0, colors) 35 | 36 | glClearColor(0, 0.1, 0.1, 1) 37 | 38 | def main_loop(self): 39 | while not glfw.window_should_close(self._win): 40 | glfw.poll_events() 41 | 42 | glClearColor(0, 0, 0, 0) 43 | glClear(GL_COLOR_BUFFER_BIT) 44 | 45 | glDrawArrays(GL_TRIANGLES, 0, 3) 46 | 47 | glfw.swap_buffers(self._win) 48 | 49 | glfw.terminate() 50 | 51 | if __name__ == "__main__": 52 | win = Window(1100, 720, "My OpenGL window")#1280, 720, 53 | win.main_loop() 54 | 55 | -------------------------------------------------------------------------------- /opensave_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from tkinter import filedialog 4 | from tkinter import * 5 | import os 6 | 7 | ventana = Tk() 8 | 9 | def abrir_archivo(): 10 | archivo_abierto=filedialog.askopenfilename(initialdir = "/", 11 | title = "Seleccione archivo",filetypes = (("jpeg files","*.jpg"), 12 | ("all files","*.*"))) 13 | print(archivo_abierto) 14 | 15 | 16 | def guardar_archivo(): 17 | archivo_guardado=filedialog.asksaveasfilename(initialdir = "/",title = "Select file",defaultextension=".txt", 18 | filetypes = (("jpeg files","*.jp2g"), 19 | ("txt files","*.txt"), 20 | ("all files","*.*"))) 21 | 22 | archivo=open(archivo_guardado,"w") 23 | print(archivo_guardado) 24 | 25 | def carpeta(): 26 | directorio=filedialog.askdirectory() 27 | if directorio!="": 28 | os.chdir(directorio) 29 | print(os.getcwd()) 30 | 31 | Button(text="Abrir archivo",bg="pale green",command=abrir_archivo).place(x=10,y=10) 32 | Button(text="Guardar archivo",bg="light blue",command=guardar_archivo).place(x=10,y=40) 33 | Button(text="Directorio",bg="salmon",command=carpeta).place(x=10,y=70) 34 | 35 | ventana.mainloop() 36 | -------------------------------------------------------------------------------- /pandas2excel_example.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | #CREAR DATAFRAME 4 | data = {'col_A':[1, 2, 3], 'col_B':[1, 2, 3], 'col_c':[1, 2, 3], 'col_D':[1, 2, 3], 'col_E':[1, 2, 3]} 5 | df = pd.DataFrame(data) 6 | print(df) 7 | 8 | #INICIALIZAR WRITER 9 | writer = pd.ExcelWriter('Example.xlsx', engine='xlsxwriter') 10 | df.to_excel(writer, sheet_name='Example Sheet', index = False) 11 | 12 | #INICIALIZAR FORMATO. 13 | workbook = writer.book 14 | 15 | #REOP 16 | worksheet = writer.sheets['Example Sheet'] 17 | 18 | #HEADER FORMAT 19 | header_format = workbook.add_format() 20 | header_format.set_center_across(True) 21 | header_format.set_bold(True) 22 | header_format.set_font('Courier New') 23 | 24 | #FORMATO DE CELDA 25 | cell_format = workbook.add_format() 26 | cell_format.set_font('Courier New') 27 | 28 | #ANCHO DE 15 PARA COLUMNS A - C Y 20 PARA 20 PARA D. 29 | worksheet.set_column('A:C', 15, cell_format) 30 | worksheet.set_column('D:D', 20, cell_format) 31 | 32 | for col in ['A', 'E']: 33 | worksheet.set_column(f'{col}:{col}', 5, cell_format) 34 | 35 | #GUARDAR CAMBIOS. 36 | writer.save() 37 | -------------------------------------------------------------------------------- /pares_con_filter.py: -------------------------------------------------------------------------------- 1 | #FILTRA LOS NÚMEROS PARES DE LA LISTA USANDO 'filter()'. 2 | numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 3 | 4 | def mifuncion(x): 5 | if x % 2 == 0: 6 | return True 7 | 8 | return False 9 | 10 | resultado = filter(mifuncion, numeros) 11 | print(list(resultado)) 12 | -------------------------------------------------------------------------------- /plot_2stock_prices.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import matplotlib.pyplot as plt 3 | from datetime import datetime 4 | 5 | # Define los símbolos de las acciones de las compañías 6 | symbol1 = 'NVDA' # Apple Inc. 7 | symbol2 = 'MSFT' # Microsoft Corporation 8 | 9 | # Define el rango de fechas para los datos históricos 10 | start_date = '2022-01-01' 11 | end_date = datetime.today().strftime('%Y-%m-%d') 12 | 13 | # Descarga los datos históricos de las acciones usando yfinance 14 | data1 = yf.download(symbol1, start=start_date, end=end_date) 15 | data2 = yf.download(symbol2, start=start_date, end=end_date) 16 | 17 | # Graficar la evolución del precio de las acciones 18 | plt.figure(figsize=(14, 7)) 19 | plt.plot(data1.index, data1['Adj Close'], label=symbol1) 20 | plt.plot(data2.index, data2['Adj Close'], label=symbol2) 21 | 22 | # Añadir títulos y etiquetas 23 | plt.title(f'Evolución del Precio de las Acciones de {symbol1} y {symbol2}') 24 | plt.grid() 25 | plt.xlabel('Fecha') 26 | plt.ylabel('Precio de Cierre Ajustado') 27 | plt.legend() 28 | 29 | # Mostrar la gráfica 30 | plt.show() 31 | -------------------------------------------------------------------------------- /pmw_counter.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import Pmw 3 | 4 | ventana = Tk() 5 | Pmw.initialise(ventana) 6 | 7 | counter1 = Pmw.Counter() 8 | counter1.setentry(41) 9 | counter1.increment() 10 | counter1.pack(padx = 10, pady = 10) 11 | #counter1.configure(increment=3)#ESPECIFICAR INCREMENTO 12 | 13 | counter2 = Pmw.Counter(datatype = 'time', 14 | increment = 60) 15 | counter2.setentry('00:00:00') 16 | counter2.configure(increment = 1 * 1/60 * 60) #cambiar incremento 17 | counter2.pack(padx = 10, pady = 10) 18 | counter2.configure(downarrow_background = 'green', 19 | uparrow_background = 'red') 20 | #print(counter2.get()) 21 | #print(counter2.cget('datatype')) 22 | 23 | counter3 = Pmw.Counter(orient = 'vertical') 24 | counter3.pack(padx = 10, pady = 10) 25 | #print(counter3.cget('increment')) 26 | 27 | counter4 = Pmw.Counter( 28 | hull_relief = 'sunken', 29 | hull_borderwidth = 5) 30 | counter4.setentry(1982) 31 | counter4.pack(padx = 10, pady = 10) 32 | -------------------------------------------------------------------------------- /practica1_cv2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | from matplotlib import pyplot as plt 4 | #from copy import deepcopy 5 | import os 6 | 7 | os.chdir(r'ruta') 8 | 9 | img=cv2.imread(archivo,1) 10 | 11 | def click2circle(event,x,y,flags,param): 12 | if event==cv2.EVENT_LBUTTONDBLCLK: 13 | cv2.circle(img,(x,y),50,(255,0,0),4) 14 | 15 | cv2.namedWindow("IMAGEN",cv2.WINDOW_NORMAL) 16 | cv2.setMouseCallback("IMAGEN",click2circle) 17 | 18 | while True: 19 | cv2.imshow("IMAGEN",img) 20 | a=cv2.waitKey(1000) 21 | print("2 secs") 22 | if a == 27: #ESC button 23 | print("FIN") 24 | break 25 | cv2.destroyAllWindows() 26 | -------------------------------------------------------------------------------- /primer_juego.py: -------------------------------------------------------------------------------- 1 | import pygame, sys 2 | from pygame.locals import * 3 | 4 | pygame.init() 5 | DISPLAYGAME=pygame.display.set_mode((400,300)) 6 | pygame.display.set_caption("Hello World!") 7 | while True: 8 | for event in pygame.event.get(): 9 | if event.type==QUIT: 10 | pygame.quit() 11 | sys.exit() 12 | pygame.display.update() 13 | -------------------------------------------------------------------------------- /probaility_of_detection.py: -------------------------------------------------------------------------------- 1 | import random 2 | from collections import Counter 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | NUM_EQUIV_VOLUMES = 1000 7 | MAX_CIVS = 5000 8 | TRIALS = 1000 9 | CIV_STEP_SIZE = 100 10 | 11 | x = [] 12 | y = [] 13 | 14 | for num_civs in range(2,MAX_CIVS + 2,CIV_STEP_SIZE): 15 | #print(num_civs) 16 | civs_per_vol = num_civs/NUM_EQUIV_VOLUMES 17 | #print(civs_per_vol) 18 | num_single_civs = 0 19 | 20 | for trial in range(TRIALS): 21 | locations = [] 22 | while len(locations)": 34 | done = True 35 | else: 36 | file_bytes += data 37 | time.sleep(0.003) 38 | progress.update(1024) # ACTUALIZAR BARRA DE PROGRESO 39 | 40 | file.write(file_bytes) # ESCRIBIR ARCHIVO 41 | 42 | file.close() # CERRAR ARCHIVO 43 | client.close() # CERRAR CLIENTE 44 | server.close() # CERRAR SERVIDOR 45 | 46 | -------------------------------------------------------------------------------- /regresion_lineal.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS RECURSOS. 2 | import numpy as np 3 | from sklearn import datasets, linear_model 4 | from sklearn.model_selection import train_test_split 5 | import matplotlib.pyplot as plt 6 | 7 | #IMPORTAMOS DATOS DE MUESTRA. 8 | boston = datasets.load_boston() 9 | print(boston) 10 | print("") 11 | 12 | #TIPOS DE DATOS. 13 | print("Información del dataset:") 14 | print(boston.keys()) 15 | print("") 16 | 17 | #MOSTRAR NOMBRES COLUMNAS. 18 | print("Nombres Columnas:") 19 | print(boston.feature_names) 20 | 21 | #DESCRIPCIÓN COLUMNAS. 22 | print(boston.DESCR) 23 | 24 | #SELECCIONAR DATOS DE LA COLUMNA 5. 25 | X = boston.data[:, np.newaxis, 5] 26 | 27 | #EJE "y". 28 | y = boston.target 29 | 30 | #GRAFICAR DATOS. 31 | plt.scatter(X, y) 32 | plt.xlabel("Número de habitaciones") 33 | plt.ylabel("Valor medio") 34 | plt.show() 35 | 36 | #SEPARAR DATOS DE ENTRENAMIENTO DE DATOS DE PRUEBA. 37 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) 38 | 39 | #ALGORITMO DE REGRESION LINEAL. 40 | lr = linear_model.LinearRegression() 41 | 42 | #ENTRENAR MODELO. 43 | lr.fit(X_train, y_train) 44 | 45 | #OBTENER PREDICCIÓN. 46 | Y_pred = lr.predict(X_test) 47 | 48 | #GRAFICAR MODELO. 49 | plt.scatter(X_test, y_test) 50 | plt.plot(X_test, Y_pred, color='red', linewidth=3) 51 | plt.title('Regresión Lineal Simple') 52 | plt.xlabel('Número de habitaciones') 53 | plt.ylabel('Valor medio') 54 | plt.show() 55 | 56 | #PENDIENTE. 57 | print("Pendiente: ",lr.coef_) 58 | #INTERCEPTOR. 59 | print("Interceptor: ",lr.intercept_) 60 | print("") 61 | 62 | #PRECISIÓN DEL MODELO. 63 | print("Precisión del modelo: ",lr.score(X_train, y_train)) 64 | -------------------------------------------------------------------------------- /reloj_digital.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from tkinter import * 4 | import time 5 | 6 | #FUNCION PARA ACTUALIZAR LA HORA 7 | def times(): 8 | current_time=time.strftime("%H:%M:%S") 9 | clock.config(text=current_time,bg="black",fg="green",font="Arial 50 bold") 10 | clock.after(200,times) 11 | 12 | #VENTANA 13 | root=Tk() 14 | root.geometry("485x250") 15 | root.title("Reloj digital con Tkinter") 16 | clock=Label(root,font=("times",50,"bold")) 17 | 18 | clock.grid(row=2,column=1,pady=25,padx=100) 19 | times() 20 | 21 | digi=Label(root,text=" Hora Actual",font="times 24 bold",fg="red") 22 | digi.grid(row=0,column=1) 23 | 24 | root.mainloop() 25 | 26 | 27 | -------------------------------------------------------------------------------- /reproduce_audio.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | 3 | def reproducir_mp3(ruta_archivo): 4 | # Comando para reproducir el archivo MP3 con ffmpeg 5 | comando = ['ffplay', '-nodisp', '-autoexit', ruta_archivo] 6 | 7 | # Ejecutar el comando en un proceso 8 | subprocess.call(comando) 9 | 10 | # Ruta al archivo MP3 11 | ruta_mp3 = "grabacion.mp3" 12 | 13 | # Llamar a la función para reproducir el archivo MP3 14 | reproducir_mp3(ruta_mp3) 15 | -------------------------------------------------------------------------------- /reverse_cipher.py: -------------------------------------------------------------------------------- 1 | #REVERSE CIPHER 2 | from VALID import ns 3 | 4 | while True: 5 | text = input("Your text: ") 6 | translated = "" 7 | i = len(text) - 1 8 | 9 | while i >= 0: 10 | translated = translated + text[i] 11 | i = i - 1 12 | print(translated) 13 | 14 | print('Final translation: ',translated) 15 | 16 | conti = ns(input("Continue(n/s)?: ")) 17 | if conti == "n": 18 | break 19 | -------------------------------------------------------------------------------- /robot_control.py: -------------------------------------------------------------------------------- 1 | from robot_control_class import RobotControl 2 | import argparse 3 | 4 | rc = RobotControl(robot_name="summit") 5 | 6 | def main(): 7 | parser = argparse.ArgumentParser(prog="ROBOT-CONTROL",conflict_handler='resolve', 8 | description="Mnipulate Summit Robot") 9 | parser.add_argument('-mv','--move',required=True,choices=["straight","turn"],type=str,help="...") 10 | parser.add_argument('-dir','--direction',required=True,choices=["up","back"],type=str,help="...") 11 | parser.add_argument('-tm','--time',required=True,type=int,help="Time in seconds") 12 | parser.add_argument('-spd','--speed',required=True,type=float,help="Distance") 13 | 14 | args = parser.parse_args() 15 | 16 | if args.move == "straight": 17 | movements = {"up":"forward","back":"backward"} 18 | rc.move_straight_time(movements[args.direction],args.speed,args.time) 19 | else: 20 | movements = {"up":"clockwise","back":"counter-clockwise"} 21 | rc.turn(movements[args.direction],args.speed,args.time) 22 | 23 | if __name__=='__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /sapimienta.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import random 4 | 5 | img_gs = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE) 6 | 7 | def salt_pepper(prob): 8 | row, col = img_gs.shape 9 | 10 | s_vs_p = 0.5 11 | output = np.copy(img_gs) 12 | 13 | num_salt = np.ceil(prob * img_gs.size * s_vs_p) 14 | coords = [np.random.randint(0, i - 1, int(num_salt)) 15 | for i in img_gs.shape] 16 | output[tuple(coords)] = 1 17 | 18 | num_pepper = np.ceil(prob * img_gs.size * (1. - s_vs_p)) 19 | coords = [np.random.randint(0, i - 1, int(num_pepper)) 20 | for i in img_gs.shape] 21 | output[tuple(coords)] = 0 22 | cv2.imshow("ima",output) 23 | 24 | return output 25 | 26 | sp_05 = salt_pepper(0.5) 27 | 28 | cv2.imwrite('lena_new.jpg', sp_05) 29 | -------------------------------------------------------------------------------- /sayit.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | import pyfiglet 3 | 4 | engine = pyttsx3.init() 5 | 6 | engine.setProperty('voice', 'spanish') 7 | engine.setProperty('rate',200) 8 | 9 | print(pyfiglet.figlet_format("SayIt!\n",font="dos_rebel")) 10 | 11 | while True: 12 | texto = input("> ") 13 | engine.say(texto) 14 | engine.runAndWait() 15 | 16 | if texto == "": 17 | print("Program finished") 18 | break 19 | -------------------------------------------------------------------------------- /scatter.py: -------------------------------------------------------------------------------- 1 | from mpl_toolkits.mplot3d import Axes3D 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | 6 | def randrange(n, vmin, vmax): 7 | return (vmax - vmin)*np.random.rand(n) + vmin 8 | 9 | fig = plt.figure() 10 | ax = fig.add_subplot(111, projection='3d') 11 | 12 | n = 100 13 | 14 | for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]: 15 | xs = randrange(n, 23, 32) 16 | ys = randrange(n, 0, 100) 17 | zs = randrange(n, zlow, zhigh) 18 | ax.scatter(xs, ys, zs, c=c, marker=m) 19 | 20 | ax.set_xlabel('X Label') 21 | ax.set_ylabel('Y Label') 22 | ax.set_zlabel('Z Label') 23 | 24 | plt.show() 25 | -------------------------------------------------------------------------------- /screen_assistant.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter import filedialog 3 | import cv2 4 | import pyautogui 5 | import threading 6 | import os 7 | 8 | class assistant: 9 | def __init__(self): 10 | self.window = Tk() 11 | self.window.title("Screen Assistant") 12 | self.window.geometry("520x250") 13 | 14 | self.currentDir = StringVar() 15 | self.currentDir.set(os.getcwd()) 16 | self.awake = False 17 | 18 | Entry(self.window,textvariable=self.currentDir,width=86).place(x=0,y=0) 19 | self.statusLab = Label(self.window,text='ZZZZZZ...',bg='black',fg='green',font=('arial',20,'bold'),width=29) 20 | self.statusLab.place(x=10,y=26) 21 | self.btnActiv = Button(self.window,text="ACTIVATE",bg='blue',fg='white',width=70,height=3,command=self.wake_up) 22 | self.btnActiv.place(x=10,y=80) 23 | Button(self.window,text="CHANGE DIRECTORY",bg='khaki',width=70,height=3,command=self.change_dir).place(x=10,y=142) 24 | 25 | 26 | self.window.mainloop() 27 | 28 | def change_dir(self): 29 | new_dir = filedialog.askdirectory() 30 | if new_dir != "": 31 | os.chdir(new_dir) 32 | self.currentDir.set(os.getcwd()) 33 | 34 | def wake_up(self): 35 | if self.awake == False: 36 | self.awake = True 37 | self.btnActiv.configure(text='ACTIVATED') 38 | self.statusLab.configure(text='NOW LISTENING...') 39 | else: 40 | self.awake = False 41 | self.btnActiv.configure(text='ACTIVATE') 42 | self.statusLab.configure(text='ZZZZZZ...') 43 | 44 | 45 | if __name__=="__main__": 46 | assistant() 47 | -------------------------------------------------------------------------------- /sender.py: -------------------------------------------------------------------------------- 1 | import os 2 | import socket 3 | 4 | HOST = "localhost" #IP DEL SERVIDOR 5 | PORT = 9999 #PUERTO DE ENVIO 6 | 7 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | client.connect((HOST, PORT)) # SOLICITUD DE CONEXION CON SERVIDOR 9 | 10 | file = open("image.png", "rb") # ABRIR ARCHIVO A TRANSFERIR 11 | file_size = os.path.getsize("image.png") # OBTENER TAMAÑO ARCHIVO 12 | 13 | client.send("copied_image.png".encode()) # ENVIAR NOMBRE DE NUEVO ARCHIVO 14 | client.send(str(file_size).encode()) # ENVIAR TAMAÑO ARCHIVO 15 | 16 | data = file.read() # LEER INFORMACIÓN DEL ARCHIVO 17 | client.sendall(data) # ENVIAR INFORMACIÓN DE ARCHIVO AL SERVIDOR 18 | client.send(b"") # MARCADOR DE FIN DE DATOS 19 | 20 | file.close() # CERRAR ARCHIVO 21 | client.close() # CERRAR CLIENTE 22 | -------------------------------------------------------------------------------- /serializacion.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | 3 | class Vehiculo: 4 | marca = "" 5 | num_ruedas = 0.0 6 | 7 | def __init__(self, marca, num_ruedas): 8 | self.marca = marca 9 | self.num_ruedas = num_ruedas 10 | 11 | def getMarca(self): 12 | return self.marca 13 | 14 | 15 | v1 = Vehiculo("seat", 4) 16 | 17 | f = open('datos.bin','wb') 18 | pickle.dump(v1, f)#SERIALIZACION 19 | f.close() 20 | 21 | f = open('datos.bin', 'rb') 22 | vehiculo = pickle.load(f)#DESERIALIZACIÓN 23 | f.close() 24 | 25 | print(vehiculo.getMarca(), "número de ruedas: ", vehiculo.num_ruedas) 26 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | HOST = "127.0.0.1" # ESTABLECEMOS DIRECCIÓN 4 | PORT = 65123 # PUERTO DE ESCUCHA 5 | 6 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 7 | 8 | s.bind((HOST, PORT)) # ASOCIAR SOCKET A DIRECCIÓN IP Y PUERTO 9 | s.listen() # PONER SOCKET A LA ESCUCHA 10 | conn, addr = s.accept() # ESPERAR CONEXIONES ENTRANTES 11 | 12 | with conn: 13 | print(f"Conexión establecida con {addr}:") 14 | while True: 15 | data = conn.recv(1024) # RECIBE DATOS DEL CLIENTE 16 | if not data: 17 | break 18 | 19 | conn.sendall(data) # DEVUELVE LOS DATOS AL CLIENTE 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /server_expro.py: -------------------------------------------------------------------------------- 1 | 2 | def get_event_date(event): 3 | return event.date 4 | 5 | def current_users(events): 6 | events.sort(key=get_event_date) 7 | machines={} 8 | for event in events: 9 | if event.machine not in machines: 10 | machines[event.machine] = set() 11 | if event.type == "login": 12 | machines[event.machine].add(event.user) 13 | elif event.type == "logout": 14 | machines[event.machine].remove(event.user) 15 | return machines 16 | 17 | def generate_report(machines): 18 | for machine, users in machines.items(): 19 | if len(users) > 0: 20 | user_list = ", ".join(users) 21 | print("{}: {}".format(machine, user_list)) 22 | 23 | class Event: 24 | def __init__(self,event_date,event_type,machine_name,user): 25 | self.date = event_date 26 | self.type = event_type 27 | self.machine = machine_name 28 | self.user = user 29 | 30 | events = [ 31 | Event('2020-01-21 12:45:56', 'login', 'myworkstation.local','jordan'), 32 | Event('2020-01-22 15:53:42', 'logout', 'webserver.local','jordan'), 33 | Event('2020-01-21 18:53:21', 'login', 'webserver.local','lane'), 34 | Event('2020-01-22 10:25:34', 'logout', 'myworkstation.local','jordan'), 35 | Event('2020-01-21 08:20:01', 'login', 'webserver.local','jordan'), 36 | Event('2020-01-23 11:24:35', 'login', 'mailserver.local','chris'), 37 | ] 38 | 39 | users = current_users(events) 40 | print(users) 41 | 42 | generate_report(users) 43 | -------------------------------------------------------------------------------- /simple_bitcoin_miner.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | #print(hashlib.sha256("Hello world".encode()).hexdigest()) 4 | 5 | NONCE_LIMIT = 100000000000 6 | 7 | zeros = 4 8 | 9 | def miner(block_number, transactions, previous_hash): 10 | for nonce in range(NONCE_LIMIT): 11 | base_text = str(block_number) + transactions + previous_hash + str(nonce) 12 | hash_try = hashlib.sha256(base_text.encode()).hexdigest() 13 | if hash_try.startswith('0' * zeros): 14 | print(f"Found Hash With Nonce: {nonce}") 15 | print(f"Hash: {hash_try}") 16 | return hash_try 17 | return -1 18 | 19 | 20 | block_number = 24 21 | transactions = "76123fcc2141" 22 | previous_hash = "876de8756b967c87" 23 | 24 | miner(block_number, transactions, previous_hash) 25 | -------------------------------------------------------------------------------- /sine_anim.py: -------------------------------------------------------------------------------- 1 | '''import plotext 2 | import numpy as np 3 | 4 | def main(): 5 | l = 1000 6 | frames = 50 7 | 8 | plotext.title("Sine Animation") 9 | plotext.clc() 10 | 11 | for i in range(frames): 12 | plotext.clt() 13 | plotext.cld() 14 | 15 | x = np.linspace(0, 10, l) 16 | y = np.sin(1 * x + 2 * np.pi * i / frames) 17 | 18 | plotext.xlim(0, 10) 19 | plotext.plot(x, y, marker="dot", color="red") 20 | plotext.sleep(0.1) 21 | plotext.show() 22 | 23 | if __name__ == "__main__": 24 | main()''' 25 | 26 | #################################################### 27 | import plotext 28 | import numpy as np 29 | 30 | def main(): 31 | amplitude = 1 32 | frequency = 0.2 33 | length = 1000 34 | frames = 50 35 | 36 | plotext.title("Sine Animation") 37 | plotext.clc() 38 | 39 | for i in range(frames): 40 | plotext.clt() 41 | plotext.cld() 42 | 43 | x = np.linspace(0, 10, length) 44 | phase = 2 * np.pi * i / frames # Variamos la fase en cada frame 45 | 46 | y = amplitude * np.sin(frequency * x + phase) 47 | 48 | plotext.plot(x, y, marker="dot", color="red") 49 | plotext.ylim(-1.0, 1.0) # Limitamos el eje y a un rango fijo 50 | plotext.xlim(0, 10) # Limitamos el eje x a un rango fijo 51 | plotext.sleep(0.1) 52 | plotext.show() 53 | 54 | if __name__ == "__main__": 55 | main() 56 | -------------------------------------------------------------------------------- /sinusoid_interact.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from matplotlib.widgets import Button 4 | 5 | 6 | freqs = np.arange(2, 20, 3) 7 | 8 | fig, ax = plt.subplots() 9 | plt.subplots_adjust(bottom=0.2) 10 | t = np.arange(0.0, 1.0, 0.001) 11 | s = np.sin(2*np.pi*freqs[0]*t) 12 | l, = plt.plot(t, s, lw=2) 13 | 14 | 15 | class Index: 16 | ind = 0 17 | 18 | def next(self, event): 19 | self.ind += 1 20 | i = self.ind % len(freqs) 21 | ydata = np.sin(2*np.pi*freqs[i]*t) 22 | l.set_ydata(ydata) 23 | plt.draw() 24 | 25 | def prev(self, event): 26 | self.ind -= 1 27 | i = self.ind % len(freqs) 28 | ydata = np.sin(2*np.pi*freqs[i]*t) 29 | l.set_ydata(ydata) 30 | plt.draw() 31 | 32 | callback = Index() 33 | axprev = plt.axes([0.7, 0.05, 0.1, 0.075]) 34 | axnext = plt.axes([0.81, 0.05, 0.1, 0.075]) 35 | bnext = Button(axnext, 'Next') 36 | bnext.on_clicked(callback.next) 37 | bprev = Button(axprev, 'Previous') 38 | bprev.on_clicked(callback.prev) 39 | 40 | plt.show() 41 | -------------------------------------------------------------------------------- /sphere.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.locals import * 3 | from OpenGL.GL import * 4 | from OpenGL.GLU import * 5 | 6 | '''def draw_sphere(): 7 | glColor3f(1.0, 1.0, 1.0) # Color blanco 8 | gluSphere(gluNewQuadric(), 1, 32, 32) # Crea una esfera con radio 1''' 9 | 10 | def draw_sphere(): 11 | glColor3f(1.0, 1.0, 1.0) # Color blanco 12 | quad = gluNewQuadric() 13 | gluQuadricDrawStyle(quad, GLU_LINE) # Establecer el estilo de dibujo a líneas 14 | gluSphere(quad, 1, 32, 32) # Crea una esfera con radio 1 15 | 16 | def main(): 17 | pygame.init() 18 | display = (800, 600) 19 | pygame.display.set_mode(display, DOUBLEBUF | OPENGL) 20 | gluPerspective(45, (display[0] / display[1]), 0.1, 50.0) 21 | glTranslatef(0.0, 0.0, -5) # Mueve la esfera hacia atrás para que sea visible 22 | glRotatef(90, 1, 0, 0) 23 | glRotatef(-23, 0, 1, 0) 24 | 25 | 26 | clock = pygame.time.Clock() 27 | 28 | running = True 29 | while running: 30 | for event in pygame.event.get(): 31 | if event.type == pygame.QUIT: 32 | running = False 33 | 34 | #glRotatef(1, 3, 1, 1) # Rotación de la esfera 35 | glRotatef(1, 0, 0, 1) 36 | 37 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) 38 | draw_sphere() 39 | pygame.display.flip() 40 | clock.tick(30) 41 | 42 | pygame.quit() 43 | 44 | if __name__ == "__main__": 45 | main() 46 | -------------------------------------------------------------------------------- /square_anim.py: -------------------------------------------------------------------------------- 1 | import pygame, sys 2 | import os 3 | from pygame.locals import * 4 | 5 | os.chdir(r'') 6 | 7 | pygame.init() 8 | 9 | FPS = 30 10 | fpsClock = pygame.time.Clock() 11 | 12 | 13 | DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32) 14 | pygame.display.set_caption('Animation') 15 | 16 | WHITE = (255, 255, 255) 17 | catImg = pygame.image.load('anger_square.png') 18 | catx = 10 19 | caty = 10 20 | direction = 'right' 21 | 22 | while True: # the main game loop 23 | DISPLAYSURF.fill(WHITE) 24 | if direction == 'right': 25 | catx += 5 26 | if catx == 280: 27 | direction = 'down' 28 | elif direction == 'down': 29 | caty += 5 30 | if caty == 220: 31 | direction = 'left' 32 | elif direction == 'left': 33 | catx -= 5 34 | if catx == 10: 35 | direction = 'up' 36 | elif direction == 'up': 37 | caty -= 5 38 | if caty == 10: 39 | direction = 'right' 40 | 41 | DISPLAYSURF.blit(catImg, (catx, caty)) 42 | 43 | for event in pygame.event.get(): 44 | if event.type == QUIT: 45 | pygame.quit() 46 | sys.exit() 47 | 48 | pygame.display.update() 49 | -------------------------------------------------------------------------------- /stereo_sound_example.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.io import wavfile 3 | 4 | # Parámetros del audio 5 | frecuencia_muestreo = 44100 # Frecuencia de muestreo (44.1 kHz es estándar en audio) 6 | duracion = 0.4 # Duración en segundos 7 | frecuencia_tono = 440 # Frecuencia de la señal (por ejemplo, A4, 440 Hz) 8 | 9 | # Tiempo 10 | t = np.linspace(0, duracion, int(frecuencia_muestreo * duracion), endpoint=False) 11 | 12 | # Crear las señales para los dos canales (estéreo) 13 | canal_izquierdo = 0.5 * np.sin(2 * np.pi * frecuencia_tono * t) # Señal sinusoidal en el canal izquierdo 14 | #canal_derecho = 0.5 * np.sin(2 * np.pi * (frecuencia_tono + 100) * t) # Canal derecho con una frecuencia diferente 15 | canal_derecho = 0.5 * np.sin(2 * np.pi * frecuencia_tono * t) 16 | 17 | # Combinar los canales en un solo arreglo estéreo 18 | audio_estereo = np.column_stack((canal_izquierdo, canal_derecho)) 19 | 20 | 21 | # Convertir el audio a formato de enteros de 16 bits (WAV estándar) 22 | audio_estereo_int16 = np.int16(audio_estereo * 32767) 23 | 24 | # Guardar el archivo WAV en estéreo 25 | wavfile.write('audio_estereo.wav', frecuencia_muestreo, audio_estereo_int16) 26 | -------------------------------------------------------------------------------- /stock_graph.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import matplotlib.pyplot as plt 3 | from datetime import datetime 4 | 5 | # Definir los símbolos de las acciones de las compañías 6 | symbol1 = 'NVDA' # Nvidia 7 | symbol2 = 'MSFT' # Microsoft Corporation 8 | symbol3 = 'AMD' # AMD 9 | 10 | # Define el rango de fechas para los datos históricos 11 | start_date = '2022-01-01' 12 | end_date = datetime.today().strftime('%Y-%m-%d') # Fecha actual 13 | 14 | # Descarga los datos históricos de las acciones usando yfinance 15 | data1 = yf.download(symbol1, start=start_date, end=end_date) 16 | data2 = yf.download(symbol2, start=start_date, end=end_date) 17 | data3 = yf.download(symbol3, start=start_date, end=end_date) 18 | 19 | # Mostrar datos descargados (5 últimas líneas) 20 | print(data1.tail()) 21 | print(data1.tail()) 22 | print(data1.tail()) 23 | 24 | # Graficar la evolución del precio de las acciones 25 | plt.figure(figsize=(14, 7)) 26 | plt.plot(data1.index, data1['Adj Close'], label=symbol1) 27 | plt.plot(data2.index, data2['Adj Close'], label=symbol2) 28 | plt.plot(data3.index, data3['Adj Close'], label=symbol3) 29 | 30 | # Añadir títulos y etiquetas 31 | plt.title(f'Evolución del Precio de las Acciones de {symbol1}, {symbol2} y {symbol3}') 32 | plt.grid() 33 | plt.xlabel('Fecha') 34 | plt.ylabel('Precio de Cierre Ajustado') 35 | plt.legend() 36 | 37 | # Mostrar la gráfica 38 | plt.show() 39 | -------------------------------------------------------------------------------- /sumaColumnas_matriz.py: -------------------------------------------------------------------------------- 1 | #SUMA DE LAS COLUMNAS DE UNA MATRIZ. 2 | mat = [[5,7,8],[5,8,1],[7,8,0]] 3 | 4 | for x in range(0,3): 5 | sumaColumn = 0 6 | for y in range(0,3): 7 | sumaColumn = sumaColumn+mat[y][x] 8 | print("\nSuma de la columna "+str(x+1)+": "+str(sumaColumn)) 9 | -------------------------------------------------------------------------------- /sumaFilas_matriz.py: -------------------------------------------------------------------------------- 1 | #SUMA FILAS DE UNA MATRIZ 2 | mat = [[5,7,8],[5,8,1],[7,8,0]] 3 | 4 | for x in range(0,3): 5 | sumaFilas = 0 6 | 7 | for y in range(0,3): 8 | sumaFilas = sumaFilas + mat[x][y] 9 | print("\nSuma de la fila "+str(x+1)+": "+str(sumaFilas)) 10 | 11 | -------------------------------------------------------------------------------- /tareas_con_hilos.py: -------------------------------------------------------------------------------- 1 | import queue 2 | import threading 3 | import time 4 | 5 | # Crear una cola 6 | tareas = queue.Queue() 7 | 8 | # Función para que los trabajadores procesen la cola 9 | def procesar_tarea(): 10 | while not tareas.empty(): 11 | tarea = tareas.get() 12 | print(f"Procesando {tarea}") 13 | time.sleep(1) # Simula el tiempo de procesamiento 14 | tareas.task_done() 15 | 16 | # Agregar tareas a la cola 17 | for i in range(5): 18 | tareas.put(f"Tarea {i+1}") 19 | 20 | start_time = time.time() 21 | 22 | # Crear y lanzar múltiples hilos 23 | hilos = [] 24 | for _ in range(3): # 3 hilos procesando 25 | hilo = threading.Thread(target=procesar_tarea) 26 | hilo.start() 27 | hilos.append(hilo) 28 | 29 | # Esperar a que todos los hilos terminen 30 | for hilo in hilos: 31 | hilo.join() 32 | 33 | end_time = time.time() 34 | execution_time = end_time - start_time 35 | 36 | print(f"Todas las tareas han sido procesadas en {execution_time:.2f} segundos.") 37 | -------------------------------------------------------------------------------- /tareas_sin_hilos.py: -------------------------------------------------------------------------------- 1 | import queue 2 | import time 3 | 4 | # Crear una cola 5 | tareas = queue.Queue() 6 | 7 | # Agregar tareas a la cola 8 | for i in range(5): 9 | tareas.put(f"Tarea {i+1}") 10 | 11 | # Función para procesar tareas de manera secuencial (sin hilos) 12 | def procesar_tarea_secuencial(): 13 | while not tareas.empty(): 14 | tarea = tareas.get() 15 | print(f"Procesando {tarea}") 16 | time.sleep(1) # Simula el tiempo de procesamiento 17 | tareas.task_done() 18 | 19 | # Medir el tiempo de ejecución 20 | start_time = time.time() 21 | 22 | # Procesar las tareas de manera secuencial 23 | procesar_tarea_secuencial() 24 | 25 | end_time = time.time() 26 | 27 | # Calcular y mostrar el tiempo de ejecución total 28 | execution_time = end_time - start_time 29 | print(f"Todas las tareas han sido procesadas en {execution_time:.2f} segundos.") 30 | 31 | -------------------------------------------------------------------------------- /terminal_progress_bar.py: -------------------------------------------------------------------------------- 1 | import math 2 | from colorama import Back, init 3 | 4 | #INICIAR 'colorama' 5 | init() 6 | 7 | print("CALCULANDO FACTORIALES...") 8 | def progress_bar(progress, total): 9 | percent = 100 * (progress / float(total))#CALCULA PORCENTAJE 10 | bar = (Back.GREEN+' '+Back.RESET) * int(percent) + '-' * (100 - int(percent))#DEFINE BARRA 11 | print(f"\r|{bar}| {percent:.2f}%", end="\r")#MUESTRA BARRA + PORCENTAJE 12 | 13 | #GENERAR LISTA DE VALORES 14 | numbers = [x * 5 for x in range(2000,3000)] 15 | 16 | #RESULTADOS 17 | results = [] 18 | 19 | #REALIZAR CALCULOS. 20 | for i, x in enumerate(numbers): 21 | results.append(math.factorial(x)) 22 | progress_bar(i + 1, len(numbers))#LLAMADA A FUNCIÓN 'progress_bar()' 23 | -------------------------------------------------------------------------------- /test_normalidad.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib as mpl 4 | import scipy 5 | import matplotlib 6 | import matplotlib.pyplot as plt 7 | from scipy.stats import skew, kurtosis, chi2 8 | 9 | ''' 10 | Goal: Create a normality test e.g. Jarque-Bera 11 | 12 | step 1: generate random variables 13 | step 2: visualise histogram 14 | step 3: what is Jarque-Bera 15 | 16 | ''' 17 | 18 | # SIMULATE RANDOM VARIABLES 19 | x_size = 10**6 20 | degrees_freedom = 9 21 | type_random_variable = "normal" 22 | 23 | if type_random_variable == "normal": 24 | x = np.random.standard_normal(x_size) 25 | x_str = type_random_variable 26 | elif type_random_variable == "exponential": 27 | x = np.random.standard_exponential(x_size) 28 | x_str = type_random_variable 29 | elif type_random_variable == "normal": 30 | x = np.random.standard_t(df=degrees_freedom,size=x_size) 31 | x_str = type_random_variable + ' (df=' + str(degrees_freedom) + ')' 32 | elif type_random_variable == "chi-squared": 33 | x = np.random.chisquare(size=x_size,df=2) 34 | x_str = type_random_variable + ' (df=' + str(degrees_freedom) + ')' 35 | 36 | print(" ") 37 | # COMPUTE RISK METRICS 38 | x_mean = np.mean(x) 39 | s_stdev = np.std(x) 40 | x_skew = skew(x) 41 | x_kurt = kurtosis(x) 42 | x_median = np.percentile(x,95) 43 | x_VaR95 = np.percentile(x,5) 44 | x_cvar95 = np.mean(x[x <= x_VaR95]) 45 | x_jb = x_size/6*(x_skew**2 + 1/4*x_kurt**2) 46 | p_value = 1 - chi2.cdf(x_jb,df=degrees_freedom) 47 | is_normal = (p_value > 0.05) 48 | 49 | print("MEAN: ",x_mean) # MEDIA 50 | print("STD_DEV: ",s_stdev) # VOLATILIDAD 51 | print("SKEWNESS: ",x_skew) # SIMETRIA 52 | print("KURTOSIS: ",x_kurt) # LONG COLAS 53 | print("MEDIAN: ",x_median) # MEDIANA 54 | print("VaR95: ",x_VaR95) # VALOR EN RIESGO 55 | print("CVaR95: ",x_cvar95) # VALOR EN RIESGO CONDICIONAL 56 | print("JARQUE-BERA: ",x_jb) # NORMALIDAD 57 | print("P-VALUE: ",p_value) 58 | print("IS NORMAL: ",str(is_normal)) 59 | 60 | # PLOT HISTOGRAM 61 | plt.figure() 62 | plt.hist(x,bins=100) 63 | plt.title('Histogram ' + x_str) 64 | plt.show() 65 | 66 | -------------------------------------------------------------------------------- /testeto.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class TestStringMethods(unittest.TestCase): 4 | 5 | def test_upper(self): 6 | #COMPRUEBA SI 'foo'.upper() == 'FOO' 7 | self.assertEqual('foo'.upper(), 'FOO') 8 | 9 | def test_isupper(self): 10 | #COMPRUEBA SI ES CIERTO QUE 'FOO' ESTÁ EN MAYUSCULAS 11 | self.assertTrue('FOO'.isupper()) 12 | #COMPRUEBA SI ES FALSO QUE 'foo' ESTÁ EN MAYUSCULAS 13 | self.assertFalse('foo'.isupper()) 14 | 15 | def test_split(self): 16 | s = 'hello world' 17 | #COMPRUEBA SI 's.split() == ['hello', 'world']. 18 | self.assertEqual(s.split(), ['hello', 'world']) 19 | with self.assertRaises(TypeError): 20 | s.split(2) 21 | 22 | if __name__ == '__main__': 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /to_do.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import json 3 | 4 | def guardar_tareas(): 5 | with open("tareas.json", "w") as archivo: 6 | json.dump(tareas, archivo) 7 | 8 | def cargar_tareas(): 9 | try: 10 | with open("tareas.json", "r") as archivo: 11 | return json.load(archivo) 12 | except FileNotFoundError: 13 | return [] 14 | 15 | def agregar_tarea(): 16 | tarea = entrada_tarea.get() 17 | if tarea: 18 | lista_tareas.insert(tk.END, tarea) 19 | tareas.append(tarea) 20 | guardar_tareas() 21 | entrada_tarea.delete(0, tk.END) 22 | 23 | def eliminar_tarea(): 24 | tarea_seleccionada = lista_tareas.curselection() 25 | if tarea_seleccionada: 26 | indice = tarea_seleccionada[0] 27 | tarea_eliminada = lista_tareas.get(indice) 28 | lista_tareas.delete(indice) 29 | tareas.remove(tarea_eliminada) 30 | guardar_tareas() 31 | 32 | root = tk.Tk() 33 | root.title("Lista de Tareas") 34 | root.configure(bg="light blue") 35 | 36 | frame = tk.Frame(root) 37 | frame.pack(padx=20, pady=20) 38 | 39 | tareas = cargar_tareas() 40 | 41 | lista_tareas = tk.Listbox(frame, width=40, height=10) 42 | lista_tareas.pack(side=tk.LEFT, fill=tk.BOTH) 43 | lista_tareas.configure(selectmode='multiple') 44 | 45 | scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL) 46 | scrollbar.pack(side=tk.RIGHT, fill=tk.Y) 47 | 48 | lista_tareas.config(yscrollcommand=scrollbar.set) 49 | scrollbar.config(command=lista_tareas.yview) 50 | 51 | for tarea in tareas: 52 | lista_tareas.insert(tk.END, tarea) 53 | 54 | entrada_tarea = tk.Entry(root, width=30) 55 | entrada_tarea.pack() 56 | 57 | btn_agregar = tk.Button(root, text="Agregar tarea", width=15, bg="gray88", command=agregar_tarea) 58 | btn_agregar.pack(pady=5) 59 | 60 | btn_eliminar = tk.Button(root, text="Eliminar tarea", width=15, bg="gray88", command=eliminar_tarea) 61 | btn_eliminar.pack(pady=5) 62 | 63 | root.mainloop() 64 | -------------------------------------------------------------------------------- /to_do_app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import os 4 | import tkinter as tk 5 | from tkinter import ttk, Tk, Listbox, Canvas 6 | import json 7 | 8 | class ToDo: 9 | def __init__(self): 10 | self.root = Tk() 11 | self.root.geometry("898x600") 12 | self.root.title("To Do List") 13 | 14 | current_dir = tk.StringVar() 15 | current_dir.set(os.getcwd()) 16 | 17 | tk.Entry(self.root, textvariable=current_dir,width=149).place(x=0,y=0) 18 | self.canvas = Canvas(self.root,bg="blue")#,width=500,height=500) 19 | self.canvas.place(x=9,y=27) 20 | self.todo_list = Listbox(self.canvas,bg="gray96",width=80,height=30) 21 | self.todo_list.pack() 22 | 23 | 24 | 25 | if __name__ == "__main__": 26 | ToDo() 27 | 28 | 29 | -------------------------------------------------------------------------------- /tone.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import sounddevice as sd 3 | import time 4 | 5 | # Parámetros 6 | fs = 44100 # Frecuencia de muestreo 7 | duracion_tono = 0.5 # duración del tono (segundos) 8 | duracion_silencio = 0.1 # duración del silencio 9 | frecuencia1 = 440 # Hz 10 | frecuencia2 = 480 # Hz 11 | 12 | # Tiempo para el tono 13 | t = np.linspace(0, duracion_tono, int(fs * duracion_tono), endpoint=False) 14 | 15 | # Crear el tono combinando las dos frecuencias 16 | tono = 0.5 * (np.sin(2 * np.pi * frecuencia1 * t) + np.sin(2 * np.pi * frecuencia2 * t)) 17 | 18 | # Hacemos un bucle para sonar como un teléfono llamando 19 | num_repeticiones = 7 # cuántos "ring" quieres hacer 20 | 21 | for _ in range(num_repeticiones): 22 | # Reproducir el tono 23 | sd.play(tono, samplerate=fs) 24 | sd.wait() 25 | # Silencio 26 | time.sleep(duracion_silencio) 27 | -------------------------------------------------------------------------------- /trading_bot.py: -------------------------------------------------------------------------------- 1 | # Import packages. 2 | from tradingview_ta import TA_Handler, Interval, Exchange 3 | import time 4 | 5 | # Instantiate TA_Handler. 6 | handler = TA_Handler( 7 | symbol="META", 8 | exchange="NASDAQ", 9 | screener="america", 10 | interval=Interval.INTERVAL_1_MINUTE 11 | ) 12 | 13 | start = handler.get_analysis().summary["RECOMMENDATION"] 14 | if "BUY" in start: 15 | last_order = "buy" 16 | else: 17 | last_order = "sell" 18 | 19 | print("INITIAL RECOMMENDATION: ",last_order.upper()) 20 | time.sleep(60) 21 | 22 | # Repeat forever. 23 | count = 0 24 | while True: 25 | # Retrieve recommendation. 26 | rec = handler.get_analysis().summary["RECOMMENDATION"] 27 | 28 | # Create a buy order if the recommendation is "BUY" or "STRONG_BUY" and the last order is "sell". 29 | # Create a sell order if the recommendation is "SELL" or "STRONG_SELL" and the last order is "buy". 30 | if "BUY" in rec and last_order == "sell": 31 | # REPLACE COMMENT: Create a buy order using your exchange's API. 32 | print("RECOMMENDATION: ",rec) 33 | 34 | last_order = "buy" 35 | elif "SELL" in rec and last_order == "buy": 36 | # REPLACE COMMENT: Create a buy order using your exchange's API. 37 | print("RECOMMENDATION: ",rec) 38 | 39 | last_order = "sell" 40 | else: 41 | print("NO NEWS") 42 | count += 1 43 | if count == 4: 44 | break 45 | 46 | # Wait for x seconds before retrieving new analysis. 47 | # The time should be the same as the interval. 48 | time.sleep(60) 49 | 50 | '''Interval.INTERVAL_1_MINUTE: Representa un intervalo de 1 minuto. 51 | Interval.INTERVAL_5_MINUTES: Representa un intervalo de 5 minutos. 52 | Interval.INTERVAL_15_MINUTES: Representa un intervalo de 15 minutos. 53 | Interval.INTERVAL_1_HOUR: Representa un intervalo de 1 hora. 54 | Interval.INTERVAL_4_HOURS: Representa un intervalo de 4 horas. 55 | Interval.INTERVAL_1_DAY: Representa un intervalo de 1 día.''' 56 | -------------------------------------------------------------------------------- /turtle_art.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | WIDTH = 640 4 | HEIGHT = 360 5 | 6 | def setup_window(): 7 | turtle.title('Circles in My Mind') 8 | turtle.setup(WIDTH, HEIGHT, 0 ,0) 9 | turtle.colormode(255) 10 | 11 | turtle.hideturtle() 12 | turtle.tracer(2000) 13 | 14 | turtle.speed(10) 15 | turtle.penup() 16 | 17 | def draw_circle(x, y, radius, red=50, green=255, blue=10, width=7): 18 | colour = (red, green, blue) 19 | 20 | if radius > 50: 21 | if red < 216: 22 | red = red + 33 23 | green = green - 42 24 | blue = blue + 10 25 | width -= 1 26 | else: 27 | red = 0 28 | green = 255 29 | 30 | new_radius = int(radius / 1.3) 31 | draw_circle(int(x + new_radius), y, new_radius, red, 32 | green, blue, width) 33 | draw_circle(x - new_radius, y, new_radius, red, green, 34 | blue, width) 35 | draw_circle(x, int(y + new_radius), new_radius, red, green, 36 | blue, width) 37 | draw_circle(x, int(y - new_radius), new_radius, red, green, 38 | blue, width) 39 | 40 | turtle.goto(x, y) 41 | turtle.color(colour) 42 | turtle.width(width) 43 | turtle.pendown() 44 | turtle.circle(radius) 45 | turtle.penup() 46 | 47 | print('Starting') 48 | setup_window() 49 | draw_circle(25, -100, 200) 50 | 51 | turtle.update() 52 | print('Done') 53 | turtle.done() 54 | 55 | -------------------------------------------------------------------------------- /ur_voice.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import pyaudio 3 | import threading 4 | 5 | class App: 6 | def __init__(self): 7 | 8 | self.CHUNK = 1024#1024 9 | WIDTH = 2 10 | CHANNELS = 2 11 | RATE = 44100 12 | #RECORD_SECONDS = 10 13 | self.playing = False 14 | 15 | self.p = pyaudio.PyAudio() 16 | 17 | self.stream = self.p.open(format=self.p.get_format_from_width(WIDTH), 18 | channels=CHANNELS, 19 | rate=RATE, 20 | input=True, 21 | output=True, 22 | frames_per_buffer=self.CHUNK) 23 | 24 | 25 | 26 | self.ventana = Tk() 27 | self.ventana.geometry("480x140") 28 | 29 | self.btnPlay = Button(self.ventana,text="START DEMO",width=10,command=self.playing_state) 30 | self.btnPlay.place(x=100,y=50) 31 | 32 | self.ventana.mainloop() 33 | 34 | def playing_v(self): 35 | print("* playing") 36 | while self.playing == True: 37 | data = self.stream.read(self.CHUNK) 38 | self.stream.write(data,self.CHUNK) 39 | 40 | def playing_state(self): 41 | if self.playing == False: 42 | self.playing = True 43 | t = threading.Thread(target=self.playing_v) 44 | t.start() 45 | else: 46 | self.playing = False 47 | print("* stopped") 48 | 49 | def terminate_p(self): 50 | print("TERMINATING") 51 | self.stream.stop_stream() 52 | self.stream.close() 53 | self.p.terminate() 54 | self.t.join() 55 | 56 | 57 | def __del__(self): 58 | self.terminate_p() 59 | 60 | if __name__=="__main__": 61 | App() 62 | -------------------------------------------------------------------------------- /utilid_librosaPlot.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import librosa.display 3 | from VALID import ns 4 | import os 5 | 6 | ap = ns(input("¿Usar audio de prueba? :")) 7 | if ap == "s": 8 | audiofile = librosa.util.example_audio_file() 9 | else: 10 | os.chdir(r'C:\Users\Antonio\Documents') 11 | audiofile = input("Indicar archivo: ") 12 | 13 | y, sr = librosa.load(audiofile, duration=10) 14 | plt.figure() 15 | plt.subplot(3,1,1) 16 | librosa.display.waveplot(y, sr=sr) 17 | plt.title('Monophonic') 18 | 19 | y, sr = librosa.load(audiofile, 20 | mono = False, duration=10) 21 | plt.subplot(3,1,2) 22 | librosa.display.waveplot(y, sr=sr) 23 | plt.title('Stereo') 24 | 25 | y, sr = librosa.load(audiofile, duration=10) 26 | y_harm, y_perc = librosa.effects.hpss(y) 27 | plt.subplot(3, 1, 3) 28 | librosa.display.waveplot(y_harm, sr=sr, alpha=0.25) 29 | librosa.display.waveplot(y_perc, sr=sr, color='r', alpha=0.5) 30 | plt.title('Harmonic + Percussive') 31 | plt.tight_layout() 32 | plt.show() 33 | -------------------------------------------------------------------------------- /vectors.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | class ParOrdenado: 5 | def __init__(self,a,b): 6 | self.real = int(a) 7 | self.imaginario = int(b) 8 | 9 | def graficarComp(e): 10 | x,y = e.real, e.imaginario 11 | 12 | izda = min(-1, x-1) 13 | dcha = max(1, x+1) 14 | abjo = min(-1, y-1) 15 | arba = max(1, y+1) 16 | 17 | plt.quiver([x],[y],angles='xy',scale_units='xy',scale=1) 18 | 19 | plt.axhline(0,color='black') 20 | plt.axvline(0,color='black') 21 | 22 | plt.xlim([izda,dcha]) 23 | plt.ylim([abjo,arba]) 24 | plt.xlabel('x') 25 | plt.ylabel('y') 26 | plt.title('({},{})'.format(e.real,e.imaginario)) 27 | plt.show() 28 | 29 | ejemplo = ParOrdenado(1,2) 30 | graficarComp(ejemplo) 31 | -------------------------------------------------------------------------------- /vectors2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | class ParOrdenado: 5 | def __init__(self,a,b): 6 | self.real = int(a) 7 | self.imaginario = int(b) 8 | 9 | 10 | def graficarComp(lista, colores = ["r", "g", "b"]): 11 | x = [0]*len(lista) 12 | y = [0]*len(lista) 13 | u = [] 14 | v = [] 15 | for vector in lista: 16 | u.append(vector.real) 17 | v.append(vector.imaginario) 18 | 19 | izda = min(-1, min(u)-1) 20 | dcha = max(1, max(u)+1) 21 | abjo = min(-1, min(v)-1) 22 | arba = max(1, max(v)+1) 23 | 24 | plt.quiver(x, y, u, v, angles='xy',scale_units='xy',scale=1,color=colores) 25 | #plt.quiver([1],[1],angles='xy',scale_units='xy',scale=1) 26 | 27 | 28 | plt.axhline(0,color='black') 29 | plt.axvline(0,color='black') 30 | 31 | plt.xlim([izda,dcha]) 32 | plt.ylim([abjo,arba]) 33 | plt.xlabel('x') 34 | plt.ylabel('y') 35 | #plt.title('({},{})'.format(e.real,e.imaginario)) 36 | return plt.gca() 37 | #plt.show() 38 | 39 | x1 = ParOrdenado(1,2) 40 | x2 = ParOrdenado(-3,5) 41 | x3 = ParOrdenado(2,-5) 42 | 43 | ax = graficarComp([x1, x2, x3]) 44 | plt.show() 45 | -------------------------------------------------------------------------------- /ventana_pestañas.py: -------------------------------------------------------------------------------- 1 | #IMPORTAMOS "tkinter" 2 | from tkinter import * 3 | import tkinter 4 | from tkinter import ttk 5 | 6 | def saludo(): 7 | print("Hola ",nombre.get()) 8 | 9 | def suma5(): 10 | resultado=numero.get()+5 11 | print("RESULTADO: ",resultado) 12 | 13 | def resta5(): 14 | resultado=numero.get()-5 15 | print("RESULTADO: ",resultado) 16 | 17 | def multi5(): 18 | resultado=numero.get()*5 19 | print("RESULTADO: ",resultado) 20 | 21 | def divid5(): 22 | resultado=numero.get()/5 23 | print("RESULTADO: ",resultado) 24 | 25 | #VENTANA PRINCIPAL. 26 | root = tkinter.Tk() 27 | root.title("VENTANA CON PESTAÑAS") 28 | root.geometry("500x300") 29 | nombre = StringVar() 30 | numero = IntVar() 31 | 32 | #INCLUIMOS PANEL PARA LAS PESTAÑAS. 33 | nb = ttk.Notebook(root) 34 | nb.pack(fill='both',expand='yes') 35 | 36 | #CREAMOS PESTAÑAS 37 | p1 = ttk.Frame(nb) 38 | p2 = ttk.Frame(nb) 39 | p3 = ttk.Frame(nb) 40 | p4 = ttk.Frame(nb) 41 | p5 = ttk.Frame(nb) 42 | 43 | #ELEMENTOS PESTAÑA Saludo. 44 | Button(p1, text='Saludar',bg='light blue',command=saludo).place(x=225,y=160) 45 | Entry(p1, textvariable=nombre).place(x=190,y=70) 46 | #ELEMENTOS PESTAÑA Suma5. 47 | Button(p2, text='Suma5',bg='light blue',command=suma5).place(x=225,y=160) 48 | Entry(p2, textvariable=numero).place(x=190,y=70) 49 | #ELEMENTOS PESTAÑA Resta5. 50 | Button(p3, text='Resta5',bg='light blue',command=resta5).place(x=225,y=160) 51 | Entry(p3, textvariable=numero).place(x=190,y=70) 52 | #ELEMENTOS PESTAÑA Multi5. 53 | Button(p4, text='Multi5',bg='light blue',command=multi5).place(x=225,y=160) 54 | Entry(p4, textvariable=numero).place(x=190,y=70) 55 | #ELEMENTOS PESTAÑA Divid5. 56 | Button(p5, text='Divid5',bg='light blue',command=divid5).place(x=225,y=160) 57 | Entry(p5, textvariable=numero).place(x=190,y=70) 58 | 59 | #AGREGAMOS PESTAÑAS CREADAS 60 | nb.add(p1,text='Saludo') 61 | nb.add(p2,text='Suma5') 62 | nb.add(p3,text='Resta5') 63 | nb.add(p4,text='Multi5') 64 | nb.add(p5,text='Divid5') 65 | 66 | root.mainloop() 67 | -------------------------------------------------------------------------------- /ver_gif.py: -------------------------------------------------------------------------------- 1 | #from pyglet.window import key 2 | import pyglet 3 | 4 | 5 | animation = pyglet.image.load_animation('walk.gif') 6 | bin = pyglet.image.atlas.TextureBin() 7 | animation.add_to_texture_bin(bin) 8 | sprite = pyglet.sprite.Sprite(animation) 9 | 10 | w = sprite.width 11 | h = sprite.height 12 | 13 | window = pyglet.window.Window(width=w, height=h) 14 | 15 | @window.event 16 | def on_draw(): 17 | sprite.draw() 18 | 19 | 20 | pyglet.app.run() 21 | -------------------------------------------------------------------------------- /ver_imagen.py: -------------------------------------------------------------------------------- 1 | import pyglet 2 | window = pyglet.window.Window() 3 | image = pyglet.resource.image('robots.png') 4 | 5 | 6 | @window.event 7 | def on_draw(): 8 | window.clear() 9 | image.blit(0, 0) 10 | 11 | pyglet.app.run() 12 | -------------------------------------------------------------------------------- /vid2gif.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import ttk, filedialog, messagebox 3 | import cv2 4 | import threading 5 | from PIL import Image, ImageTk 6 | 7 | class GIFMaker(tk.Tk): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.title('GIF Maker') 13 | self.geometry('800x850') 14 | 15 | self.video_path = '' 16 | self.output_path = '' 17 | self.frames = [] 18 | self.preview_frame_index = 0 19 | 20 | self.select_video_button = tk.Button(self, text='Select Video',command=self.select_video) ) 21 | self.select_video_button.pack(paddy=10) 22 | 23 | self.preview_label = tk.Label(self, text='Video Preview') 24 | self.preview_label.pack(paddy=10) 25 | 26 | self.canvas = tk.Canvas(self, width=640, height=480, background='#eeeeee') 27 | self.canvas.pack(paddy=10) 28 | 29 | def select_video(self): 30 | pass 31 | -------------------------------------------------------------------------------- /videoCaptura_ejemplo.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | captura = cv2.VideoCapture(0) 4 | #captura = cv2.VideoCapture('videoSalida.avi') 5 | #salida=cv2.VideoWriter('videoSalida.avi',cv2.VideoWriter_fourcc(*'XVID'),20.0,(640,480)) 6 | while(captura.isOpened()): 7 | ret,imagen=captura.read() 8 | if ret==True: 9 | cv2.imshow('video',imagen) 10 | #salida.write(imagen) 11 | if cv2.waitKey(1) & 0xFF == ord('s'):#(40) 12 | break 13 | #else: 14 | #break 15 | captura.release() 16 | #salida.release() 17 | cv2.destroyAllWindows() 18 | -------------------------------------------------------------------------------- /videoToFrames.py: -------------------------------------------------------------------------------- 1 | #CREATING FRAMES FROM A VIDEO 2 | 3 | #LIBRARIES YOU NEED. 4 | import cv2 5 | import os 6 | 7 | #ENTER PATH TO VIDEO. 8 | root = input("Enter path to video: ") 9 | 10 | #READ THE VIDEO. 11 | cam = cv2.VideoCapture(root) 12 | 13 | #CREATE 'data' FOLDER IF IT NOT EXISTS. 14 | try: 15 | if not os.path.exists('data'): 16 | os.makedirs('data') 17 | 18 | except OSError: 19 | print('Error: Creating directory of data') 20 | 21 | #CREATE FRAME COUNTER. 22 | currentframe = 0 23 | 24 | while(True): 25 | #READ FROM FRAMES 26 | ret,frame = cam.read() 27 | 28 | if ret: 29 | #IF VIDEO IS STILL LETF, CONTINUE CREATING FRAMES. 30 | name = './data/frame'+str(currentframe)+'.jpg' 31 | print('Creating...'+name) 32 | 33 | #WRITE THE EXTRACTED FRAME. 34 | cv2.imwrite(name,frame) 35 | 36 | #INCREASE FRAME COUNTER. 37 | currentframe += 1 38 | else: 39 | #FINISH THE LOOP. 40 | break 41 | 42 | #FINISH THE PROGRAM. 43 | cam.release() 44 | cv2.destroyAllWindows() 45 | -------------------------------------------------------------------------------- /video_compressor.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | def reducir_tamano_video(input_path, output_path, calidad_compresion): 4 | # Abrir el video de entrada 5 | cap = cv2.VideoCapture(input_path) 6 | 7 | # Obtener información del video original 8 | fps = int(cap.get(cv2.CAP_PROP_FPS)) 9 | width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 10 | height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 11 | 12 | # Definir el codec y crear el objeto VideoWriter 13 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 14 | out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) 15 | 16 | while cap.isOpened(): 17 | ret, frame = cap.read() 18 | if not ret: 19 | break 20 | 21 | # Escribir el fotograma en el archivo de salida con la calidad de compresión especificada 22 | out.write(frame) 23 | 24 | # Liberar los recursos 25 | cap.release() 26 | out.release() 27 | 28 | # Ruta del archivo de video de entrada y salida 29 | input_path = 'video_original.avi' 30 | output_path = 'video_reducido.avi' 31 | 32 | # Calidad de compresión (rango de 0 a 100, donde 0 significa la compresión máxima) 33 | calidad_compresion = 50 # Puedes ajustar este valor según tus necesidades 34 | 35 | # Reducir el tamaño del video 36 | reducir_tamano_video(input_path, output_path, calidad_compresion) 37 | 38 | print("Video reducido generado exitosamente.") 39 | -------------------------------------------------------------------------------- /weather_app.py: -------------------------------------------------------------------------------- 1 | # Weather App 2 | # Get Your Free API : http://openweathermap.org/appid 3 | # pip install requests 4 | import requests as req 5 | from bs4 import BeautifulSoup as bs 6 | 7 | def get_weather(loc): 8 | # Set API 9 | key = "Api key" 10 | api_url = f"http://api.openweathermap.org/data/2.5/weather?" 11 | params = f"q={loc}&appid={key}" 12 | 13 | # Get the response from the API 14 | url = api_url + params 15 | response = req.get(url) 16 | weather = response.json() 17 | 18 | # Fetch Weather 19 | print(f"Weather for {loc}:") 20 | temp = weather['main']['temp'] 21 | print("Temperature:", temp - 273.15, "Celsius") 22 | humidity = weather['main']['humidity'] 23 | print("Humidity:", humidity, "%") 24 | wind = weather['wind']['speed'] 25 | print("Wind speed:", wind, "m/s") 26 | 27 | 28 | # main 29 | get_weather('London') 30 | -------------------------------------------------------------------------------- /windows_logo_turtle.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | #CREAR VENTANA 3 | t = turtle.Turtle() 4 | s = turtle.Screen() 5 | s.bgcolor("black") #COLOR FONDO 6 | t.speed(2) #VELOCIDAD 7 | #POSICIONAR PUNTERO. 8 | t.penup() 9 | t.goto(-50,60) 10 | t.pendown() 11 | t.color("#00adef") #COLOR LIÍNEA 12 | t.begin_fill() #INICIAR RELLENO 13 | t.goto(100,100) 14 | t.goto(100,-100) 15 | t.goto(-50,-60) 16 | t.goto(-50,60) 17 | t.end_fill() #FINALIZAR RELLENO 18 | #CAMBIAR COLOR Y DESPLAZAR PUNTERO 19 | t.color("black") 20 | t.goto(15,100) 21 | #CAMBIAR GROSOR LÍNEA. 22 | t.width(10) 23 | #TRAZAR NUEVA LÍNEA. 24 | t.goto(15,-100) 25 | #LINEA HORIZONTAL. 26 | t.penup() 27 | t.goto(100,0) 28 | t.pendown() 29 | t.goto(-100,0) 30 | -------------------------------------------------------------------------------- /world_population.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader.wb as wb 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | 5 | # Get a list of 2-letter country code excluding aggregates 6 | countries = wb.get_countries() 7 | countries = list(countries[countries.region != "Aggregates"]["iso2c"]) 8 | 9 | # Read countries' total population data (SP.POP.TOTL) in year 2020 10 | population_df = wb.download(indicator="SP.POP.TOTL", country=countries, start=2020, end=2020) 11 | 12 | # Sort by population, then take top 25 countries, and make the index (i.e., countries) as a column 13 | population_df = (population_df.dropna() 14 | .sort_values("SP.POP.TOTL") 15 | .iloc[-25:] 16 | .reset_index()) 17 | 18 | # Plot the population, in millions 19 | fig = plt.figure(figsize=(15,7)) 20 | plt.bar(population_df["country"], population_df["SP.POP.TOTL"]/1e6) 21 | plt.xticks(rotation=90) 22 | plt.ylabel("Million Population") 23 | plt.title("Population") 24 | plt.show() 25 | --------------------------------------------------------------------------------