Developer Blog

Tipps und Tricks für Entwickler und IT-Interessierte

Vue – Cookbook

Responsive Design

React on Size Change

<script>
export default {
    data() {
        return {
            isMobile: false,
            isDesktop: false,

            windowWidth: window.innerWidth,
            windowHeight: window.innerHeight,
        };
    },

    created() {
        this.updateWindowSize();
        window.addEventListener('resize', this.updateWindowSize);
    },

    methods: {
        updateWindowSize() {
            // console.log("updateWindowSize())");

            this.windowWidth = window.innerWidth;
            this.windowHeight = window.innerHeight;
            this.checkIsMobile();
        },

        checkIsMobile() {
            this.isMobile = this.windowWidth <= 768;
            // console.log(`checkIsMobile(): windowWidth = ${this.windowWidth} isMobile=${this.isMobile}`)
        },

        beforeUnmount() {
            console.log("beforeUnmount()");

            window.removeEventListener('resize', this.updateWindowSize);
        },

    },
};
</script>

Debugging

<script setup>
import {
    onActivated,
    onBeforeMount,
    onBeforeUnmount,
    onBeforeUpdate,
    /*  onCreated, */
    onDeactivated,
    onErrorCaptured,
    onMounted,
    /*  onRenderTracked,*/
    onRenderTriggered,
    onScopeDispose,
    onServerPrefetch,
    onUnmounted,
    onUpdated,
    /*  onWatcherCleanup, */

} from 'vue';

onActivated(() => { console.log('onActivated() called'); });
onBeforeMount(() => { console.log(`onBeforeMount():`) })
onBeforeUnmount(() => { console.log('onBeforeUnmount() called'); });
onBeforeUpdate(() => { console.log(`onBeforeUpdate():`) })
onDeactivated(() => { console.log('onDeactivated() called'); });
onErrorCaptured((err, instance, info) => { console.log('onErrorCaptured() called'); console.error(err); return false; });
onMounted(() => { console.log(`onMounted():`) })
onRenderTriggered((e) => { console.log('onRenderTriggered() called', e); });
onUnmounted(() => { console.log(`onUnmounted():`) })
onUpdated(() => { console.log('onUpdated() called'); });
onScopeDispose(() => { console.log('onScopeDispose() called'); });
onServerPrefetch(() => { console.log('onServerPrefetch() called'); });

</script>

Ollama Cookbook

Setting up VS Code Environment

Debugging

Create a file launch.json and add this to configuration

"configurations": [
        {
            "name": "Streamlit",
            "type": "debugpy",
            "request": "launch",
            "module": "streamlit",
            "args": [
                "run",
                "${file}",
                "--server.port",
                "2000"
            ]
        }
    ]

Ollama und Python

Beispiele

Getting Started

Python

pip install ollama
import ollama

response = ollama.chat(model='llama2', messages=[
  {
    'role': 'user',
    'content': 'Why is the sky blue?',
  },
])

print(response['message']['content'])

JavaScript

npm install ollama
import ollama from 'ollama'

const response = await ollama.chat({
  model: 'llama2',
  messages: [{ role: 'user', content: 'Why is the sky blue?' }],
})
console.log(response.message.content)

Use cases

Both libraries support Ollama’s full set of features. Here are some examples in Python:

Streaming

for chunk in chat('mistral', messages=messages, stream=True):
    print(chunk['message']['content'], end='', flush=True)

Multi-modal

with open('image.png', 'rb') as file:
  response = ollama.chat(
    model='llava',
    messages=[
      {
        'role': 'user',
        'content': 'What is strange about this image?',
        'images': [file.read()],
      },
    ],
  )

print(response['message']['content'])

Text Completion

result = ollama.generate(
  model='stable-code',
  prompt='// A c function to reverse a string\n',
)

print(result['response'])

Creating custom models

modelfile='''
FROM llama2
SYSTEM You are mario from super mario bros.
'''

ollama.create(model='example', modelfile=modelfile)

Custom client

ollama = Client(host='my.ollama.host')

More examples are available in the GitHub repositories for the Python and JavaScript libraries.

Tipps und Tricks

ollama serve

OLLAMA_ORIGINS=https://webml-demo.vercel.app
OLLAMA_HOST=127.0.0.1:11435 ollama serve

Docker

