¿Para qué sirve y cómo funciona la palabra clave "with" en Python?

N

NPN328

He encontrado bloques de código de este tipo:

Code:
with a as b:
    c = b.algo()

Parecería alguna dinámica similar a namespaces, pero el siguiente código

Code:
a = 1
with a as b:
    print a, b

regresa el siguiente error:

Code:
AttributeError: __exit__

Entonces, ¿para qué sirve la palabra clave with, y cómo funciona? ¿Cuál es el rol de __exit__?
 

Unreplied Threads

Vba + Google Chrome

  • Vinícius Oliveira
  • Technology
  • Replies: 0
Estou com dúvidas há algum tempo e mesmo após várias pesquisas não obtive sucesso. Estou criando uma função no VBA capaz de manipular uma página da internet utilizando o Google Chrome. Apesar de setar o chrome como objeto só consigo enviar comandos "sendkeys" para o navegador e isso é complicado, pois não consigo capturar informações mas somente enviar as funções do teclado.
Minha pergunta é: Há alguma forma de utilizar o vba para capturar/enviar/manipular as páginas abertas no google chrome sem utilizar métodos sendkeys?

Почему при идентичных запросах получаю разный результат

Ребята, все приветствую, пожалуйста, объясните мне, почему эти 2 запроса возвращают разные результаты?

SELECT CASE WHEN to_char(creation_time,'Dy') IN ('Sat','Sut') THEN 'weekend' ELSE 'weekdays' END as week_part, ROUND(AVG(array_length(product_ids,1)), 2) as avg_order_size FROM orders GROUP BY week_part ORDER BY avg_order_size

SELECT case when to_char(creation_time, 'Dy') in ('Sat', 'Sun') then 'weekend' else 'weekdays' end as week_part, round(avg(array_length(product_ids, 1)), 2) as avg_order_size FROM orders GROUP BY week_part ORDER BY avg_order_size

1 -запрос возвращает это: week_part avg_order_size weekdays 3.40 weekend 3.41

2-запрос возвращает это: week_part avg_order_size weekend 3.39 weekdays 3.40

Через VS code работает, а через стандартный интерпретатор выдает ошибку

Всем добра! Написал программу. Через VS code все работает, а через стандартный интерпретатор выдает ошибку "Указанное устройство не открыто или не опознается интерфейсом MCI." Что может быть не так? Помогите, пожалуйста.

Code:
    from tkinter import *
    from playsound import playsound
    import random

    ALPHABET = {'A': "EnglishAlphabet/letter-a.wav",
        'B': "EnglishAlphabet/letter-b.mp3",
        'C': "EnglishAlphabet/letter-c.mp3",
        'D': "EnglishAlphabet/letter-d.mp3",
        'E': "EnglishAlphabet/letter-e.mp3",
        'F': "EnglishAlphabet/letter-f.mp3",
        'G': "EnglishAlphabet/letter-g.mp3",
        'H': "EnglishAlphabet/letter-h.mp3",
        'I': "EnglishAlphabet/letter-i.mp3",
        'J': "EnglishAlphabet/letter-j.mp3",
        'K': "EnglishAlphabet/letter-k.mp3",
        'L': "EnglishAlphabet/letter-l.mp3",
        'M': "EnglishAlphabet/letter-m.mp3",
        'N': "EnglishAlphabet/letter-n.mp3",
        'O': "EnglishAlphabet/letter-o.mp3",
        'P': "EnglishAlphabet/letter-p.mp3",
        'Q': "EnglishAlphabet/letter-q.mp3",
        'R': "EnglishAlphabet/letter-r.mp3",
        'S': "EnglishAlphabet/letter-s.mp3",
        'T': "EnglishAlphabet/letter-t.mp3",
        'U': "EnglishAlphabet/letter-u.mp3",
        'V': "EnglishAlphabet/letter-v.mp3",
        'W': "EnglishAlphabet/letter-w.mp3",
        'X': "EnglishAlphabet/letter-x.mp3",
        'Y': "EnglishAlphabet/letter-y.mp3",
        'Z': "EnglishAlphabet/letter-z.mp3"}
    keys = []
    values = []
    for i, j in ALPHABET.items():
        keys.append(i)
        values.append(j)

    class Word():
        def __init__(self):
            self.word = ALPHABET[random.choice(list(ALPHABET))]
            self.answer = ''

        def newWord(self):
            self.word = ALPHABET[random.choice(list(ALPHABET))]
            return self.word    
    
        def playWord(self):
            playsound(self.word)    

        def checkAnswer(self):
            self.answer = txtAnswer.get()
            if ALPHABET[self.answer.upper()] == self.word:
                result.configure(text = "Верно!")
            else:
                result.configure(text = "Ошибка!")  

    word = Word()


    window = Tk()
    window.geometry("640x480")
    btnPlay = Button(window, text = "Играть", command = word.playWord)
    txtAnswer = Entry(window, width = 5)
    btnCheckAnswer = Button(window, text = "Проверить", command = word.checkAnswer) 
    result = Label(window, text = '')
    btnNewWord = Button(window, text = "Новая буква", command = word.newWord)

    btnPlay.grid(column = 1, row = 0)
    txtAnswer.grid(column = 2, row = 0)
    btnCheckAnswer.grid(column = 3, row = 0)
    result.grid(column = 4, row = 0)
    btnNewWord.grid(column = 1, row = 1)
    window.mainloop()

multiplier with 2 binary inputs x and y, each input 3 bits, with 5 outputs

  • 4yow Faris
  • Physics
  • Replies: 0
multiplier with 2 binary inputs x and y, each input 3 bits, with 5 outputs can someone show me how it should look in Multisim I tried to do it but couldn`t do it BTW IM new to Multisim and the Digital Logic Design Thing

How to keep the voltage of an LED constant while using a MOSFET as a switch?

  • user3369353
  • Physics
  • Replies: 0
I need help with a project involving an Arduino and a high-power LED. I am using a MOSFET as a switch to control the LED, with the gate of the MOSFET connected to the output of the Arduino. The positive terminal of the LED is connected to a 12V DC power source in series with resistors, and the negative terminal is connected to the drain of the MOSFET. The source of the MOSFET is connected to the ground.

The explained configuration works and I can switch on/off the LED using the signal from the v, but the problem is that since 1 A is carrying through the system, the transistor gets hot and its on-state resistance slightly increases as a result. This will result in slightly more voltage drop across the MOSFET so that the voltage that reaches the LED slightly decreases. I have measured the change in voltage across the LED using a multimeter and it is in the range of 0.1 V. This causes a change in the illumination of the LED which is a very unwanted effect.

I am wondering if there's a way to use capacitors and/or diodes to maintain a constant voltage across the LED, despite the changing resistance of the system. I'm new to electronics and would appreciate any advice or comments, but not replacing the MOSFET, Arduino, and LEDs.

The components I'm using are:

Code:
Arduino: UNO
MOSFET: IRF620
LED: SMB1N-970

I tried to use a capacitor (100 uf) in parallel with the LED but it didn't work.

Fallo en la variable request de laravel con multiples inputs

tengo la siguiente situación en laravel: cree un formulario con un for en la vista que itera 500 veces

Code:
 @for ($i = 0; $i < 500; $i++)
  <tr id="dia_itinerario_{{ $i }}">
    <td>
          <input class="form-control" id="dia_{{ $i }}" name="dia_{{ $i }}">                          
    </td>
  </tr>

Ahora, cuando intento recuperar en el contralador, a traves de la variable request, en ella solo hay almacenado hasta la variable "dia_248". ¿ Por qué el request no almacena las 500 variables, y como puedo solucionar el problema? Gracias de antemano.

What's the best way to organize the content on this page? How do I place the different kinds of inputs and read-only values since there's so many

  • Janhavi Shah
  • Technology
  • Replies: 0
I'm redesigning a web form that users can use to create water compliance tests. The issue I'm running into is that there's a lot of information - both inputs and read-only fields that are derived from an input. What's the best way to organize this content on the screen? I have read that it's better to have a single column layout in web forms but I don't want to waste the width of the screen by having a single column. What's the optimal use of screen space in this case? I'm also wondering the best way to display read-only fields with input fields together. Any help is appreciated, thanks!

Here's a picture of the screen for reference: https://drive.google.com/file/d/1kZh2pF7h0Yz2FZWQH7JnUR_0bepVJqOQ/view?usp=sharing

Login To add answer/comment
Top