Frage zu Python im Editor Thonny: Optische Illusionen?

Hallo Zusammen,
wir müssen optische Illusionen mithilfe von 3 Befehlen in der Programmiersprache Python angeben. Editor wird Thonny benutzt.

Die Befehle sind:

rectangle(1,2,3,4) line (1,2,3,4) ellypse (1,2,3,4)

Damit müssen wir optische Illusionen darstellen oder zeichnen lassen.

Der Lehrer hat es uns gezeigt, wie es funktioniert am Computer. Ich habe aber keine weiteren Übungen mehr dazu und finde im Internet dazu auch keine Videos/Tutorials oder Beschreibungen.

Kennt jemand hier Unterlagen oder auch Übungen zu dem Thema? Ich besuche das Fach IMP (Informatik/Mathe/Physik) und habe bald eine Arbeit dazu. Leider haben wir schriftlich rein gar nichts. In der Arbeit bekommen wir dann eine Aufgabe zu dem Thema, die wir dann auf Papier nachbauen müssen oder erklären/verbessern müssen. Mir fällt das nicht so leicht und ich hätte gerne noch Übungsmaterial dazu. Leider kann mir der Lehrer auch nicht weiterhelfen, er sagte zu mir, dass ich es im Utnerricht ja verstanden hätte.

Bei der letzten Arbeit dachte ich das auch, jedoch war dann die Arbeit überhaupt nicht gut und ich habe es falsch gelöst. Nun möchte ich mich besser vorbereiten, habe aber kein Material und finde auch hier im Internet zu diesem Thema praktisch nichts. Kennt sich jemand damit aus und weiß, wo ich irgendwelches Material/Informationen zum Lernen/Üben bekommen könnte?

Vielen Dank und viele Grüße

Programmiersprache, Python
Wo ist der Fehler in meinem Python-Skript für Blender?
import bpy

# Funktion zum Erstellen eines Materials
def create_material(name, base_color):
  material = bpy.data.materials.new(name=name)
  material.use_nodes = True
  material.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = base_color
  return material

# Funktion zum Erstellen eines Rechtecks
def create_rectangle(name, location, scale, material):
  bpy.ops.mesh.primitive_cube_add(size=1, location=location)
  rectangle = bpy.context.active_object
  rectangle.name = name
  rectangle.scale = scale
  rectangle.data.materials.append(material)
  return rectangle

# Szene zurücksetzen
bpy.ops.wm.read_factory_settings(use_empty=True)

# Farben für die verschiedenen Seiten der Handyhülle
case_colors = [
  (1.0, 0.8, 0.6, 1.0), # Vorderseite (Beispiel: hellbraun)
  (0.8, 0.8, 0.8, 1.0), # Rückseite (Beispiel: hellgrau)
  (0.0, 0.0, 0.0, 1.0), # Seiten (Beispiel: schwarz)
]

# Farben für Graphen und PCM
graphene_color = (0.0, 1.0, 0.0, 1.0) # Grün
pcm_color = (0.0, 0.0, 1.0, 1.0) # Blau
epoxy_color = (1.0, 1.0, 1.0, 1.0) # Weiß für Epoxidharz

# Länge, Breite und Dicke der Handyhülle
length = 0.15
width = 0.07
thickness = 0.02

# Ursprungskoordinaten
origin = (0, 0, 0)

# Material für Graphen erstellen
graphene_material = create_material("Graphene_Material", graphene_color)

# Material für PCM erstellen
pcm_material = create_material("PCM_Material", pcm_color)

# Material für Epoxidharz erstellen
epoxy_material = create_material("Epoxy_Material", epoxy_color)

# Schleife zum Erstellen der Seiten der Handyhülle mit verschiedenen Farben
for i, color in enumerate(case_colors):
  # Material für die Handyhülle erstellen und zuweisen
  case_material = create_material(f"Case_Material_{i}", color)
  # Handyhüllen-Rechteck erstellen
  create_rectangle(f"HandyHuelle_{i}", origin, (length if i == 0 else width, width if i == 0 else thickness, thickness if i == 0 else width), case_material)

# Graphen in der Mitte platzieren
create_rectangle("Graphene", (origin[0] + length / 2, origin[1] + width / 2, origin[2] + thickness / 2), (width,), graphene_material)

# PCM auf der Innenseite platzieren mit Epoxidharz-Beschichtung
pcm_rectangle = create_rectangle("PCM", (origin[0] + length / 2, origin[1] + width / 2, origin[2] + thickness / 2), (width,), pcm_material)

# Material der Epoxidharz-Beschichtung zuweisen
epoxy_material_node = pcm_material.node_tree.nodes.new(type='ShaderNodeBsdfPrincipled')
epoxy_material_node.location = (-300, 0) # Position des Materialknotens für Epoxidharz
epoxy_material_node.material = bpy.data.materials.get("Epoxy_Material")

# Material der Epoxidharz-Beschichtung verbinden
pcm_material.node_tree.links.new(pcm_material.node_tree.nodes["Material Output"].inputs['Surface'], epoxy_material_node.outputs['BSDF'])

Mir fällt da an sich kein Fehler auf, aber Blender meint:

Python: Traceback (most recent call last):
  File "\Text", line 57, in <module>
  File "\Text", line 13, in create_rectangle
  AttributeError: 'Context' object has no attribute 'active_object'

Hilfe. :D

MfG aus der Nachbarschaft.

Blender 3D, Code, Programmiersprache, Python
Raspberry PI Flask-404 Not Found?

Hallo!

Ich habe das programmiert. Es wird jede Sekunde die Temperatur von der CPU ausgelesen. Jetzt möchte ich Flask einbauen, damit ich mit mehreren PC's darauf zugreifen kann. Aber es funktioniert nicht. Warum?

from flask import Flask, jsonify
import subprocess
import time
import os
from colorama import Fore, Style

app = Flask(__name__)

@app.route("/temp")
def get_cpu_temperature():
  try:
    result = subprocess.run(['vcgencmd', 'measure_temp'], capture_output=True, text=True, check=True)
    temperature_str = result.stdout.strip()
    temperature = float(temperature_str[5:-2]) # Extrahiere die Temperatur aus dem String
    return temperature
  except subprocess.CalledProcessError as e:
    print(f"Fehler beim Ausführen des Befehls: {e}")
    return None

def print_colored_temperature(temperature):
  if temperature is not None:
    if temperature > 49.9:
      print(f"{Fore.RED}Temperatur: {temperature}°C{Style.RESET_ALL}")
    else:
      print(f"Temperatur: {temperature}°C")
  else:
    print("Fehler beim Lesen der CPU-Temperatur.")

def main():
  try:
    while True:
      temperature = get_cpu_temperature()
      print_colored_temperature(temperature)
      time.sleep(1)
      os.system('clear')
  except KeyboardInterrupt:
    print("Programm wurde durch den Benutzer unterbrochen.")
  except Exception as e:
    print(f"Ein Fehler ist aufgetreten: {e}")
     
     


if __name__ == '__main__':
  app.run(host="0.0.0.0")

if __name__ == '__main__':
  main()
  import sys
  sys.exit(main(sys.argv))  
HTML, Code, Programmiersprache, Python, Python 3, Pycharm, Discord, Flask, Discord Bot, ChatGPT
Python: wann sind slice-Operationen an Arrays vorteilhaft?

Ich habe in Python versucht, eine doppelte Schleife über ein 2D Array (Variante 1) durch "array slice" Operationen (Variante 2) zu optimieren, stelle aber fest, dass dies nichts bringt, sondern die Rechenzeit sogar etwas größer wird.

Ich dachte eigentlich, dass man wo immer möglich slice Notation verwenden sollte, da dies schneller ist. Scheinbar kann man das aber nicht so einfach sagen.

Wann sind slice Operationen schneller bzw. von Vorteil? Leserlicher wid der Code ja nicht, aber dass er sogar langsamer wird überrascht mich nun doch ein wenig...

Der Code:

import numpy as np
import numpy.ma as ma
import time


def test():

 
  f = np.array([
    [0,  0,  0,  0,  0,  0,   0], 
    [0,  1,  3,  6 , 4,  2,   0], 
    [0,  2,  4,  7 , 6,  4,   0],   
    [0,  0,  0,  0,  0,  0,   0]
    ], dtype=float)
     

  u = np.array([
    [0,  0,  0,  0,  0,  0,   0], 
    [0,  0.5, 1,  0, -1, -0.5,  0], 
    [0,  0.7, 1.1, 0, -1, -0.4,  0], 
    [0,  0,  0,  0,  0,  0,   0], 
    ], dtype=float)
     
   
  # calculate : variant 1
  x = np.zeros_like(f)
   
  maxcount = 100000
   
  start = time.time()

  for count in range(maxcount):
    for i in range(1,u.shape[0]-1):
      for j in range(1,u.shape[1]-1):
        if u[i,j] > 0: 
          x[i,j] = u[i,j]*(f[i,j]-f[i,j-1])
        else:
          x[i,j] = u[i,j]*(f[i,j+1]-f[i,j])
         
  end = time.time()
  print("used time for variant 1:", end-start)
         
              
   
  # calculate : variant 2

  y = np.zeros_like(f)  

   
  start = time.time()
   
  for count in range(maxcount):
    maskl = (u[1:-1, 1:-1] > 0)
    maskr = ~maskl 
    diff = f[1:-1, 1:] - f[1:-1, 0:-1]
     
    yy = (y[1:-1, 1:-1])
    uu = (u[1:-1, 1:-1 ])
     
    yy[maskl] = uu[maskl] * (diff[:, :-1])[maskl]
    yy[maskr] = uu[maskr] * (diff[:, 1: ])[maskr]
   
  end = time.time()
  print("used time for variant 2:", end-start)
   
  np.testing.assert_array_equal(x, y)


test()

Die Ausgabe:

D:\python\animation>python test.py
used time for variant 1: 1.0328729152679443
used time for variant 2: 1.3058593273162842

D:\python\animation>python test.py
used time for variant 1: 1.1189219951629639
used time for variant 2: 1.3527190685272217

D:\python\animation>python test.py
used time for variant 1: 1.066974401473999
used time for variant 2: 1.3022441864013672
programmieren, Python, numpy, Python 3
Rechnungsproblem C# -> Python Verknüpfung?

Hallo,

ich habe folgendes Problem:

Ich habe ein ERP-Programm in C# geschrieben. Dieses funktioniert auch einwandfrei. In der Auftragsverwaltungsübersicht habe ich zwei Buttons hinzugefügt: Einmal Rechnung erstellen und einmal Angebot erstellen.

Wenn ich den Knopf Rechnung erstellen klicke, wird ein Python-Code aufgerufen, welcher die Rechnung mit den Daten automatisch erstellt.

Er zeigt immer an, Rechnung erfolgreich erstellt, allerdings erstellt er keine Rechnung bzw. er speichert keine Rechnung ab. Woran könnte das Problem denn liegen?

Hier die Methode, welche aufgerufen wird, wenn ich auf Rechnung erstellen klicke:

private void CreateInvoice(DataGridViewRow row)
{
  try
  {
    var invoiceData = new
    {
      provider_name = "Media Soft",
      provider_address = "Bahnhofstraße 40, 66639 Beispiel",
      provider_mobile = "0174 | 623 655 9",
      provider_email = "klasenjulian@web.de",
      customer_name = $"{row.Cells["Vorname"].Value} {row.Cells["Nachname"].Value}",
      customer_address_line1 = $"{row.Cells["Adresse"].Value}",
      customer_address_line2 = $"{row.Cells["PLZ"].Value} {row.Cells["Ort"].Value}",
      customer_mobile = "",
      date = DateTime.Now.ToString("dd.MM.yyyy"),
      invoice_number = row.Cells["AuftragID"].Value.ToString(),
      customer_number = "Ihre Kundennummer",
      items = new[] {
        new {
          title = row.Cells["Artikelname"].Value.ToString(),
          description = "",
          price = Convert.ToDouble(row.Cells["Einzelpreis"].Value),
          total = Convert.ToDouble(row.Cells["Gesamtpreis"].Value)
        }
      },
      total = Convert.ToDouble(row.Cells["Gesamtpreis"].Value)
    };

    string json = JsonConvert.SerializeObject(invoiceData);
    File.WriteAllText(@"C:\Projekte\rechnung\invoice_data.json", json);

    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = "python.exe";
    start.Arguments = string.Format("{0} {1}", @"C:\Projekte\rechnung\rechnung.py", @"C:\Projekte\rechnung\invoice_data.json");
    start.UseShellExecute = false;
    start.RedirectStandardOutput = true;
    start.RedirectStandardError = true;

    using (Process process = Process.Start(start))
    {
      using (StreamReader reader = process.StandardOutput)
      {
        string stderr = process.StandardError.ReadToEnd();
        string result = reader.ReadToEnd();

        if (string.IsNullOrEmpty(stderr))
        {
          MessageBox.Show("Rechnung erfolgreich erstellt!");
        }
        else
        {
          MessageBox.Show("Fehler beim Erstellen der Rechnung:\n" + stderr);
        }
      }
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show("Fehler beim Erstellung der Rechung: " + ex.Message);
  }
}

Hier der Python-Code:

  • Rechnung - Pastebin.com

Hier die Python-Daten:

  • Daten zur Projektmappe
  • Name: rechnung
  • Pfad: C:\Projekte\rechnung\rechnung.sln
  • Startprojekt: rechnung

Daten zur Projekteigenschaft:

Allgemein:

  • Arbeitsverzeichnis: .
  • Startdatei: C:\Projekte\rechnung\rechnung.py

Sonstiges:

  • Projektdatei: rechnung.pyproj
  • Projektordner: C:\Projekte\rechnung
  • Projektstartseite: C:\Projekte\rechnung
C Sharp, Programmiersprache, Python, Visual Studio
Kann jemand über den Python Code gucken?

Der Dateipfad ist definitiv richtig. Ich habe versucht, das Bild direkt in den Ordner der Python-Datei zu legen. Trotzdem tritt weiterhin der gleiche Fehler auf. Das Bild ist im richtigen Format, und ich habe keine Ahnung, was das Problem verursacht.

import logging
import pyautogui


class Coordinates:
    def __init__(self, function, image_name, confidence=0.9, region=None):
        self.function = function
        self.image_name = image_name
        self.confidence = confidence
        self.region = region


    def offset(self, x_offset=0, y_offset=0, width_offset=0, height_offset=0):
        try:
            image_path = fr'templates\{self.image_name}.png'
            location = self.function(image_path, confidence=self.confidence, region=self.region)         
            
            if len(location) == 2:
                x, y = location
                x += x_offset
                y += y_offset
                return x, y


            elif len(location) == 4:
                x, y, width, height = location
                x += x_offset
                y += y_offset
                width += width_offset
                height += height_offset
                return x, y, width, height
            
        except pyautogui.ImageNotFoundException as e:
            logging.error(f'{e}')
            return None
        
x = Coordinates(pyautogui.locateCenterOnScreen, 'test').offset()


print(x)

Bild zu Frage
Computer, Programmiersprache, Python, Python 3
was bedeuted das?
C:\Users\admin\Desktop\app> pip install turtle
Collecting turtle
 Downloading turtle-0.0.2.tar.gz (11 kB)
 Installing build dependencies ... done
 Getting requirements to build wheel ... error
 error: subprocess-exited-with-error

 × Getting requirements to build wheel did not run successfully.
 │ exit code: 1
 ╰─> [22 lines of output]
     Traceback (most recent call last):
       File "C:\Users\admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module>
         main()
       File "C:\Users\admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main
         json_out['return_val'] = hook(**hook_input['kwargs'])
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       File "C:\Users\admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 118, in get_requires_for_build_wheel
         return hook(config_settings)
                ^^^^^^^^^^^^^^^^^^^^^
       File "C:\Users\admin\AppData\Local\Temp\pip-build-env-9moh374e\overlay\Lib\site-packages\setuptools\build_meta.py", line 325, in get_requires_for_build_wheel
         return self._get_build_requires(config_settings, requirements=['wheel'])
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       File "C:\Users\admin\AppData\Local\Temp\pip-build-env-9moh374e\overlay\Lib\site-packages\setuptools\build_meta.py", line 295, in _get_build_requires
         self.run_setup()
       File "C:\Users\admin\AppData\Local\Temp\pip-build-env-9moh374e\overlay\Lib\site-packages\setuptools\build_meta.py", line 480, in run_setup
         super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script)
       File "C:\Users\admin\AppData\Local\Temp\pip-build-env-9moh374e\overlay\Lib\site-packages\setuptools\build_meta.py", line 311, in run_setup
         exec(code, locals())
       File "<string>", line 40
         except ValueError, ve:
                ^^^^^^^^^^^^^^
     SyntaxError: multiple exception types must be parenthesized
     [end of output]

 note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip
cmd, Code, Programmiersprache, Python, Python 3

Meistgelesene Fragen zum Thema Python