elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Temas
Páginas: [1] 2
1  Programación / Programación C/C++ / [C] [solved] Comportamiento inesperado en: 4 Abril 2022, 22:15 pm
Hola a todos.
Estoy tratando de implementar el metodo str.center() que existe en Python pero en C y de paso estoy
aprendiendo a programar en C, pero al borrar la linea que añade el carácter nulo al String resultante obtengo un resultado indeseado.

He estado dandole vueltas al asunto pero no me da el maní que tengo por cerebro, asi que acudo a ustedes en buscas de respuesta.

Muchas Gracias.


Código
  1. #include <stdio.h>
  2. #include <string.h>
  3. char* center(int, char, char *);
  4. int main()
  5. {
  6.    char* pstr = center(30, '*', "hola");
  7.    printf("Value: %s\t Address: %p\n", pstr, pstr);
  8.    return 0;
  9. }
  10.  
  11. char* center(int width, char fc, char* str) {
  12.    char output[width];
  13.    char* buffer = NULL;
  14.    int   cc = 0, n = 0;
  15.    for(char* i = str; *i != '\0'; ++i) cc += 1;
  16.    n = (width - cc) / 2;
  17.    for(int j = 0; j < n; ++j) output[j] = fc;
  18.    output[n] = '\0'; // Al borrar esta linea obtengo una salida incorrecta
  19.    strncat(output, str, cc);
  20.    for(int i = strlen(output); i < width; ++i) output[i] = fc;
  21.    return (buffer = output);
  22. }
  23.  
2  Programación / Scripting / [Python3] Me podrian explicar el funcionamiento. en: 27 Junio 2020, 04:12 am
Hola que tal a todos, me encontre este codigo y no termino de entender input.n y los demas usos
que le dan en este codigo.
Crei que era sobreescritura del metodo input pero eso solo lo he visto implementado en clases
no en funciones simples.

Gracias por sus respuestas

Código
  1.  
  2. inputs = """
  3. emanuel
  4. eduardo
  5. nuñez
  6. maliños
  7. """
  8.  
  9.  
  10. def input():
  11.    try:
  12.        input.n += 1
  13.    except Exception:
  14.        input.n = 0
  15.    return inputs.split()[input.n]
  16.  
  17.  
  18. first = input()
  19. second = input()
  20. print(first, second)
  21.  
  22.  
[/size][/size][/size][/size]
3  Programación / Scripting / [Python3-Ayuda] en: 2 Abril 2020, 02:54 am
Existe alguna de forma crear un script que se este siempre activo en espera de cambios de un directorio determinado.
Ya que quiero realizar uno en python con dicho cometido para mover los ejecutables de archivos C a una carpeta aparte de donde tengo el código de C valga la redundancia.Se que hay programas que ya lo hacen.

Que tengo que buscar ya que no se por donde empezar.
4  Programación / Scripting / [Python3-Graficador de funciones basico] en: 1 Abril 2020, 06:01 am
Hola que tal todos este es un muy simple graficador de funciones usando el módulo turtle.

