Are there any good guides to programming in python for people who are already very familiar to Mathematica. I understand that for some things the canonical python approach is different and it is good to learn that from a python guide from scratch but it would also often be useful to leverage some functional programming knowledge from Mathematica when programming in Python. It would be great if there was a guide explaining similar data structures and functions and the differences you have to be careful with when coming from Mathematica. For example I would like to know whether there are things like pure functions, @
,/@
, etc., that can be used in Python.
Tag: Python
python – Confusing behavior of Tor
I am trying to use tor on Windows to access Imgur which is blocked in my country, now when I try to use Tor Browser with obfs4 everything seems fine but when I try to use only tor somehow I can access check.torproject.org or normal sites but i cant’t access imgur. I will be using tor in my python application(haven’t gotten into stem yet) and for testing if i can access imgur i have been using firefox and changing the connection settings to socks5 127.0.0.1:9050. I don’t know of anything that might cause the problem and I am in need of help. Here is my torrc:
Log notice stdout
SOCKSPort 9050
GeoIPFile C:TorDataTorgeoip
GeoIPv6File C:TorDataTorgeoip6
CookieAuthentication 1
DormantCanceledByStartup 1
AvoidDiskWrites 1
UseBridges 1
Bridge obfs4 …..
Bridge obfs4 …..
ClientTransportPlugin meek_lite,obfs2,obfs3,obfs4,scramblesuit exec C:TorTorobfs4proxy.exe
Thanks for any help
Python – Programação Orientada a Objeto – Iniciante
Eu criei um módulo com duas duas classes: Quero usar as duas como se o Mouse dependesse do Computador.
Ex.: quando utilizá-los: somente quando o Computador estiver ligado o mouse tenha permissão para ser ligado(plugado)..senão apresentar uma mensagem que ele não pode plugar…
Porém não obtive êxito como mostro no código abaixo:
Alguém pode me ajudar e me dizer onde eu errei, por gentileza?
from time import sleep
class Computador:
def __init__(self, marca, ligado=False, desligado=False):
self.marca = marca
self.ligado = ligado
self.desligado = desligado
def ligar(self):
if self.ligado:
print(f'{self.marca}, já está ligado')
return
print(f'{self.marca} está ligado')
self.ligado = True
def desligar(self):
if self.desligado:
print(f'{self.marca}, já está desligado')
return
print(f'{self.marca} está desligado')
self.desligado = True
class Mouse(Computador):
def __init__(self, marca):
super().__init__(marca)
self.marca = marca
self.plugado = False
self.desplugado = False
def plugar(self):
if not self.desligado or not self.ligado:
print(f'O {self.marca} não está conectando o mouse..')
return
print(f'{self.marca} está conectando...')
sleep(1)
print(f'{self.marca} plugando...')
sleep(2)
print('Pronto!')
sleep(1)
def desplugar(self):
return
# Essa é a Segunda Parte do Código onde estou chamando os objetos/funções:
from classes import Computador, Mouse
c1 = Computador('Dell', 'Mouse RedDragon')
m1 = Mouse('RedDragon')
print(f'Descrição: (1){c1.marca}n')
m1.plugar()
c1.ligar()
c1.desligar()
c1.desligar()
c1.ligar()
m1.plugar()
Me mostrem o que não estou fazendo de correto, por gentileza.
python – Como faço para armazenar dados e não excluir quando o programa acaba?
Como que eu faço para que quando um dado é armazenado, ele não seja excluído ao programa acabar?
por exemplo:
LISTA = ('Morango', 'Abacate')
ADD_ITEM = input('Digite algo que deseja adcionar:')
LISTA.append(ADD_ITEM)
Enquanto o programa estiver a rodar,o valor fica armazenado em LISTA
.
No entanto,ao termino do programa, o valor armazenado simplismente some.
Como devo resolver isso?
Já tentei o open
, mas como não sei usar muito bem, acabei falhando.
Já usei todo qualquer tipo de lista.
Python Sockets conexión LAN – Stack Overflow en español
hice un programa con la intención de comunicarme entre dos ordenadores de casa que usan la misma red wi-fi, haciendo un chat y usando Tkinter para la GUI.
Si no entiendo mal el ordenador que hace de server tendrá una IP del estilo “192.168…” y exactamente esa dirección es la que he de colocarle al valor de “SERVIDOR_IP” del cliente para establecer la comunicación. Pero no se logran comunicar para empezar a chatear. Si alguien me puede guiar sobre qué puede estar ocurrido, lo agradezco. Gracias de antemano!
Mi código para el servidor es el siguiente:
import socket
import threading
PUERTO = 5500
SERVIDOR_IP = socket.gethostbyname(socket.gethostname()) # dirección IP del localhost
print(SERVIDOR_IP)
FORMATO = "utf-8" # Escogemos el formato en el que se hará la codificación y la decodificación
server_address = (SERVIDOR_IP, PUERTO) # Guardamos la dirección del server en forma de tupla.
clientes = ()
nicknames = ()
# Creamos un puerto (socket) para el server:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creamos un objeto de tipo socket TCP para el servidor
server_socket.bind(server_address) # Tenemos ahora que indicar en qué puerto se va a mantener a la escucha nuestro servidor con bind
# Para sockets IP, el argumento de bind es una tupla que contiene el host y el puerto.
def broadcast(message):
''' Función para enviar mensajes a todos los clientes conectados '''
for client in clients:
client.send(message)
def inicio_conexion():
''' Creamos una función para iniciar la conexión '''
server_socket.listen()
while True:
print ('Esperando nuevas conexiones ...')
client, address = server_socket.accept() # address es la dirección IP del cliente que se quiere conectar
client.settimeout(30) # Ponemos un timeout de 30 segundos al cliente para que se conecte
client.send("NAME".encode(FORMATO))
nickname = client.recv(1024).decode(FORMATO) # máximo se pueden recibir 1024 bytes
clientes.append(client)
nicknames.append(nickname)
# Print And Broadcast Nickname
print("Nickname is {}".format(nickname))
broadcast("{} unido!".format(nickname).encode(FORMATO))
client.send('Connectado al servidor!'.encode(FORMATO))
# Start Handling Thread For Client
thread = threading.Thread(target=handle, args=(client,address))
thread.start()
def handle(cliente):
conectado = True
while conectado:
try:
mensaje = cliente.recv(1024)
broadcast(mensaje)
except:
# eliminando y cerrando a clientes
index = clientes.index(client)
clientes.remove(client)
client.close()
nickname = nicknames(index)
broadcast('{} left!'.format(nickname).encode(FORMATO))
nicknames.remove(nickname)
break
cliente.close()
inicio_conexion()
Mi código para el cliente es el siguiente:
import socket
import threading
from tkinter import * # La librería para hacer la GUI (Interfaz Gráfica de usuario)
from tkinter import ttk
PUERTO = 5050
SERVIDOR_IP = "192.168..." # Esta sería la dirección IP del servidor al que nos queremos conectar
FORMATO = "utf-8" # Escogemos el formato en el que se hará la codificación y la decodificación
server_address = (SERVIDOR_IP, PUERTO) # Guardamos la dirección del server en forma de tupla.
# Creamos un socket para el cliente y le conectamos al servidor:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(server_address)
class GUI_cliente:
def __init__(self): # Definimos el constructor de la clase
self.root = Tk() # Creamos la ventana principal (la del Chat)
self.root.withdraw() # Escondemos la ventana principal de la aplicación
''' Creamos la ventana de registro del usuario'''
self.login_window = Toplevel() # Creamos una segunda ventana que será donde se registrará el usuario
self.login_window.title("Registro")
self.login_window.resizable(False, False) # Para evitar que se pueda expandir la ventana a lo largo y a lo ancho
self.login_window.configure(width = 400, height = 200, cursor="hand2") # Especificamos las medidas de esta ventana
''' Creamos las etiqueta con los campos de registro'''
self.message = Label(self.login_window, text = "Registrate para continuar", font = ("Helvetica", 12, 'bold'), justify = CENTER)
self.message.place(relheight = 0.15, relx = 0.25, rely = 0.07) # Colocamos la etiqueta dónde nos interesa de la ventana
self.LabelUser = Label(self.login_window, text = "Nombre de usuario: ")
self.LabelUser.place(relheight = 0.2, relx = 0.1, rely = 0.3)
''' Creamos la etiqueta para poner el nombre del usuario'''
self.UserName = Entry(self.login_window)
self.UserName.place(relwidth = 0.4, relheight = 0.10, relx = 0.40, rely = 0.35)
''' Creamos el botón que nos permitirá pasar de la ventana de registro a la ventana principal del Chat Room'''
style = ttk.Style() # Para dar estilo al botón
style.map("C.TButton", foreground=(('pressed', 'red'), ('active', 'blue')), background=(('pressed', '!disabled', 'black'), ('active', 'white')))
# Con el método get obtenemos el nombre del usuario registrado:
self.button_mainWindow = ttk.Button(self.login_window, text = "Confirmar", style="C.TButton", command=lambda:self.inicio_chat(self.UserName.get()))
self.button_mainWindow.place(relx = 0.4, rely = 0.65)
self.root.mainloop()
def inicio_chat(self, nombre):
''' Esta función sirve para, una vez logeado un usuario, "destruir" la ventana de registro y abrir la ventana del chat'''
self.login_window.destroy()
self.design_mainwindow(nombre) # llamamos a la función que abre la ventana principal y la diseña
receiving = threading.Thread(target=self.receive)
receiving.start()
def design_mainwindow(self, name):
''' Esta función se encarga de diseñar la ventana principal (chat room)'''
self.name = name
self.root.deiconify() # Hacemos que aparezca de nuevo la pantalla principal creada anteriormente
self.root.title("Chat")
self.root.configure(width = 500, height = 550, cursor="hand2") # Especificamos las medidas de esta ventana y le ponemos el tipo de cursor en forma de mano
# Etiqueta que hará que aparezca nuestro nombre de usuario en la parte superior del chat room
self.LabelUser2 = Label(self.root, bg = "OliveDrab1", text = "User Name: ".format(self.name), font = ("Helvetica Neue", 16))
self.LabelUser2.place(relwidth = 1)
# Colocamos una línea de separación entre lo anterior y el chat en sí
self.linea = Label(self.root, bg = "OliveDrab4")
self.linea.place(relwidth = 1, rely = 0.06, relheight = 0.008)
# Creamos la zona dónde se van a ver los mensajes del Chat
self.texto_chat = Text(self.root, width = 20, height = 2, bg = "pale green", font = ("Calibri",12), padx = 20, pady = 20)
self.texto_chat.place(relheight = 0.75, relwidth = 1, rely = 0.07)
# Creamos la zona dónde el cliente enviará sus mensajes
self.labelBottom = Label(self.root, bg = "light grey", height = 80)
self.labelBottom.place(relwidth = 1, rely = 0.825)
# Creamos un espacio para enviar los mensajes
self.Entrar_mensaje = Entry(self.labelBottom, bg = "floralwhite", font = ("Calibri",14), justify = CENTER)
self.Entrar_mensaje.place(relwidth = 0.7, relheight = 0.055, rely = 0.012, relx = 0.025)
# Creamos el botón que nos permita enviar el mensaje escrito al chat
self.boton_sendMensaje = Button(self.labelBottom, text = "Enviar", borderwidth = 3, command = self.botonEnviar(self.Entrar_mensaje.get()))
self.boton_sendMensaje.place(relx = 0.77, rely = 0.012, relheight = 0.055, relwidth = 0.195)
# Creamos el Scrollbar para el Chat por si se envían muchos mensajes y queremos ver cualquier parte de la conversación
scrollbar = Scrollbar(self.texto_chat)
scrollbar.pack(side = RIGHT, fill = Y) # Ponemos el Scrollbar a la derecha y que llene todo el largo del chat
scrollbar.config(command = self.texto_chat.yview)
self.texto_chat.config(yscrollcommand = scrollbar.set)
def botonEnviar(self, mensaje):
self.mensaje = mensaje
self.Entrar_mensaje.delete(0,END)
snd = threading.Thread(target = self.enviar_mensaje)
snd.start()
def receive(self):
while True:
try:
message = client.recv(1024).decode(FORMATO)
if message == 'Nombre':
client.send(self.name.encode(FORMATO))
else:
self.texto_chat.insert(END,message + "nn")
except: # Cerramos la conexión cuando un error suceda
print("An error occured!")
client.close()
break
def enviar_mensaje(self):
while True:
mensaje = '{}: {}'.format(self.name, self.mensaje)
client.send(mensaje.encode(FORMATO))
break
GUI_cliente()
python 3.x – Summation of large inputs
Assume we are given $ n $ natural numbers, $a_{1}, a_{2}, dots, a_{n} $ and we are supposed to calculate the following summation:
$ sum_{i = 1}^{n}sum_{j = 1}^{n} lfloor dfrac{a_{i}}{a_{j}} rfloor$.
This is a question from a challenge and in only one test, I get time-limit exceeded error.
Can my code become faster?
Here’s the question and my code is as follows:
from collections import Counter
numbers = (int(i) for i in input().split())
sorted_numbers = sorted(Counter(numbers).items())
sigma = 0
for i in range(len(sorted_numbers)):
for j in range(i, len(sorted_numbers)):
sigma += (sorted_numbers(j)(0) // sorted_numbers(i)(0)) * sorted_numbers(j)(1) * sorted_numbers(i)(1)
print(sigma)
Discord Bot – python modificar timeout
O timeout normal é 2 segundos, e quando ativado o OnRan ele manda mensagens a cada 2 segundos, MAS o OffRan eu coloquei para o valor do timeout ser muito grande, mas mesmo assim ele ainda manda mensagens, Eu creio que seja porque o timeout apenas modifica dentro do OffRan, mesmo assim eu não tenho a mínima ideia do que fazer
@client.command(
brief='Ativa mensagens aleatorias')
async def OnRan(ctx):
while True:
await asyncio.sleep(timeout)
await ctx.send(random.choice(RandomMsg))
@client.command(
brief='Desativa mensagens aleatorias')
async def OffRan(ctx):
timeout == 9999999*9 # quase Infinito
await ctx.send('Mensagens aleatorias desativada😔👍')
#await ctx.send(file=discord.File('SourcesImagesosdevdd.jpg'))
python – QMenu en QApplication
¿Cómo puedo poner el widget QMenu en el widget QApplication? Sólo encuentro contenido en el que se pone QMenu en QMainWindow. De esta forma creo una ventana:
import sys
from PyQt5 import QtWidgets, QtCore
class QtApp():
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.setWindowTitle("Kubi Note")
window.setGeometry(0, 0, 800, 600)
window.setFixedSize(800, 600)
editor = QtWidgets.QTextEdit(window)
editor.setGeometry(10, 10, 780, 580)
window.show()
sys.exit(app.exec_())
MyApp = QtApp()
python – YouTube Data API how to extract more than 100 comments?
I am using YouTube Data API v3 to extract comments but the maximum I can get is 100 comments.
This is the code
url = "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=1000&order=relevance&videoId=cosc1UEbMbY&key=MYKEY"
data = requests.get(url).json()
comments = ()
co = 0;
for i in range(len(data('items'))):
comments.append(data('items')(i)('snippet')('topLevelComment')('snippet')('textOriginal'))
Even if I set maxResults parameter to 1000, it only returns 100 comments.
How can I fix this problem?
Thank you
stdin – convertir lista en entero python y separar pares
comanda:
cat nums.txt | python3 prueba.py > nuevonums.txt
nums.txt:
1
2
7
8
Necesito editar prueba.py
para que me tome estos números y los separe sus pares (2 y 8). Para esto habría que convertirlos a int
verdad?
Quiero hacer
IF (nom %2 == 0):
pares()
else
impar()
Lo que hice sólo toma la cadena de texto (numeros
) y los envía tal cual.
import sys
for nom in sys.stdin:
nom = nom.strip()
print(type(nom))