Run Ollama in Docker container

CPU only

docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama

Nvidia GPU

Install the Nvidia container toolkit.
Run Ollama inside a Docker container

docker run -d --gpus=all -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama

Run a model

Now you can run a model like Llama 2 inside the container.

docker exec -it ollama ollama run llama2

OpenAI

OpenAI Compatibility

from openai import OpenAI

client = OpenAI(
    base_url = 'http://localhost:11434/v1',
    api_key='ollama', # required, but unused
)

response = client.chat.completions.create(
  model="llama2",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Who won the world series in 2020?"},
    {"role": "assistant", "content": "The LA Dodgers won in 2020."},
    {"role": "user", "content": "Where was it played?"}
  ]
)

print(response.choices[0].message.content)

Using Streamlit

LangChain

from langchain_community.llms import Ollama
llm = Ollama(model="gemma2")
llm.invoke("Why is the sky blue?")

LlamaIndex

from llama_index.llms.ollama import Ollama

llm = Ollama(model="gemma2")
llm.complete("Why is the sky blue?")

LLMs and Models by Example

wizard-math

ollama run wizard-math 'Expand the following expression: $7(3y+2)$'

Learning | Hello World in different Languages

Python

print("Hello, World!")

Java

public class HelloWorld {
    public static void main(String[] args) {
        System out println("Hello, World!");
    }
}

C

#include <stdio h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

C++:

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

JavaScript

console log("Hello, World!");

Ruby

puts "Hello, World!"

Swift

print("Hello, World!")

Go

package main

import "fmt"

func main() {
    fmt Println("Hello, World!")
}

Rust

fn main() {
    println!("Hello, World!");
}

PHP

<?php
echo "Hello, World!";
?>

Perl

print "Hello, World!\n";

Kotlin

fun main() {
    println("Hello, World!")
}

Scala

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello, World!")
  }
}

Lua

print("Hello, World!")

Haskell

main :: IO ()
main = putStrLn "Hello, World!"

Dart

void main() {
  print('Hello, World!');
}

Shell

echo "Hello, World!"

Batch

@echo off
echo Hello, World!

PowerShell

Write-Output "Hello, World!"

VBScript

MsgBox "Hello, World!"

Objective-C

#import <Foundation/Foundation h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"Hello, World!");
    }
    return 0;
}

Assembly

section  data
    hello db 'Hello, World!',10
    len equ $ - hello

section  text
    global _start

_start:
    ; write our string to stdout
    mov eax, 4         ; sys_write
    mov ebx, 1         ; file descriptor 1 (stdout)
    mov ecx, hello     ; message to write
    mov edx, len       ; message length
    int 0x80           ; syscall
    ; exit
    mov eax, 1         ; sys_exit
    xor ebx, ebx       ; exit status 0
    int 0x80           ; syscall

VBA (Visual Basic for Applications)

Sub HelloWorld()
    MsgBox "Hello, World!"
End Sub

Tcl

puts "Hello, World!"

COBOL

       IDENTIFICATION DIVISION 
       PROGRAM-ID  HELLO-WORLD 
       PROCEDURE DIVISION 
           DISPLAY "Hello, World!" 
           STOP RUN 

26 F#:

printfn "Hello, World!"

Elixir

IO puts "Hello, World!"

SQL (MySQL)

SELECT 'Hello, World!';

SQL (SQLite)

SELECT 'Hello, World!';

SQL (PostgreSQL)

SELECT 'Hello, World!';

SQL (Oracle)

SELECT 'Hello, World!' FROM DUAL;

SQL (SQL Server)

PRINT 'Hello, World!';

Smalltalk

Transcript show: 'Hello, World!'; cr 

R

cat("Hello, World!\n")

Bash

echo "Hello, World!"

Erlang

-module(hello) 
-export([hello_world/0]) 

hello_world() ->
    io:fwrite("Hello, World!~n") 

Julia

println("Hello, World!")

MATLAB

disp('Hello, World!');

AutoHotkey

MsgBox, Hello, World!

Clojure

(println "Hello, World!")

Groovy

println "Hello, World!"

OCaml

print_endline "Hello, World!"

D

import std stdio;

void main()
{
    writeln("Hello, World!");
}

Crystal

puts "Hello, World!"

Nim

echo "Hello, World!"