Código
  1. def graficar_funciones2D(*args):
  2.    """
  3.    El primer vector se tomara como las coordenadas de inicio de la gráfica
  4.    si no las proporcionas por defecto es (0, 0).
  5.    """
  6.  
  7.    # ----------- Workspace --------------
  8.    WIDTH = 700
  9.    HEIGHT = 500
  10.    wn = Screen()
  11.    wn.title("Vectores y gráficas básicas")
  12.    wn.setup(WIDTH, HEIGHT)
  13.    wn.screensize(WIDTH-10, HEIGHT-10)
  14.    wn.bgcolor("#FFFDF9")
  15.  
  16.    pen = Turtle()
  17.    pen.pen({"pensize": 2,
  18.             "shown": False,
  19.             "speed": -1})
  20.  
  21.    # ----------- global variables --------------
  22.    dot_radio = 5
  23.    color = "red"
  24.    wn_width = wn.window_width()
  25.    wn_height = wn.window_height()
  26.  
  27.    """ # Descomenta esto si quieres ver un fondo cuadriculádo
  28.    # ----------- grid --------------
  29.    pen.pu()
  30.    pen.goto(-wn_width, wn_height)
  31.    pen.seth(0)
  32.    pen.pd()
  33.    for i in range(0, wn_height+wn_height, 10):
  34.        pen.pencolor("#daafaf")
  35.        pen.pensize(1)
  36.        pen.fd(wn_width)
  37.        pen.up()
  38.        pen.goto(-wn_width, (wn_height)-i)
  39.        pen.down()
  40.        pen.fd(wn_width)
  41.  
  42.    pen.pu()
  43.    pen.goto(-wn_width, wn_height)
  44.    pen.seth(270)
  45.    pen.pd()
  46.    for j in range(0, wn_width+wn_width, 10):
  47.        pen.fd(wn_height)
  48.        pen.up()
  49.        pen.goto(-wn_width+j, wn_height)
  50.        pen.down()
  51.        pen.fd(wn_height)
  52.    """
  53.  
  54.    # ----------- Graph --------------
  55.    pen.up()
  56.    pen.home()
  57.    pen.pencolor("#090909")
  58.    pen.pd()
  59.    for i in range(4):
  60.        pen.fd(wn_width)
  61.        pen.bk(wn_width)
  62.        pen.lt(90)
  63.  
  64.    # ----------- Points --------------
  65.    vector = args
  66.    pen.up()
  67.    pen.goto(vector[0][0], vector[0][1])
  68.    pen.pd()
  69.    for values in vector:
  70.        # pen.up()  # Descomenta esta linea si no deseas ver el trazo del dibujo
  71.        pen.goto(values[0], values[1])
  72.        # pen.pd()  # Descomenta esta linea si no deseas ver el trazo del dibujo
  73.        pen.dot(dot_radio, color)
  74.        # pen.write(tuple(values), False, "right", ("tahoma", 7, "italic"))
  75.    wn.listen()
  76.    wn.onkeypress(lambda: wn.bye(), "space")
  77.    wn.mainloop()
  78.  
  79.  
[/size][/size][/size]
5  Programación / Scripting / Python en: 17 Marzo 2020, 06:28 am
¿Es necesario usar la estructura try/except cuando envió un correo usando ssl  o simplemente cuando
utilizo tls?

¿Cuales son las convenciones a seguir al enviar correos por medio de python?

Gracias por sus respuestas!
6  Programación / Scripting / [Python3 + turtle] = Dibujo de Pacman en: 17 Marzo 2020, 04:41 am
Código
  1. from turtle import Turtle, Screen
  2.  
  3. width = 600
  4. height = 600
  5. X = width - 10
  6. Y = height - 10
  7.  
  8.  
  9. def _turtle():
  10.    # Pantalla
  11.    pantalla = Screen()
  12.    pantalla.title("Pacman")
  13.    pantalla.bgcolor("#254555")
  14.    pantalla.setup(width=width, height=height)
  15.    pantalla.colormode(255)
  16.    pantalla.screensize(X, Y)
  17.    pantalla.delay(0)
  18.  
  19.    # Tortuga
  20.    turtle = Turtle()
  21.    turtle.pensize(2)
  22.    turtle.hideturtle()
  23.    turtle.speed(0)
  24.    turtle.pu()
  25.    turtle.goto(-X/2, Y/2)
  26.    turtle.pd()
  27.    turtle.pencolor("#212140")
  28.    for i in range(91):
  29.        turtle.setheading(-i)
  30.        turtle.fd(width/2)
  31.        turtle.bk(width/2)
  32.    turtle.pu()
  33.    turtle.goto(X/2, Y/2)
  34.    turtle.pd()
  35.    for i in range(91):
  36.        turtle.setheading(i)
  37.        turtle.fd(-width/2)
  38.        turtle.bk(-width/2)
  39.  
  40.    turtle.pu()
  41.    turtle.goto(-X/2, -Y/2)
  42.    turtle.pd()
  43.    for i in range(91):
  44.        turtle.setheading(i)
  45.        turtle.fd(width/2)
  46.        turtle.bk(width/2)
  47.  
  48.    turtle.pu()
  49.    turtle.goto(X/2, -Y/2)
  50.    turtle.pd()
  51.    for i in range(91):
  52.        turtle.setheading(-i)
  53.        turtle.fd(-width/2)
  54.        turtle.bk(-width/2)
  55.    turtle.pu()
  56.    turtle.home()
  57.    turtle.pd()
  58.    for i in range(round(width/2)):
  59.        turtle.pencolor("#cfbb00")
  60.        turtle.setheading(-i)
  61.        turtle.fd(90)
  62.        turtle.bk(90)
  63.  
  64.    turtle.pu()
  65.    turtle.goto(-10, 45)
  66.    turtle.color("#001020")
  67.    turtle.pd()
  68.    turtle.begin_fill()
  69.    turtle.circle(10)
  70.    turtle.end_fill()
  71.  
  72.    pantalla.exitonclick()
  73.  
  74.  
  75. _turtle()
  76.  
  77.  
  78.  
