ejemplo simple de una aplicación Node.js que utiliza Express.js

Aquí te proporcionaré un ejemplo simple de una aplicación Node.js que utiliza Express.js para crear un servidor web y manejar el ingreso de usuarios y contraseñas de manera básica. Para este ejemplo, utilizaremos una matriz (array) para almacenar usuarios y contraseñas en memoria, lo cual no es seguro para una aplicación en producción, pero es útil para fines de demostración.

Asegúrate de tener Node.js instalado en tu sistema antes de continuar.

1. Crea una carpeta para tu proyecto y accede a ella en tu línea de comandos:

```bash
mkdir node-login-app
cd node-login-app
```

2. Inicializa un proyecto Node.js ejecutando el siguiente comando e instalando las dependencias necesarias:

```bash
npm init -y
npm install express express-session body-parser
```

3. Crea un archivo llamado `app.js` en la carpeta de tu proyecto y agrega el siguiente código:

```javascript
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');

const app = express();

// Configurar middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
  secret: 'secret-key',
  resave: true,
  saveUninitialized: true
}));

// Datos de usuarios (en un entorno real, esto debería almacenarse de forma segura en una base de datos)
const users = [
  { username: 'usuario1', password: 'contrasena1' },
  { username: 'usuario2', password: 'contrasena2' }
];

// Rutas
app.get('/', (req, res) => {
  res.send('Bienvenido al sistema de inicio de sesión');
});

app.get('/login', (req, res) => {
  res.sendFile(__dirname + '/login.html');
});

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  
  const user = users.find(u => u.username === username && u.password === password);

  if (user) {
    req.session.loggedin = true;
    req.session.username = username;
    res.redirect('/home');
  } else {
    res.send('Credenciales incorrectas. <a href="/login">Intenta de nuevo</a>');
  }
});

app.get('/home', (req, res) => {
  if (req.session.loggedin) {
    res.send(`¡Hola, ${req.session.username}! Has iniciado sesión. <a href="/logout">Cerrar sesión</a>`);
  } else {
    res.redirect('/login');
  }
});

app.get('/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) {
      console.error(err);
    } else {
      res.redirect('/');
    }
  });
});

// Iniciar servidor
const port = 3000;
app.listen(port, () => {
  console.log(`Servidor escuchando en el puerto ${port}`);
});
```

4. Crea un archivo llamado `login.html` en la misma carpeta y agrega el siguiente código HTML para la página de inicio de sesión:

```html
<!DOCTYPE html>
<html>
<head>
  <title>Iniciar sesión</title>
</head>
<body>
  <h1>Iniciar sesión</h1>
  <form action="/login" method="POST">
    <label for="username">Usuario:</label>
    <input type="text" id="username" name="username" required><br>
    <label for="password">Contraseña:</label>
    <input type="password" id="password" name="password" required><br>
    <button type="submit">Iniciar sesión</button>
  </form>
</body>
</html>
```

5. Ejecuta la aplicación:

```bash
node app.js
```

La aplicación estará disponible en `http://localhost:3000`. Puedes acceder a la página de inicio de sesión y probar con los usuarios y contraseñas definidos en el código. Este es solo un ejemplo básico, y en una aplicación real, deberías utilizar una base de datos para almacenar y autenticar usuarios de manera segura.
En Jetpack Compose, el objeto `Modifier` proporciona una variedad de propiedades que puedes utilizar para aplicar modificadores a tus componentes de interfaz de usuario y controlar su diseño y comportamiento. A continuación, se muestran algunas de las propiedades más comunes que puedes utilizar con `Modifier`:

1. Tamaño y Diseño:
   - `size(width: Dp, height: Dp)`: Establece el ancho y el alto del componente.
   - `fillMaxWidth()`: Hace que el componente ocupe todo el ancho disponible.
   - `fillMaxHeight()`: Hace que el componente ocupe todo el alto disponible.
   - `requiredWidth(width: Dp)`: Requiere que el componente tenga un ancho específico.
   - `requiredHeight(height: Dp)`: Requiere que el componente tenga una altura específica.
   - `offset(x: Dp, y: Dp)`: Desplaza el componente en el eje X e Y.

2. Margen y Espaciado:
   - `padding(all: Dp)`: Agrega márgenes iguales en todos los lados.
   - `padding(horizontal: Dp, vertical: Dp)`: Agrega márgenes horizontales y verticales.
   - `padding(start: Dp, top: Dp, end: Dp, bottom: Dp)`: Agrega márgenes en lados específicos.

