## python – El while true ejecuta solo el primer comando y no sigue indefina mente a menos que complete el segundo comando

Estoy intentando enviar datos del arduino a la raspberry le envio un caracter para prender un led y un sensor el tema es que hasta que no le envie un caracter el sensor no va estar midiendo
este es mi codigo de python

``````def SENSOR():
temperatura = temp.decode('utf-8').strip()
print(temperatura)
def led():
comando = input() #Input
arduino.write(comando.encode()) #Mandar un comando hacia Arduino
if comando == 'A':
print('LED ENCENDIDO')
elif comando == 'a':
while True:
SENSOR()
led()
``````

## nt.number theory – Is it true that \${x^4+y^2+z^2: x,y,zinmathbb Z[i]}={a+2bi: a,binmathbb Z}\$?

Recall that the ring of Gaussian integers is
$$mathbb Z(i)={a+bi: a,binmathbb Z}.$$
Clearly
$$(a+bi)^2=a^2-b^2+2abi mbox{and} (a+bi)^4=(a^2-b^2)^2-4a^2b^2+4ab(a^2-b^2)i.$$

Question. Is it true that $${x^4+y^2+z^2: x,y,zinmathbb Z(i)}={a+2bi: a,binmathbb Z}$$?

Evidence. Via Mathematica I have found that
begin{align} &{x^4+y^2+z^2: x,y,zin{r+si: r,sin{-14,ldots,14}}} \&quad supseteq{a+2bi: a,binmathbb Z mbox{and} |a+2bi|le 50}. end{align}
For example,
$$43+22i=2^4+(14-11i)^2+(11-13i)^2$$
and
$$-34+26i=(2+i)^4+(13-i)^2+(1+14i)^2=(4+i)^4+(11-11i)^2+(1+14i)^2.$$

Motivation. The question is motivated by my following result (cf. my 2017 JNT paper)
$${x^4+y^2+z^2+w^2: x,y,z,w=0,1,2,ldots}={0,1,2,ldots}$$
which refines Lagrange’s four-square theorem.

I conjecture that the question has a positive answer, but I’m unable to prove this. Your comments are welcome!

## ❓ASK – “Bitcoin used for illegal activities.” How true is this statement? | Proxies123.com

Due to the fact that bitcoin transactions cannot be tracked by government officials, people seem to criticise it’s nature by saying that it’s used by criminals for illegal purchases like to buy drugs and other stuff. This just gives a bad reputation and seems to undermine the massive benefits of using bitcoin. What are your thoughts?

## doublespend – NBitcoin – how to set RBF to true in order to give higher fee for transaction

I have a few transactions staying unconfirmed – been a few days now.

I suspect the minimum mining fee was upped – 15 minutes prior I was still doing hundreds of transactions a day at that fee – but now it is not enough.

All documentation indicates this is an easy process – simply use the same TX as you used earlier.

I am now feeling that this is more involved.

I took the unconfirmed TX – and goot its prev_hash.

I loaded the TX of this prev_hash and resubmitted it to BlockCypher – and get the message :

``````Error sending transaction: Unable to lock an input of transactions xxx, likely already spent by yyy..
``````

It correctly identifies that unconfirmed transaction in yyy placeholder.

Thus it does not want to spend it as its already spent.

Now there is a Readonly RBF property on NBitcoin.Transaction class.

RBF means “Replace by Fee” which is what I want to do – but I can’t set it as it is read only.

How do I go about to indicate this is a RBF?

## If is true f(n) = Θ(g(n)) and if f(n) = o(h(n)) then g(n) = o(h(n))?

In asymptotic notation the transivity holds, however what happens when we have small o such as if f(n)= o(h(n)) does that means that also g(n)=o(h(n)) holds?

i take as granted that both of f(n)=o(h(n)) is true and f(n)= O(g(n)) (from THETA) then i need to show
g(n) < c h(n) given that i have f(n) <= d g(n) and f(n) < c h(n) how one would proceed from there?

## Como implementar um codigo de socket em python sem usar o while true?