Common Lisp

(format t "Hello, World!



Scheme

(display "Hello, World!")
(newline)

Prolog

:- initialization(main) 

main :-
    write('Hello, World!'), nl,
    halt 

ABAP

REPORT ZHELLO_WORLD 

WRITE: / 'Hello, World!' 

VB NET

vb net
Module HelloWorld
    Sub Main()
        Console WriteLine("Hello, World!")
    End Sub
End Module 

AI Environment | Writing Apps for OpenAI, ChatGPT, Ollama and others

Python UI Frameworks

  • Gradio
    Gradio is the fastest way to demo your machine learning model with a friendly web interface so that anyone can use it, anywhere!
  • Streamlit
    Streamlit turns data scripts into shareable web apps in minutes.
    All in pure Python. No front‑end experience required.
  • HyperDiv
    Open-source framework for rapidly building reactive web apps in Python, with built-in Shoelace components, Markdown, charts, tables, and more.
  • Shoelace
    A forward-thinking library of web components.

Ollama | Getting Started

Installation

Read here for details.

Linuxcurl -fsSL https://ollama.com/install.sh | sh
Mac OSDownload
WindowsDownload

Start Ollama Service

ollama start

This starts the Ollama Service and binds it to the default ip address 127.0.0.1:11434

If you want to access the service from another host/client, you have to use the ip address 0.0.0.0

systemctl stop ollama.service
export OLLAMA_HOST=0.0.0.0:11434
ollama start

To change the IP address of the service, edit the file /etc/systemd/system/ollama.service and add

[Unit]
Description=Ollama Service
After=network-online.target

[Service]
ExecStart=/usr/local/bin/ollama serve
User=ollama
Group=ollama
Restart=always
RestartSec=3
Environment="OLLAMA_HOST=0.0.0.0:11434"

[Install]
WantedBy=default.target

Access the Ollama Service from your Browser using <ip-adress of host>:11434

Sample Python Chat

Install Python

Install Ollama Library

pip install ollama

Create the chat programm

#!/usr/bin/env python

from ollama import Client

ollama = Client(host='127.0.0.1')

response = ollama.chat(model='llama3', messages=[
  {
    'role': 'user',
    'content': 'Why is the sky blue?',
  },
])
print(response['message']['content'])

Run the programm

❯ ./chat.py

Hint: To see, whats happen with the service, monitor the logfile

❯ sudo journalctl -u ollama.service -f

Query the API

Read the API definition here

curl http://localhost:11434/api/generate -d '{
  "model": "llama2",
  "prompt": "Why is the sky blue?",
  "stream": false
}'

Create a simple ChatGPT Clone

Create the Gradio App

Gatsby | Getting started with Gatsby

Installation

npm init gatsby
pnpm create gatsby
❯ npm create gatsby
.../21.6.2/pnpm/store/v3/tmp/dlx-42253   |   +3 +
.../21.6.2/pnpm/store/v3/tmp/dlx-42253   | Progress: resolved 3, reused 1, downloaded 2, added 3, done
create-gatsby version 3.13.1

                                                                            Welcome to Gatsby!
What would you like to call your site?
✔ Getting-Started-with-Gatsby/ site
✔ Will you be using JavaScript or TypeScript?
· TypeScript
✔ Will you be using a CMS?
· No (or I'll add it later)
✔ Would you like to install a styling system?
· Tailwind CSS
✔ Would you like to install additional features with other plugins?
· Add responsive images
· Add an automatic sitemap
· Generate a manifest file
· Add Markdown and MDX support


Thanks! Here's what we'll now do:

    🛠  Create a new Gatsby site in the folder site
    🎨 Get you set up to use Tailwind CSS for styling your site
    🔌 Install gatsby-plugin-image, gatsby-plugin-sitemap, gatsby-plugin-manifest, gatsby-plugin-mdx

✔ Shall we do this? (Y/n) · Yes
✔ Created site from template
✔ Installed Gatsby
✔ Installed plugins
✔ Created site in site
🔌 Setting-up plugins...
info Adding gatsby-plugin-postcss
info Adding gatsby-plugin-image
info Adding gatsby-plugin-sitemap
info Adding gatsby-plugin-manifest
info Adding gatsby-plugin-mdx
info Adding gatsby-plugin-sharp
info Adding gatsby-transformer-sharp
info Adding gatsby-source-filesystem
info Adding gatsby-source-filesystem
info Installed gatsby-plugin-postcss in gatsby-config
success Adding gatsby-plugin-postcss to gatsby-config - 0.224s
info Installed gatsby-plugin-image in gatsby-config
success Adding gatsby-plugin-image to gatsby-config - 0.221s
info Installed gatsby-plugin-sitemap in gatsby-config
success Adding gatsby-plugin-sitemap to gatsby-config - 0.230s
info Installed gatsby-plugin-manifest in gatsby-config
success Adding gatsby-plugin-manifest to gatsby-config - 0.258s
info Installed gatsby-plugin-mdx in gatsby-config
success Adding gatsby-plugin-mdx to gatsby-config - 0.264s
info Installed gatsby-plugin-sharp in gatsby-config
success Adding gatsby-plugin-sharp to gatsby-config - 0.265s
info Installed gatsby-transformer-sharp in gatsby-config
success Adding gatsby-transformer-sharp to gatsby-config - 0.269s
info Installed gatsby-source-filesystem in gatsby-config
success Adding gatsby-source-filesystem (images) to gatsby-config - 0.279s
info Installed gatsby-source-filesystem in gatsby-config
success Adding gatsby-source-filesystem (pages) to gatsby-config - 0.286s
🎨 Adding necessary styling files...
🎉  Your new Gatsby site Getting Started with Gatsby has been successfully created
at /Users/Shared/CLOUD/Programmier-Workshops/Kurse/Gatsby/Einsteiger/Getting-Started-with-Gatsby/site.
Start by going to the directory with

  cd site

Start the local development server with

  npm run develop

See all commands at

  https://www.gatsbyjs.com/docs/reference/gatsby-cli/
❯ cd site
❯ npm install
❯ npm run develop

PHP | Ökosystem

PHPStan

Finds bugs in your code without writing tests. It’s open-source and free.

PHPMD: PHP Mess Detector

What PHPMD does is: It takes a given PHP source code base and look for several potential problems within that source. These problems can be things like:

  • Possible bugs
  • Suboptimal code
  • Overcomplicated expressions
  • Unused parameters, methods, properties

PHPMD is a mature project and provides a diverse set of pre defined rules (though may be not as many its Java brother PMD) to detect code smells and possible errors within the analyzed source code. Checkout the rules section to learn more about all implemented rules.

PHP CodeSniffer

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

GrumPHP

Sick and tired of defending code quality over and over again? GrumPHP will do it for you! This composer plugin will register some git hooks in your package repository. When somebody commits changes, GrumPHP will run some tests on the committed code. If the tests fail, you won’t be able to commit your changes. This handy tool will not only improve your codebase, it will also teach your co-workers to write better code following the best practices you’ve determined as a team.

https://api-platform.com

Laravel | Arbeiten mit Swagger

Schritt 1: Erstellen Sie ein Laravel-Projekt

Wenn Sie noch kein Laravel-Projekt haben, erstellen Sie eines mit Composer. Öffnen Sie Ihr Terminal und führen Sie den folgenden Befehl aus:

composer create-project --prefer-dist laravel/laravel App

Ersetzen Sie your-api-project durch den gewünschten Projektnamen.

Schritt 2: Installieren Sie die Swagger-PHP-Bibliothek

Sie benötigen die Swagger-PHP-Bibliothek, um Swagger-Dokumentation zu generieren. Installieren Sie diese mit Composer:

composer require zircote/swagger-php

Schritt 3: Erstellen Sie API-Routen

In Laravel definieren Sie Ihre API-Routen in der Datei routes/api.php. Sie können Routen erstellen, wie Sie es normalerweise für Ihre API tun würden.

routes/api.php

use Illuminate\Support\Facades\Route;

Route::get('/users', 'UserController@index');
Route::post('/users', 'UserController@store');
Route::get('/users/{id}', 'UserController@show');

Schritt 4: Generieren Sie Swagger-Annotationen

In Ihren Controller-Methoden verwenden Sie Swagger-Annotationen, um Ihre API zu dokumentieren. Hier ist ein Beispiel, wie man eine Controller-Methode annotiert:

/**
 * @SWG\Get(
 *     path="/users",
 *     summary="Holt eine Liste von Benutzern",
 *     tags={"Users"},
 *     @SWG\Response(response=200, description="Erfolgreiche Operation"),
 *     @SWG\Response(response=400, description="Ungültige Anfrage")
 * )
 */
public function index()
{
    // Ihre API-Logik hier
}

Weitere Informationen zu Swagger-Annotationen finden Sie in der Swagger-PHP-Dokumentation.

Schritt 5: Generieren Sie Swagger-Dokumentation

Nachdem Sie Ihre Controller annotiert haben, müssen Sie die Swagger-Dokumentation generieren. Dies können Sie mit dem artisan Befehl tun, der vom darkaonline/l5-swagger Paket bereitgestellt wird.

Zuerst installieren Sie das Paket:

composer require darkaonline/l5-swagger

Veröffentlichen Sie nun die Swagger-Konfiguration:

php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"

Bearbeiten Sie die Datei config/l5-swagger.php, um die Swagger-Konfiguration nach Bedarf anzupassen.

Schritt 6: Generieren Sie Swagger-Dokumentation

Führen Sie den folgenden Befehl aus, um die Swagger-Dokumentation zu generieren:

php artisan l5-swagger:generate

Die Swagger UI ist verfügbar unter http://127.0.0.1:8000/api/documentation.

Schritt 7: Zugriff auf Swagger UI

Öffnen sie die Swagger UI URL in Ihrem Browser.

Astro Tutorial – Add Table of Content (TOC) to the Post Layout

TL;DR

Code for this tutorial is on Github

Starter Project

Create Starter

❯ npm create astro@latest
.../21.6.2/pnpm/store/v3/tmp/dlx-5990    |  +39 ++++
.../21.6.2/pnpm/store/v3/tmp/dlx-5990    | Progress: resolved 39, reused 39, downloaded 0, added 39, done

 astro   Launch sequence initiated.

   dir   Where should we create your new project?
         ./Tutorial - Add TOC to PostLayout

  tmpl   How would you like to start your new project?
         Use blog template

    ts   Do you plan to write TypeScript?
         Yes

   use   How strict should TypeScript be?
         Strict

  deps   Install dependencies?
         Yes

   git   Initialize a new git repository?
         Yes

      ✔  Project initialized!
         ■ Template copied
         ■ TypeScript customized
         ■ Dependencies installed
         ■ Git initialized

  next   Liftoff confirmed. Explore your project!

         Enter your project directory using cd "./Tutorial - Add TOC to PostLayout"
         Run pnpm dev to start the dev server. CTRL+C to stop.
         Add frameworks like react or tailwind using astro add.

         Stuck? Join us at https://astro.build/chat

╭─────╮  Houston:
│ ◠ ◡ ◠  Good luck out there, astronaut! 🚀
╰─────╯

Run Starter

❯ cd Tutorial\ -\ Add\ TOC\ to\ PostLayout/

Tutorial - Add TOC to PostLayout on  master [+] is 📦 v0.0.1 via  v21.6.2 via 🐍 v3.12.2 (3.12)
❯ npm run dev

> tutorial---add-toc-to-postlayout@0.0.1 dev /Users/Shared/CLOUD/Programmier-Workshops/Kurse/Astro/Einsteiger/Tutorial - Add TOC to PostLayout
> astro dev


 astro  v4.5.12 ready in 300 ms

┃ Local    http://localhost:4321/
┃ Network  use --host to expose

12:18:45 watching for file changes...

Modify Project Structur and add helper code

tsconfig.json

{
  "extends": "astro/tsconfigs/strict",
  "compilerOptions": {
    "allowJs": true,
    "strictNullChecks": true,
    "baseUrl": ".",
    "lib": ["es2022", "dom", "dom.iterable"],
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "exclude": ["node_modules", "**/node_modules/*", ".vscode", "dist"]
}

Replace relative path with reference to path alias in every page

import Layout from '../../layouts/BlogPost.astro';

becomes to

import Layout from '@/layouts/BlogPost.astro';
import Layout from '../styles/global.css';

becomes to

import Layout from '@/styles/global.css';

Create separate Layouts for Project and Posts

Rename src/layouts/BlogPost.astro to src/layouts/BaseLayout.astro

Change every import of BlogPost to

import Layout from '@/layouts/BaseLayout.astro';