3. Alineación:
   - `align(alignment: Alignment)`: Alinea el componente dentro de su contenedor.
   - `alignBy(alignmentLine: AlignmentLine)`: Alinea el componente por una línea específica (por ejemplo, la línea base de un texto).

4. Fondo y Color:
   - `background(color: Color)`: Establece un color de fondo para el componente.
   - `border(border: BorderStroke)`: Agrega un borde al componente.

5. Interacción:
   - `clickable(onClick: () -> Unit)`: Hace que el componente sea interactivo y responde a clics.
   - `pointerInput` y `pointerInteropFilter`: Permite gestionar eventos de entrada personalizados.

6. Comportamiento Scroll:
   - `scrollable`: Hace que el componente sea desplazable.

7. Flujo de Contenido:
   - `fillMaxSize()`: Hace que el componente ocupe todo el espacio disponible en su contenedor.
   - `weight(weight: Float)`: Distribuye el espacio disponible en un `Row` o `Column` según el peso relativo.

8. Transformación y Rotación:
   - `scale(scaleX: Float, scaleY: Float)`: Escala el componente en el eje X e Y.
   - `rotate(degrees: Float)`: Rota el componente por un ángulo específico.

9. Clips y Recortes:
   - `clip(shape: Shape)`: Aplica un clip a la forma del componente.
   - `clipToBounds()`: Recorta el contenido que se desborda del componente.

10. Interacción táctil:
    - `swipeable()`: Hace que el componente sea deslizable.

Estas son solo algunas de las propiedades más comunes que puedes utilizar con `Modifier` en Jetpack Compose. Puedes combinar y anidar modificadores para lograr el diseño y el comportamiento específicos que necesites para tus componentes de interfaz de usuario. El uso de estos modificadores te permite crear interfaces de usuario flexibles y personalizadas en Compose.

------ Aquí te proporcionaré ejemplos de código para algunas de las propiedades comunes que se pueden aplicar utilizando el modificador Modifier en Jetpack Compose: Tamaño y Diseño: size(width: Dp, height: Dp):
    
        
Box(
    modifier = Modifier
        .size(100.dp, 100.dp)
        .background(Color.Blue)
) {
    // Contenido del componente
}
        
    
Margen y Espaciado: padding(all: Dp):

Box(
    modifier = Modifier
        .padding(16.dp)
        .background(Color.Green)
) {
    // Contenido del componente con margen en todos los lados
}
     
Alineación: align(alignment: Alignment):

Box(
    modifier = Modifier
        .size(100.dp, 100.dp)
        .background(Color.Red)
        .align(Alignment.Center)
) {
    // Contenido del componente alineado en el centro
}

Fondo y Color: background(color: Color):

Box(
    modifier = Modifier
        .fillMaxSize()
        .background(Color.Yellow)
) {
    // Contenido del componente con color de fondo
}

Interacción: clickable(onClick: () -> Unit):

var text by remember { mutableStateOf("Haz clic en mí") }

Box(
    modifier = Modifier
        .size(100.dp, 100.dp)
        .background(Color.Magenta)
        .clickable {
            text = "¡Haz hecho clic!"
        }
) {
    Text(text)
}

Flujo de Contenido: fillMaxSize():

Column(
    modifier = Modifier
        .fillMaxSize()
        .background(Color.Cyan)
) {
    Text("Elemento 1")
    Text("Elemento 2", modifier = Modifier.fillMaxWidth())
    Text("Elemento 3")
}

Clips y Recortes: clip(shape: Shape):

Box(
    modifier = Modifier
        .size(100.dp, 100.dp)
        .clip(RoundedCornerShape(16.dp))
        .background(Color.Orange)
) {
    // Contenido del componente con esquinas redondeadas
}

Interacción táctil: swipeable():

val swipeState = rememberSwipeableState(initialValue = 0)
Box(
    modifier = Modifier
        .size(100.dp, 100.dp)
        .background(Color.Purple)
        .swipeable(
            state = swipeState,
            anchors = mapOf(
                0f to 0,
                1000f to 1
            ),
            thresholds = { _, _ -> FractionalThreshold(0.5f) },
            orientation = Orientation.Horizontal
        )
) {
    Text("Desliza")
}

herramientas online HTML

Puedes utilizar una variedad de herramientas en línea para preparar texto, darle formato y luego obtener el código HTML resultante. Aquí hay algunas opciones populares:

Nombre URL
Dillinger [https://dillinger.io/]
StackEdit [https://stackedit.io/]
TinyMCE [https://www.tiny.cloud/]
CKEditor [https://ckeditor.com/ckeditor-4/]
Google Docs [https://docs.google.com/]
Microsoft Word Online [https://login.microsoftonline.com/]

Markdown to HTML Converters:

  • Dillinger: Dillinger es un editor en línea de Markdown que te permite escribir y dar formato a tu texto en Markdown y luego convertirlo a HTML con un solo clic.
  • StackEdit: StackEdit es un editor de Markdown en línea con una vista previa en tiempo real y la capacidad de exportar tu trabajo en HTML.

Editores en Línea con Exportación HTML:

  • TinyMCE: TinyMCE es un potente editor de texto enriquecido en línea que te permite dar formato a tu contenido y luego exportarlo como HTML.
  • CKEditor: CKEditor es otro editor enriquecido en línea con capacidades de exportación HTML.

Procesadores de Texto en Línea:

  • Google Docs: Puedes usar Google Docs para dar formato a tu texto y luego exportarlo a HTML. Ve a “Archivo” > “Descargar” > “Web Page (.html, zipped)”.
  • Microsoft Word Online: Si prefieres Microsoft Word, puedes usar Microsoft Word Online y luego descargar tu documento en formato HTML.

Editores de HTML en Línea:

  • HTML Editor Online: HTML Editor Online es un editor de HTML en línea que te permite escribir y dar formato a código HTML directamente.

Plataformas de Blogging:

Si estás escribiendo contenido para un blog, muchas plataformas de blogging como WordPress, Blogger y Medium tienen editores de texto con funciones de formato y la capacidad de publicar en formato HTML.

Conversores de Texto a HTML:

Puedes utilizar herramientas en línea como Text to HTML Converter para convertir texto sin formato en HTML.
Estas herramientas pueden ayudarte a dar formato a tu contenido de manera eficiente y luego obtener el código HTML resultante para su uso en tu sitio web o blog. Elige la que mejor se adapte a tus necesidades y preferencias.

???

https://youtube.com/shorts/6mLN39EE5hE?si=ptldeUKRZ9jqJdvK

@Preview - JetPackCompose

@Preview(showBackground = true)


@Preview(name = "Preview1", heightDp = 50, widthDp = 200, showBackground = true, showSystemUi = true)




Android - Cómo escribir mensajes de registro

La clase Log te permite crear mensajes de registro que aparecerán en Logcat. Todos los mensajes de registro de Android tienen una etiqueta y una prioridad asociadas a ellos. La etiqueta de un mensaje de registro del sistema es una string breve que indica el componente del sistema a partir del cual se origina el mensaje.

Usa los siguientes métodos de acceso, ordenados de mayor a menor prioridad:



aboutToQuit

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction
from PyQt5.QtCore import QObject, pyqtSignal

class MyMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        # Crear una acción para salir de la aplicación
        exit_action = QAction('Salir', self)
        exit_action.triggered.connect(self.close)

        # Agregar la acción al menú Archivo
        file_menu = self.menuBar().addMenu('Archivo')
        file_menu.addAction(exit_action)

    def closeEvent(self, event):
        # Se emite la señal aboutToQuit antes de salir
        self.aboutToQuit.emit()
        super().closeEvent(event)

La señal aboutToQuit se emite cuando la aplicación está a punto de salir. Puedes usar esta señal para realizar tareas de limpieza o guardar datos antes de que la aplicación se cierre. Aquí tienes un ejemplo de cómo puedes usarla:

class MyApp(QObject):
    aboutToQuit = pyqtSignal()

    def __init__(self):
        super().__init__()

        # Crear la ventana principal
        self.window = MyMainWindow()
        
        # Conectar la señal aboutToQuit de la ventana a la acción de limpieza
        self.window.aboutToQuit.connect(self.cleanUp)

    def cleanUp(self):
        # Realizar tareas de limpieza aquí antes de salir de la aplicación
        print("Tareas de limpieza realizadas antes de salir.")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    my_app = MyApp()
    sys.exit(app.exec_())


En este ejemplo, hemos creado una clase MyApp que representa una aplicación PyQt5. Hemos conectado la señal aboutToQuit de la ventana principal (MyMainWindow) a un método cleanUp en la clase MyApp. Cuando se emite la señal aboutToQuit, el método cleanUp se ejecutará, lo que te permite realizar tareas de limpieza antes de que la aplicación se cierre. En este caso, simplemente se muestra un mensaje en la consola, pero puedes agregar tus propias tareas de limpieza según tus necesidades.

QMainWindow

Un `QMainWindow` en PyQt5 puede emitir una variedad de señales que representan eventos o interacciones que ocurren en la ventana principal. Aquí hay algunas de las señales más comunes que puede emitir un `QMainWindow`:

1. `aboutToQuit`: Emitida justo antes de que la aplicación esté a punto de salir, lo que permite realizar tareas de limpieza.

2. `iconSizeChanged`: Emitida cuando cambia el tamaño de los íconos en la barra de herramientas.

3. `windowIconChanged`: Emitida cuando cambia el icono de la ventana principal.

4. `windowTitleChanged`: Emitida cuando cambia el título de la ventana principal.

5. `customContextMenuRequested`: Emitida cuando se solicita un menú contextual personalizado en la ventana.

6. `focusChanged`: Emitida cuando el foco de entrada cambia dentro de la ventana principal.

7. `statusBar().messageChanged`: Emitida cuando cambia el mensaje en la barra de estado.

8. `toolButtonStyleChanged`: Emitida cuando cambia el estilo de los botones en la barra de herramientas.

9. `navigationModeChanged`: Emitida cuando cambia el modo de navegación (por ejemplo, cambiar entre modos de navegación de pestañas y de subventanas).

10. `customContextMenuRequested`: Emitida cuando se solicita un menú contextual personalizado en la ventana.

Estas son algunas de las señales más comunes que puedes conectar a funciones o métodos personalizados para responder a eventos específicos en tu aplicación PyQt5. Puedes consultar la documentación de PyQt5 para obtener una lista completa de señales disponibles en la clase `QMainWindow` y cómo se utilizan.

conda

Cómo crear y activar entornos de conda
para listar los entornos
conda env list

para crear entorno
conda create --name prueba

para activar entorno
conda activate prueba
instalar entornos de conda
conda install --file requirements.txt
Exportar entornos de conda
conda env export > environment.yml

Recrear exactamente ese entorno en otro nuevo
conda env create -f environment.yml

instalarlas en el entorno actual
conda env update -f .\environment.yml

Clonar un entorno de conda
conda create -n miclon --clone prueba

selenium Content-Security-Policy

La Content Security Policy (Política de Seguridad de Contenido o CSP, por sus siglas en inglés) es una medida de seguridad que ayuda a prevenir ataques de inyección de código, como ataques de script entre sitios (XSS) y ataques de inyección de código malicioso (por ejemplo, inyección de JavaScript) en aplicaciones web. CSP permite a los desarrolladores especificar de qué fuentes se pueden cargar recursos (como scripts, estilos y fuentes) en una página web.

En el contexto de Selenium, puedes interactuar con la Content Security Policy en el navegador web que estás automatizando. Puedes configurar una CSP para una página web específica o trabajar con la CSP existente en el sitio web que estás probando.

Para trabajar con CSP en Selenium, aquí hay algunos pasos generales que puedes seguir:

1. **Configurar la CSP:** Si deseas configurar una CSP personalizada para una página web específica en Selenium, puedes hacerlo utilizando el método `execute_script()` para inyectar una directiva CSP en el encabezado de la página. Por ejemplo:

```python
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://tusitio.com")

# Configurar una CSP personalizada
csp_directiva = "default-src 'self'; script-src 'self' 'unsafe-inline';"
driver.execute_script(f"document.head.querySelector('meta[http-equiv=\"Content-Security-Policy\"]').setAttribute('content', '{csp_directiva}');")
```

2. **Lidiar con restricciones CSP existentes:** Si la página web que estás probando ya tiene una CSP configurada y esta CSP impide que realices ciertas acciones, como la ejecución de scripts desde dominios no permitidos, deberás trabajar dentro de las restricciones de la CSP existente. Puede requerir ajustar tu código para cumplir con las políticas de seguridad establecidas por la CSP.

3. **Verificar informes de CSP:** Algunos sitios web pueden enviar informes de violaciones de CSP a un servidor. Si estás probando un sitio que utiliza informes de CSP, asegúrate de verificar los registros de informes de violaciones para comprender si tus acciones en Selenium están generando informes de violación de CSP y cómo puedes abordarlos.

Es importante recordar que la CSP es una capa de seguridad importante en muchas aplicaciones web, y su objetivo principal es prevenir ataques de seguridad. Trabajar dentro de las restricciones de CSP es esencial para mantener la seguridad de las aplicaciones web y garantizar que las pruebas de Selenium no comprometan la seguridad del sitio.

expected_conditions esperas en selenium

selenium.webdriver.support.expected_conditions
Functions

alert_is_present() An expectation for checking if an alert is currently present and switching to it.
all_of(*expected_conditions) An expectation that all of multiple expected conditions is true.
any_of(*expected_conditions) An expectation that any of multiple expected conditions is true.
element_attribute_to_include(locator, str], …) An expectation for checking if the given attribute is included in the specified element.
element_located_selection_state_to_be(…) An expectation to locate an element and check if the selection state specified is in that state.
element_located_to_be_selected(locator, str]) An expectation for the element to be located is selected.
element_selection_state_to_be(element, …) An expectation for checking if the given element is selected.
element_to_be_clickable(mark, Tuple[str, str]]) An Expectation for checking an element is visible and enabled such that you can click it.
element_to_be_selected(element) An expectation for checking the selection is selected.
frame_to_be_available_and_switch_to_it(…) An expectation for checking whether the given frame is available to switch to.
invisibility_of_element(element, Tuple[str, …) An Expectation for checking that an element is either invisible or not present on the DOM.
invisibility_of_element_located(locator, …) An Expectation for checking that an element is either invisible or not present on the DOM.
new_window_is_opened(current_handles) An expectation that a new window will be opened and have the number of windows handles increase.
none_of(*expected_conditions) An expectation that none of 1 or multiple expected conditions is true.
number_of_windows_to_be(num_windows) An expectation for the number of windows to be a certain value.
presence_of_all_elements_located(locator, str]) An expectation for checking that there is at least one element present on a web page.
presence_of_element_located(locator, str]) An expectation for checking that an element is present on the DOM of a page.
staleness_of(element) Wait until an element is no longer attached to the DOM.
text_to_be_present_in_element(locator, str], …) An expectation for checking if the given text is present in the specified element.
text_to_be_present_in_element_attribute(…) An expectation for checking if the given text is present in the element’s attribute.
text_to_be_present_in_element_value(locator, …) An expectation for checking if the given text is present in the element’s value.
title_contains(title) An expectation for checking that the title contains a case-sensitive substring.
title_is(title) An expectation for checking the title of a page.
url_changes(url) An expectation for checking the current url.
url_contains(url) An expectation for checking that the current url contains a case- sensitive substring.
url_matches(pattern) An expectation for checking the current url.
url_to_be(url) An expectation for checking the current url.
visibility_of(element) An expectation for checking that an element, known to be present on the DOM of a page, is visible.
visibility_of_all_elements_located(locator, str]) An expectation for checking that all elements are present on the DOM of a page and visible.
visibility_of_any_elements_located(locator, str]) An expectation for checking that there is at least one element visible on a web page.
visibility_of_element_located(locator, str]) An expectation for checking that an element is present on the DOM of a page and visible.
selenium.webdriver.support.expected_conditions.AnyDriver = typing.Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]
Canned “Expected Conditions” which are generally useful within webdriver
tests.
selenium.webdriver.support.expected_conditions.alert_is_present() → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.common.alert.Alert, bool]][source]
An expectation for checking if an alert is currently present and switching to it.

selenium.webdriver.support.expected_conditions.all_of(*expected_conditions) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.remote.webelement.WebElement, bool]][source]
An expectation that all of multiple expected conditions is true.

Equivalent to a logical ‘AND’. Returns: When any ExpectedCondition is not met: False. When all ExpectedConditions are met: A List with each ExpectedCondition’s return value.

selenium.webdriver.support.expected_conditions.any_of(*expected_conditions) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.remote.webelement.WebElement, bool]][source]
An expectation that any of multiple expected conditions is true.

Equivalent to a logical ‘OR’. Returns results of the first matching condition, or False if none do.

selenium.webdriver.support.expected_conditions.element_attribute_to_include(locator: Tuple[str, str], attribute_: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking if the given attribute is included in the specified element.

locator, attribute

selenium.webdriver.support.expected_conditions.element_located_selection_state_to_be(locator: Tuple[str, str], is_selected: bool) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation to locate an element and check if the selection state specified is in that state.

locator is a tuple of (by, path) is_selected is a boolean

selenium.webdriver.support.expected_conditions.element_located_to_be_selected(locator: Tuple[str, str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for the element to be located is selected.

locator is a tuple of (by, path)

selenium.webdriver.support.expected_conditions.element_selection_state_to_be(element: selenium.webdriver.remote.webelement.WebElement, is_selected: bool) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking if the given element is selected.

element is WebElement object is_selected is a Boolean.

selenium.webdriver.support.expected_conditions.element_to_be_clickable(mark: Union[selenium.webdriver.remote.webelement.WebElement, Tuple[str, str]]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.remote.webelement.WebElement, bool]][source]
An Expectation for checking an element is visible and enabled such that you can click it.

element is either a locator (text) or an WebElement

selenium.webdriver.support.expected_conditions.element_to_be_selected(element: selenium.webdriver.remote.webelement.WebElement) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking the selection is selected.

element is WebElement object

selenium.webdriver.support.expected_conditions.frame_to_be_available_and_switch_to_it(locator: Union[Tuple[str, str], str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking whether the given frame is available to switch to.

If the frame is available it switches the given driver to the specified frame.

selenium.webdriver.support.expected_conditions.invisibility_of_element(element: Union[selenium.webdriver.remote.webelement.WebElement, Tuple[str, str]]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.remote.webelement.WebElement, bool]][source]
An Expectation for checking that an element is either invisible or not present on the DOM.

element is either a locator (text) or an WebElement

selenium.webdriver.support.expected_conditions.invisibility_of_element_located(locator: Union[selenium.webdriver.remote.webelement.WebElement, Tuple[str, str]]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.remote.webelement.WebElement, bool]][source]
An Expectation for checking that an element is either invisible or not present on the DOM.

locator used to find the element

selenium.webdriver.support.expected_conditions.new_window_is_opened(current_handles: List[str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation that a new window will be opened and have the number of windows handles increase.

selenium.webdriver.support.expected_conditions.none_of(*expected_conditions) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation that none of 1 or multiple expected conditions is true.

Equivalent to a logical ‘NOT-OR’. Returns a Boolean

selenium.webdriver.support.expected_conditions.number_of_windows_to_be(num_windows: int) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for the number of windows to be a certain value.

selenium.webdriver.support.expected_conditions.presence_of_all_elements_located(locator: Tuple[str, str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], List[selenium.webdriver.remote.webelement.WebElement]][source]
An expectation for checking that there is at least one element present on a web page.

locator is used to find the element returns the list of WebElements once they are located

selenium.webdriver.support.expected_conditions.presence_of_element_located(locator: Tuple[str, str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], selenium.webdriver.remote.webelement.WebElement][source]
An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.

locator - used to find the element returns the WebElement once it is located

selenium.webdriver.support.expected_conditions.staleness_of(element: selenium.webdriver.remote.webelement.WebElement) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
Wait until an element is no longer attached to the DOM.

element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise.

selenium.webdriver.support.expected_conditions.text_to_be_present_in_element(locator: Tuple[str, str], text_: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking if the given text is present in the specified element.

locator, text

selenium.webdriver.support.expected_conditions.text_to_be_present_in_element_attribute(locator: Tuple[str, str], attribute_: str, text_: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking if the given text is present in the element’s attribute.

locator, attribute, text

selenium.webdriver.support.expected_conditions.text_to_be_present_in_element_value(locator: Tuple[str, str], text_: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking if the given text is present in the element’s value.

locator, text

selenium.webdriver.support.expected_conditions.title_contains(title: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking that the title contains a case-sensitive substring.

title is the fragment of title expected returns True when the title matches, False otherwise

selenium.webdriver.support.expected_conditions.title_is(title: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking the title of a page.

title is the expected title, which must be an exact match returns True if the title matches, false otherwise.

selenium.webdriver.support.expected_conditions.url_changes(url: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking the current url.

url is the expected url, which must not be an exact match returns True if the url is different, false otherwise.

selenium.webdriver.support.expected_conditions.url_contains(url: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking that the current url contains a case- sensitive substring.

url is the fragment of url expected, returns True when the url matches, False otherwise

selenium.webdriver.support.expected_conditions.url_matches(pattern: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking the current url.

pattern is the expected pattern. This finds the first occurrence of pattern in the current url and as such does not require an exact full match.

selenium.webdriver.support.expected_conditions.url_to_be(url: str) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], bool][source]
An expectation for checking the current url.

url is the expected url, which must be an exact match returns True if the url matches, false otherwise.

selenium.webdriver.support.expected_conditions.visibility_of(element: selenium.webdriver.remote.webelement.WebElement) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.remote.webelement.WebElement, bool]][source]
An expectation for checking that an element, known to be present on the DOM of a page, is visible.

Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element is the WebElement returns the (same) WebElement once it is visible

selenium.webdriver.support.expected_conditions.visibility_of_all_elements_located(locator: Tuple[str, str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[bool, List[selenium.webdriver.remote.webelement.WebElement]]][source]
An expectation for checking that all elements are present on the DOM of a page and visible. Visibility means that the elements are not only displayed but also has a height and width that is greater than 0.

locator - used to find the elements returns the list of WebElements once they are located and visible

selenium.webdriver.support.expected_conditions.visibility_of_any_elements_located(locator: Tuple[str, str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], List[selenium.webdriver.remote.webelement.WebElement]][source]
An expectation for checking that there is at least one element visible on a web page.

locator is used to find the element returns the list of WebElements once they are located

selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator: Tuple[str, str]) → Callable[[Union[selenium.webdriver.chrome.webdriver.WebDriver, selenium.webdriver.firefox.webdriver.WebDriver, selenium.webdriver.safari.webdriver.WebDriver, selenium.webdriver.ie.webdriver.WebDriver, selenium.webdriver.edge.webdriver.WebDriver]], Union[selenium.webdriver.remote.webelement.WebElement, bool]][source]
An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.

locator - used to find the element returns the WebElement once it is located and visible

vender un programa

Vender un programa por mes significa ofrecer una licencia o suscripción mensual a tu software a los clientes interesados. Aquí hay algunos pasos clave que puedes seguir para vender tu programa de software de esta manera:

1. **Desarrollo del Software:**
   - Asegúrate de que tu software esté completamente desarrollado y funcional antes de ofrecerlo a los clientes.

2. **Estrategia de Precios:**
   - Decide cuánto deseas cobrar mensualmente por el acceso a tu software. Debes considerar factores como los costos de desarrollo, el valor que ofrece tu software a los usuarios y la competencia en el mercado.

3. **Modelo de Negocio:**
   - Define tu modelo de negocio. ¿Ofrecerás un período de prueba gratuito antes de que los usuarios tengan que pagar? ¿Ofrecerás diferentes niveles de suscripción con características adicionales a precios más altos?

4. **Sitio Web y Plataforma de Pago:**
   - Configura un sitio web profesional donde los clientes puedan obtener información sobre tu software, sus características y precios.
   - Implementa una plataforma de pago segura para que los clientes puedan suscribirse y realizar pagos mensuales.

5. **Soporte al Cliente:**
   - Establece un sistema de soporte al cliente eficiente para responder a preguntas, solucionar problemas técnicos y brindar asistencia a los suscriptores.

6. **Promoción y Marketing:**
   - Promociona tu software a través de diferentes canales, como redes sociales, publicidad en línea, marketing por correo electrónico y colaboraciones con otros sitios web o empresas relacionadas.

7. **Prueba Gratis:**
   - Ofrece un período de prueba gratuito para que los clientes potenciales puedan experimentar tu software antes de comprometerse con una suscripción mensual.

8. **Renovación Automática:**
   - Si es posible, configura un sistema de renovación automática para las suscripciones mensuales. Esto facilita a los clientes la continuidad de su uso y ayuda a mantener un flujo de ingresos constante.

9. **Actualizaciones y Mejoras Continuas:**
   - Continúa mejorando y actualizando tu software para mantener a los clientes interesados y satisfechos.

10. **Medir y Aprender:**
    - Utiliza herramientas de análisis para medir el rendimiento de tu software y la retención de clientes. Aprende de los datos para tomar decisiones informadas sobre precios y mejoras.

11. **Cumplimiento Legal:**
    - Asegúrate de cumplir con las leyes y regulaciones locales y regionales relacionadas con la venta de software y la privacidad de los datos.

12. **Feedback de los Usuarios:**
    - Escucha a los comentarios de los usuarios y realiza ajustes según sea necesario para mejorar la experiencia del cliente.

Vender un programa por mes puede ser una estrategia efectiva para generar ingresos recurrentes, pero también requiere un enfoque constante en la satisfacción del cliente y en la mejora continua de tu producto.

que es __main__ en python

En Python, `__main__` es un módulo especial que se utiliza para determinar si un script de Python se está ejecutando directamente o si se está importando como un módulo en otro script. Cuando un script de Python se ejecuta directamente, es decir, cuando lo ejecutas desde la línea de comandos o haciendo doble clic en él, Python establece automáticamente una variable especial llamada `__name__` en el valor `"__main__"` para ese script en particular. Esto permite que el código dentro del bloque `if __name__ == "__main__":` se ejecute solo cuando el script se ejecuta directamente, y no cuando se importa como un módulo en otro script.

Aquí hay un ejemplo para ilustrar cómo funciona:

Supongamos que tienes dos archivos de Python, `modulo.py` y `principal.py`.

Contenido de `modulo.py`:

```python
def saludar():
    print("Hola desde el módulo")

if __name__ == "__main__":
    print("Este mensaje se mostrará solo si se ejecuta directamente el módulo.py")
```

Contenido de `principal.py`:

```python
import modulo

print("Hola desde el principal.py")

modulo.saludar()
```

Cuando ejecutas `modulo.py` directamente, verás el mensaje dentro del bloque `if __name__ == "__main__":`. Pero cuando ejecutas `principal.py`, no verás ese mensaje, ya que `__name__` en `modulo.py` no será igual a `"__main__"` cuando se importe como un módulo en `principal.py`. Esto te permite tener código que se ejecuta específicamente cuando se ejecuta un script directamente y otro código que se puede reutilizar en otros scripts importando el módulo.

boton para confirmar una accion QDialog

necesito un ejemplo de pyqt5 con python donde al hacer click en un boton me salte una ventana para confirmar

import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QVBoxLayout, QLabel class ConfirmationDialog(QDialog): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('Confirmación') self.setGeometry(100, 100, 300, 100) layout = QVBoxLayout() label = QLabel('¿Estás seguro de continuar?') layout.addWidget(label) confirm_button = QPushButton('Confirmar') confirm_button.clicked.connect(self.accept) # Aceptar el cuadro de diálogo layout.addWidget(confirm_button) cancel_button = QPushButton('Cancelar') cancel_button.clicked.connect(self.reject) # Rechazar el cuadro de diálogo layout.addWidget(cancel_button) self.setLayout(layout) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('Ventana Principal') self.setGeometry(100, 100, 400, 300) self.confirmation_dialog = ConfirmationDialog() confirm_button = QPushButton('Mostrar Confirmación', self) confirm_button.setGeometry(150, 100, 150, 50) confirm_button.clicked.connect(self.show_confirmation_dialog) def show_confirmation_dialog(self): result = self.confirmation_dialog.exec_() # Mostrar el cuadro de diálogo if result == QDialog.Accepted: print('Confirmado') else: print('Cancelado') if __name__ == '__main__': app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec_())

Android Studio - Problema gradle

ir a Gradle -> a la llave -> Gradle Setting -> version 17 oracle 

luego en Try Again

test1.iss

; Script generated by the Inno Script Studio Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!

#define MyAppName "My Program"
#define MyAppVersion "1.5"
#define MyAppPublisher "My Company, Inc."
#define MyAppURL "http://www.example.com/"
#define MyAppExeName "MyProg.exe"

[Setup]
; NOTE: The value of AppId uniquely identifies this application.
; Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{39CCC315-4A77-4CC9-848E-083584C110D9}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
DefaultGroupName={#MyAppName}
OutputBaseFilename=setup
Compression=lzma
SolidCompression=yes

[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"

[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked

[Files]
Source: "C:\Program Files (x86)\Inno Setup 5\Examples\MyProg.exe"; DestDir: "{app}"; Flags: ignoreversion
; NOTE: Don't use "Flags: ignoreversion" on any shared system files

[Icons]
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon

[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent

innosetup

https://doughennig.com/papers/pub/innosetup.pdf

https://blastcoding.com/utilizando-inno-setup/

https://www.opendcl.com/tutorials/IS_Tutorial_ESM.pdf

https://sysadm.es/scripts-en-inno-setup-facilitando-tareas/

https://microsoft.public.es.vb.narkive.com/0oMe1nnb/inno-setup-ejemplos


https://www.kymoto.org/products/inno-script-studio/downloads
https://jrsoftware.org/ispphelp/index.php?topic=expressions

INDICE