Estou fazendo um chat em Phyton que possui as GUIs implementadas com o Tkinter, de acordo com os erros que eu tive e pelo que eu pesquisei sobre o modulo Text do Tkinter (modulo onde serão exibidas as mensagens), eu preciso de respostas imediatas para a integração do meu sistema com os sockets do Python. Sendo assim, esse laço while True do cliente.py e do server.py seriam inviáveis. Existe outra forma de fazer essa integração sem precisar do lado cliente/servidor do socket ou sem precisar desse laço?

Tela_Chat.py

``````# Tkinter imports
from tkinter import *
import tkinter.scrolledtext as scrolledtext
from Server import *
from Cliente import *

# Funçoes imports
import random
from datetime import datetime, time

# Outros arquivos imports
from BD_chatMessages import *

# Variáveis globais
tam = "600x400"
camIco = "Iconeschat.ico"

# Classe da Janela de chat
class chatWindow():
# Função construtora da classe
def __init__(self, nome):
self.chatJanela = 0
self.textbox = 0
self.msgbox = 0
self.botaoenviar = 0
self.botaoatt = 0
self.filename = ""
self.bFrame = 0
self.data_e_hora_em_texto = 0
self.nome = nome
self.cor = "black"
self.clipPng = "Iconesclippng.png"
self.tamFrase = 0

#---------------------------MAIN------------------------------#

# Função MAIN da tela de chat => Gerencia tudo o que pode     acontecer
def chatTela(self):
# Chamada de funções de formatação
self.formata_janela()

self.botaoenviar = Button(self.bFrame, text="Enviar mensagem", command=self.envia_msgs)

self.botaoatt = Button(self.bFrame, text="Atualizarnmensagens", command=self.atualiza_textbox)

#Indica que a tela atual sempre estará em loop (comando obrigatório do Tkinter para a tela funcionar)
self.chatJanela.mainloop()

#---------------------------GERENCIAMENTO DO CHAT------------------------------#

# Método responsável por enviar a mensagem digitada diretamente para o BD
def envia_msgs(self):
msg = self.msgbox.get("1.0", "end")

# Se houver algo escrito, manda pro BD
if len(msg) > 1:
# Calcula o timestamp e apaga a caixa de texto onde o user escreveu
self.datamsg()
#self.apaga_msgbox()
self.apaga_chatbox()

# Envia pro BD
criar_tabela()
inserir_msg(self.data_e_hora_em_texto, self.nome, msg)

self.atualiza_textbox()

chamar_cliente(self.nome, msg)

# Função responsavel por atualizar o bate papo com as msgs do BD
def atualiza_textbox(self):
self.apaga_chatbox()
aux = seleciona_imprime(0)

# Formata e insere linha por linha do banco de dados no textbox
for x in aux:
self.textbox.insert(INSERT, x(0))
self.textbox.insert(INSERT, " - ")
self.textbox.insert(INSERT, x(1))
self.textbox.insert(INSERT, ": ")
self.textbox.insert(INSERT, x(2))

self.textbox.yview_moveto(1)
self.pesquisa_usuario()

# Função necessária para não permitir que o textbox seja editado
self.textbox.bind("<Key>", lambda e: "break")

# Busca o nome do usuário no textbox, marca-o com uma tag e colore seu nome
def pesquisa_usuario(self):
# Remove a tag 'found' do index 1 até o final (END)
self.textbox.tag_remove('found', '1.0', END)

# Se o usuário existir, vamos colorir seu nome
if self.nome:
# Index do começo da string no ScrooledText é sempre 1.0
idx = '1.0'
while 1:
#Encontra a string desejada a partir do index 1
idx = self.textbox.search(self.nome, idx, nocase=1, stopindex=END)

# Se não encontra a String, sai do loop
if not idx:
break

# Ultima soma de posição da posição atual e do tamanho do texto
lastidx = '%s+%dc' % (idx, len(self.nome))

# Marca a palavra encontrada com uma tag 'found'
idx = lastidx

# Marca a string encontrada com uma cor
self.textbox.tag_config('found', foreground=self.cor)

#---------------------------MÉTODOS AUXILIARES------------------------------#