7  Programación / Scripting / [Python3-tkinter ejemplo de calculadora] en: 8 Marzo 2020, 16:38 pm


Hola a todos aquí les dejo una calculadora sin funcionalidad.
Espero les guste o puede que no


Código
  1. from tkinter import Tk
  2. from tkinter import ttk
  3. from math import floor
  4.  
  5.  
  6. class App(ttk.Frame):
  7.    def __init__(self, master):
  8.        super().__init__(master)
  9.        self.pack()
  10.        # Variables
  11.        self.screen = None
  12.        # Metodos de clase
  13.        self.style_widgets()
  14.        self.create_widgets()
  15.  
  16.    # Estilos de los componentes del Frame
  17.    def style_widgets(self):
  18.        # estilos generales
  19.        ttk.Style().configure("TEntry", foreground="#00000a9")
  20.        ttk.Style().configure("TButton", width=10, padding=(
  21.            15, 10), relief=ttk.tkinter.FLAT)
  22.        ttk.Style().configure("E.TButton", background="#709234")
  23.        ttk.Style().configure("OP.TButton", background="#cccccc")
  24.  
  25.    def create_widgets(self):
  26.        self.screen = ttk.Entry(self)
  27.        self.screen.config(justify=ttk.tkinter.RIGHT)
  28.        self.screen.grid(row=1, column=1, ipady=20,
  29.                         columnspan=4, sticky="NSWE")
  30.  
  31.        # Crear botones
  32.        dic_buttons = {}  # diccionario de botones
  33.        for i in range(1, 13):
  34.            dic_buttons[f"btn{i}"] = ttk.Button(self, text=f"{i}")
  35.  
  36.        dic_buttons.update([("btnmul", ttk.Button(self, text="x")),
  37.                            ("btndif", ttk.Button(self, text="-")),
  38.                            ("btnplus", ttk.Button(self, text="+")),
  39.                            ("btnmod", ttk.Button(self, text="/"))])
  40.  
  41.        dic_buttons["btn9"].grid(row=2, column=1)
  42.        dic_buttons["btn8"].grid(row=2, column=2)
  43.        dic_buttons["btn7"].grid(row=2, column=3)
  44.        dic_buttons["btnmul"].grid(row=2, column=4)
  45.        dic_buttons["btn6"].grid(row=3, column=1)
  46.        dic_buttons["btn5"].grid(row=3, column=2)
  47.        dic_buttons["btn4"].grid(row=3, column=3)
  48.        dic_buttons["btndif"].grid(row=3, column=4)
  49.        dic_buttons["btn3"].grid(row=4, column=1)
  50.        dic_buttons["btn2"].grid(row=4, column=2)
  51.        dic_buttons["btn1"].grid(row=4, column=3)
  52.        dic_buttons["btnplus"].grid(row=4, column=4)
  53.        dic_buttons["btn10"].grid(row=5, column=1)
  54.        dic_buttons["btn11"].grid(row=5, column=2)
  55.        dic_buttons["btn12"].grid(row=5, column=3)
  56.        dic_buttons["btnmod"].grid(row=5, column=4)
  57.  
  58.        dic_buttons["btn10"].config(text=",")
  59.        dic_buttons["btn11"].config(text="0")
  60.        dic_buttons["btn12"].config(text="=", style="E.TButton")
  61.  
  62.        # print(dic_buttons.keys())
  63.        dic_buttons["btnmul"].config(style="OP.TButton")
  64.        dic_buttons["btndif"].config(style="OP.TButton")
  65.        dic_buttons["btnplus"].config(style="OP.TButton")
  66.        dic_buttons["btnmod"].config(style="OP.TButton")
  67.  
  68.  
  69. if __name__ == "__main__":
  70.    root = Tk()
  71.    root.resizable(False, False)
  72.    root.title("ttk Example")
  73.    app = App(root)
  74.    app.mainloop()
  75.  
  76.  