# Escolhe radomicamente uma cor da lista para ser a cor daquele user
def random_colors(self, x):
cores = ("yellow","blue", "navy blue", "gold", "orange", "brown", "pink", "purple", "green", "red", "violet")
if x==0:
self.cor = random.choice(cores)
else:
return random.choice(cores)

# Calcula o timestamp da msg e retorna já formatado
def datamsg(self):
data_e_hora_atuais = datetime.now()
self.data_e_hora_em_texto = data_e_hora_atuais.strftime(
"%d/%m/%Y %H:%M:%S")

# Apaga a caixa de bate-papo (onde as mensagens são exibidas)
def apaga_chatbox(self):
#self.textbox.destroy()
self.textbox.delete(1.0, END)

# Apaga a caixa de mensagem
def apaga_msgbox(self):
self.msgbox.delete(1.0, END)

#---------------------------DESIGN & FORMATAÇÃO DA JANELA------------------------------#

# Função responsável por formatar a janela da aplicação
def formata_janela(self):
# Definiçoes iniciais
self.chatJanela = Tk()
self.chatJanela.title("Chattttô!")
self.chatJanela.wm_iconbitmap(camIco)
self.chatJanela.focus_force()
self.chatJanela.geometry(tam)

# Define a cor do usuário
self.random_colors(0)

# Tela onde aparecem as mensagens enviadas => atualiza a medida que são enviadas novas mensagens
self.textbox = scrolledtext.ScrolledText(self.chatJanela, height=15, width=80)
self.textbox.insert(1.0, "Bem Vindo ao Chattttô @" + self.nome + "!!!n")

# Esse frame é uma especie de "caixa" que posiciona elementos dentro dele com o .grid
self.bFrame = Frame(self.chatJanela)
self.bFrame.pack()

# Entrada de texto do usuário
self.msgbox = Text(self.bFrame, height=3, width=40)
self.msgbox.focus_force()

c = chatWindow("Julho")
c.chatTela()
``````

Cliente.py

``````import socket
import select
import errno, sys

IP = "127.0.0.1"
PORT = 1234

# Create a socket
# socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX
# socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to a given ip and port
client_socket.connect((IP, PORT))

# Set connection to non-blocking state, so .recv() call won;t block, just return some exception we'll handle
client_socket.setblocking(False)

# We need to encode username to bytes, then count number of bytes and prepare header of fixed size, that we encode to bytes as well

while True:

# Wait for user to input a message

# If message is not empty - send it
if message:

# Encode message to bytes, prepare header and convert to bytes, like for username above, then send
message = message.encode('utf-8')

try:
# Now we want to loop over received messages (there might be more than one) and print them
while True:

# If we received no data, server gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR)
print('Connection closed by the server')
sys.exit()

# Convert header to int value

# Now do the same for message (as we received username, we received whole message, there's no need to check if it has any length)
message = client_socket.recv(message_length).decode('utf-8')

# Print message

except IOError as e:
# This is normal on non blocking connections - when there are no incoming data error is going to be raised
# Some operating systems will indicate that using AGAIN, and some using WOULDBLOCK error code
# We are going to check for both - if one of them - that's expected, means no incoming data, continue as normal
# If we got different error code - something happened
if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
sys.exit()

# We just did not receive anything
continue

except Exception as e:
# Any other exception - something happened, exit
sys.exit()
``````

Server.py

``````import socket
import select

IP = "127.0.0.1"
PORT = 1234

# Create a socket
# socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX
# socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# SO_ - socket option
# SOL_ - socket option level
# Sets REUSEADDR (as a socket option) to 1 on socket

# Bind, so server informs operating system that it's going to use given IP and port
# For a server using 0.0.0.0 means to listen on all available interfaces, useful to connect locally to 127.0.0.1 and remotely to LAN interface IP
server_socket.bind((IP, PORT))

# This makes server listen to new connections
server_socket.listen()

# List of sockets for select.select()
sockets_list = (server_socket)

# List of connected clients - socket as a key, user header and name as data
clients = {}

print(f'Listening for connections on {IP}:{PORT}...')

# Handles message receiving

try:

# Receive our "header" containing message length, it's size is defined and constant

# If we received no data, client gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR)
return False

# Convert header to int value

# Return an object of message header and message data

except:

# If we are here, client closed connection violently, for example by pressing ctrl+c on his script
# or just lost his connection
# socket.close() also invokes socket.shutdown(socket.SHUT_RDWR) what sends information about closing the socket (shutdown read/write)
# and that's also a cause when we receive an empty message
return False

while True:

# Calls Unix select() system call or Windows select() WinSock call with three parameters:
#   - rlist - sockets to be monitored for incoming data
#   - wlist - sockets for data to be send to (checks if for example buffers are not full and socket is ready to send some data)
#   - xlist - sockets to be monitored for exceptions (we want to monitor all sockets for errors, so we can use rlist)
# Returns lists:
#   - reading - sockets we received some data on (that way we don't have to check sockets manually)
#   - writing - sockets ready for data to be send thru them
#   - errors  - sockets with some exceptions
# This is a blocking call, code execution will "wait" here and "get" notified in case any action should be taken
read_sockets, _, exception_sockets = select.select(sockets_list, (), sockets_list)

# Iterate over notified sockets

# If notified socket is a server socket - new connection, accept it
if notified_socket == server_socket:

# Accept new connection
# That gives us new socket - client socket, connected to this given client only, it's unique for that client
# The other returned object is ip/port set

# Client should send his name right away, receive it

# If False - client disconnected before he sent his name
if user is False:
continue

# Add accepted socket to select.select() list
sockets_list.append(client_socket)

clients(client_socket) = user

# Else existing socket is sending a message
else:

# If False, client disconnected, cleanup
if message is False:
print('Closed connection from: {}'.format(clients(notified_socket)('data').decode('utf-8')))

# Remove from list for socket.socket()
sockets_list.remove(notified_socket)

# Remove from our list of users
del clients(notified_socket)

continue

# Get user by notified socket, so we will know who sent the message
user = clients(notified_socket)

# Iterate over connected clients and broadcast message
for client_socket in clients:

# But don't sent it to sender
if client_socket != notified_socket:

# Send user and message (both with their headers)
# We are reusing here message header sent by sender, and saved username header send by user when he connected

# It's not really necessary to have this, but will handle some socket exceptions just in case
for notified_socket in exception_sockets:

# Remove from list for socket.socket()
sockets_list.remove(notified_socket)

# Remove from our list of users
del clients(notified_socket)
``````

## How to add value to a cell in Google sheets if a checkbox is true

I am trying to make it so that if a checkbox is checked in my first tab called ‘Tareas Semanales’ it copies a value in a cell located in my second tab. I am using the following formula: =IF(‘Tareas Semanales’!E9=TRUE ,”C4″,” “) but it keeps giving me an error. Help 🙂

## Is it true that a projective Kähler manifold of general type has a smooth canonical model and has no singular fibers?

A projective Kahler manifold $$X$$ of general type is a manifold which is projective and whose canonical bundle is big and nef. Let $$Phi: X to X_{can}$$ denote the map from $$X$$ to its canonical model. Is it true that the canonical model of $$X$$ is always smooth and $$Phi$$ has no singular fibers?

## java – Spawning two threads and if any of the threads returns true, let the main thread ignore the other and move on

Caveat: I don’t know java. Since this site is pretty low volume, figured I’d offer some thoughts anyhow.

The first function sleeps for 2 seconds, the other doesn’t. How does `Hello, world 1!` ever get done first? Or is that not what “win” means?

Looking at some doc, `isDone` doesn’t appear to block. Thus, I don’t see why your `while()` is blocking on any event. That means it’s a loop of unbounded CPU cycles, and that’s never good. At least, as I’ve seen some examples do, you should sleep a bit, perhaps some ms, before checking again. Otherwise, you’re looping and checking the results as fast as you can. That seems less than optimal.

## is duality principle in boolean algebra is true for every expression

Let say A = 1 and B = 1
and then A+B = 1
now by using duality(replacing or gate by and gate and 1 by 0) we can say that, A.B = 0
but this is not 0, because 1.1 = 1, so please anyone clear my misunderstanding here, Thank in advance