8  Programación / Scripting / [Python3] Ayuda con manipulacion de ficheros en: 1 Febrero 2020, 01:51 am
Hola a todos los que lean esto.
El siguiente script trata de automatizar el envió de correos, por medio del uso de dos ficheros.

1.carta.txt:
Estimado/a H #CLIENTE#
Tenemos noticias de que usted don/doña H #CLIENTE# no a abonado el importe
de la cuota mensual a que le obliga el draconiano contrato que firmó.

2.cliente.txt:
alguncorreo@gmail.com nombre apellido
alguncorreo@gmail.com nombre apellido

La idea es sustituir #CLIENTE# por el nombre y apellido del cliente, que es lo que ya he logrado hasta el momento y sustituir H(hombre) si esta presente o M(mujer) por su correspondiente identificativo Estimado/a y don/doña esta es la parte que aun no he podido hacer si me pudieran dar alguna idea de como optimizar y como finalizar este ejercicio se los agradeceria


Gracias por responder al final lo solucione usando expresiones regulares puede que no sea muy
eficiente pero lo logre hacer  ;D.
Este es el código

Código
  1. def envio_correo_personalizado():
  2.    try:
  3.  
  4.        # variables y apertura de ficheros
  5.        nombre = []
  6.        mensaje = ""
  7.        carta = open("carta.txt", "r")
  8.        carta_copia = open("carta.txt.copia", "w")
  9.        cliente = open("cliente.txt", "r")
  10.  
  11.        # lectura de clientes
  12.        for _cliente in cliente:
  13.            nombre += _cliente.rstrip().split("/")
  14.  
  15.        # Leyendo el fichero carta
  16.        linea = carta.readline()
  17.        while linea != "":
  18.            mensaje += linea
  19.            linea = carta.readline()
  20.  
  21.        # TODO Cambiando los valores del mensaje segun el genero usando expresiones regulares.
  22.        # FIXME Buscar otra forma de hacerlo.
  23.        mensaje = re.sub(
  24.            r"/a|/doña|H", "", mensaje) if "H" in mensaje else re.sub(r"o/|don/|M", "", mensaje)
  25.        mensaje = re.sub(r"#CLIENTE#", nombre[1], mensaje)
  26.        print("Mensaje cambiado")
  27.        print(mensaje)
  28.  
  29.        for i in mensaje:
  30.            carta_copia.write(i)
  31.  
  32.        # cierre de ficheros
  33.        carta.close()
  34.        cliente.close()
  35.        carta_copia.close()
  36.  
  37.    except IOError:
  38.        print("Fichero no existe")
  39.  
  40.  
9  Programación / Scripting / [Python3-Flask] Ayuda en: 27 Enero 2020, 02:49 am
¿Existe alguna forma enmascarar la url en flask?


Gracias por su ayuda
10  Programación / Scripting / [Python3]¿Cómo lo puedo optimizar? en: 14 Enero 2020, 03:34 am
Básicamente se trata de una guía telefónica, la cual tiene ser construida usando diccionarios esa es la restricción, en la cual se puede realizar una búsqueda por  el nombre de la persona y luego imprimir ese nombre con su respectivo número.

PERO TODO INDICA QUE LE FALTA UNA MEJOR OPTIMIZACIÓN.


Gracias por sus respuestas.

Código
  1.    def phone_book():
  2.        n = int(input())
  3.        phone_book = {}  # dictionary
  4.        for i in range(n):
  5.            string = input().split()
  6.            phone_book.update({string[0]: int(string[1])})
  7.        return phone_book
  8.  
  9.    # processing
  10.    def query(phone_book):
  11.        i = 0
  12.        while i < len(phone_book):
  13.            _query = input()
  14.            if _query in phone_book:
  15.                print(f"{_query}={phone_book[_query]}")
  16.            else:
  17.                print("Not found")
  18.            i += 1
  19.    query(phone_book())
  20.  
  21. [/
Páginas: [1] 2
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines