Site Tools


Hotfix release available: 2024-02-06a "Kaos". upgrade now! [55.1] (what's this?)
New release available: 2024-02-06 "Kaos". upgrade now! [55] (what's this?)
onny:notizen:programmierung

This is an old revision of the document!


python

using argparse

import argparse
 
parser = argparse.ArgumentParser()
parser.add_argument("--input", help="choose 'microphone', 'system', 'file' or the name of a recording device (default system)")
parser.add_argument("file", nargs='?', help="common sound file with about 10 seconds runtime (optional)")
args = parser.parse_args()
 
if args.input:
    if (args.input == "system"):
[...]

beautifulsoup example

from bs4 import BeautifulSoup
soup = BeautifulSoup(req.content, features="lxml")
token = soup.findAll("input", {"name": "_token"})[0]['value']

record, play and save sound

import soundcard as sc
import soundfile as sf
import numpy
sound_device = sc.get_microphone('Monitor', include_loopback=True) # loopback system sound
sound_device = sc.default_microphone()
data = sound_device.record(samplerate=48000, numframes=500000)
sf.write("/tmp/recording.ogg", data, 48000)
default_speaker = sc.default_speaker()
default_speaker.play(data/numpy.max(data), samplerate=48000)

load json config

import json
 
config = {}
with open('config.json') as json_data:
    configfile = json.load(json_data)
    config['preferences'] = configfile["lit-eratur"]["preferences"]
suburl = config['preferences']['suburl']
{
  "lit-eratur": {
    "preferences": {
      "suburl": "",
      "password": "password"
    }
  }
}

current date

import datetime
date = datetime.datetime.now().strftime("%d.%m.%Y")

requests

import requests
upstream_head = requests.head(upstream_url+url_param)
upstream_request = requests.get(upstream_url+url_param,allow_redirects=False)
if (upstream_request.status_code == 302):
    upstream_request = requests.get(upstream_url + upstream_head.headers['location'])
    upstream_head = requests.head(upstream_url + upstream_head.headers['location'])
if (upstream_head.headers['content-type'] == "text/html;charset=UTF-8" or upstream_head.headers['content-type'] == "text/html; charset=UTF-8"):
    upstream_response = upstream_response.replace("//thepiratebay.org","")

ponyorm

from pony import orm
db = orm.Database()
 
class Article(db.Entity):
    name = orm.Required(str)
    date = orm.Required(str)
    text = orm.Required(str)
    title = orm.Required(str)
 
@orm.db_session
def add_article(name, date, text, title):
    Article(name=nane, date=date, text=text, title=title)
 
db.bind(provider='sqlite', filename='database.sqlite', create_db=True)
db.generate_mapping(create_tables=True)
 
add_article("Jonas", "01.01.2001", "hallo welt", "mein eintrag")
 
with orm.db_session:
    articles = orm.select(f for f in Article).order_by(lambda: orm.desc(f.id))[:]
    for article in articles:
        print(article["name"])

bottle

import bottle
app = bottle.Bottle()
 
@app.get("/static/logo.png")
def index():
    return bottle.static_file("logo.png", root="static")
 
@app.post("/newpost")
def index():
    myname = bottle.request.forms.get("name")
    print(myname)
    bottle.response.status = 200
    bottle.response.content_type = "text/html; charset=UTF-8"
 
@app.get("/page/<page:int>")
def index(page):
    return bottle.template('index.tpl', page=page)
 
if __name__ == '__main__':
    app.run(reloader=True, debug=True, host='0.0.0.0', port=8080)
else:
    application = app

template syntax

      %for article in articles:
      %  categories = article.categories.split(",")
      <article>
        <h1><i class="em em-bookmark"></i> {{article.title}}</h1>
        <span class="autor">rezensiert von {{article.name}} am {{article.date}} in:
          % for index, category in enumerate(categories):
            % category = category.strip()
            <a href="{{suburl}}/category/{{category}}">
            % if (len(categories) > 1 and index != (len(categories)-1)):
            {{category}}</a>,
            % else:
            {{category}}</a>
            % end
          % end
        </span>
        <p>
          {{! article.text}}
          <br><br><i>Bewertung:</i>
          % for i in range(5):
            % if i >= article.rating:
            <img src={{suburl}}/static/unlit.png class=emoji>
            % else:
            <i class="em em-fire emoji"></i>
            % end
          % end
        </p>
      </article>
      %end

regex

regex match between two special chars

pat = r'.*?\[(.*)].*'             #See Note at the bottom of the answer
s = "foobar['infoNeededHere']ddd"
match = re.search(pat, s)
match.group(1)
"'infoNeededHere'"

regex findall

regex = re.compile('https://podcasts.srf.ch/ch/audio/.*?.mp3')
it = re.finditer(regex, requests_response.text)
 
for match in it:
  print (match.group(0))

find/search text html tags

re_search_pat = r'.*(<title>.*</title>).*'
match = re.search(re_search_pat, upstream_response)
site_title = match.group(1)

strip all specific html tags

upstream_response = re.sub(r'<script.+?</script>', '', upstream_response, flags=re.DOTALL)

javascript

split up javascript files

var MODULE = (function (my) {
     var privateToThisFile = "something";
 
    // add capabilities...
 
     my.publicProperty = "something";
 
     my.publicPropertyFunc = function(){
        alert("something");
     });
 
    return my;
}(MODULE || {}));

on document ready

document.addEventListener("DOMContentLoaded", function() {
  your_function(...);
});

change content text

    var webgl_field = document.getElementById('webgl');
    if (webgl_support()) {
      webgl_field.textContent = "JA";
    } else {
      webgl_field.textContent = "NOE";
    }

ajax post form

    document.getElementById('form').onsubmit = function (evt) {
     evt.preventDefault();
     var form = document.querySelector('form');
     var form_data = new FormData(form);
     var request = new XMLHttpRequest();
      request.onreadystatechange = function() {
        if(request.readyState === 4) {
          if(request.status === 200) {
            location.reload();
          }
        }
      }
      request.open('POST', '{{suburl}}/newpost');
      request.send(form_data);
    }

change style element

    function show_create_post() {
      var x = document.getElementById("create_post");
      if (x.style.display === "block") {
        x.style.display = "none";
      } else {
        x.style.display = "block";
      }
    }

trim string to max length

var string = string.substring(0,100);

onclick class element

document.getElementsByClassName('navbar-burger')[0].onclick = function(){
  console.log('ready');
};

onclick on all class elements

var anchors = document.getElementsByClassName('wp-block-navigation-item__content');
for(var i = 0; i < anchors.length; i++) {
    var anchor = anchors[i];
    anchor.onclick = function() {
        console.log('clicked');
    }
}

remove class from element

var element = document.getElementsByClassName('wp-block-navigation__responsive-container')[0];
element.classList.remove("is-menu-open");

vuejs

add data to attribute string, for example ``<a href``

<a :href="`#/browse/show/${getEpisode.podcastid}/${getEpisode.id}`">{{ getEpisode.title }}</a>

on click change route

<div
	v-lazy:background-image="getEpisode.imgURL"
	class="playerThumb"
	@click="$router.push(`/browse/show/${getEpisode.podcast_id}/${getEpisode.id}`)" />

watch data or property change

props: {
	podcasts: {
		type: Array,
		default() { return [] },
	},
},
watch: {
	podcasts(newValue, oldValue) {
		const slider = this.$refs.slider
		console.log(slider.scrollLeft, slider.scrollWidth, slider.clientWidth)
		if (slider.scrollWidth > slider.clientWidth) {
			this.showNext = true
		}
	},
},

reference html element

<div class='cart-list' ref="cartList"></div>
 
[...]
 
export default {
  name: 'Cart',
  computed: {
    isOverflowing() {
      var element = this.$refs.cartList;
      return (element.offsetHeight < element.scrollHeight || element.offsetWidth < element.scrollWidth)
    }
  }
};

commit / pass more than one parameter to store action-method

methods: {
	...mapActions([
		'queryEpisodes',
		]),
 
	async loadEpisodes(page) {
		const response = await this.queryEpisodes({ page, sortBy: 'pubdate' })
		[...]
	},
 
# store/episodes.js:
 
actions: {
	async queryEpisodes({ commit, getters }, { page, sortBy } = {}) {
		const response = await episodeApiClient.queryEpisodes(null, page, sortBy)
		[...]
	},

frameworks

html

starting template

<!doctype html>
<html lang="de">
<head>
  <meta data-react-helmet="true" charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1">

include remote js file

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

include remote css file

<link rel="stylesheet" type="text/css" href="/lib/exe/css.php?t=dokuwiki&amp;tseed=b35240351d681d3969980f5cbb368ff4"/>

include javascript inside html document

<script language="javascript">
alert("hello");
</script>

css within html

  <style type="text/css">
    nav.main {
      background-color: green; /* will be overridden by body internal styles */
    }
  </style>

footer bottom page

<html>
<head>
  <style type="text/css">
 
    body {
      margin: 0 !important;
      padding: 0 !important;
    }
 
    article {
      min-height: 100vh;
      display: grid;
      grid-template-rows: 1fr auto;
      grid-template-columns: 100%;
    }
 
    main {
      background: whitesmoke;
      padding: 1rem;
    }
 
    footer {
      background: purple;
      padding: 1rem;
    }
 
  </style>
</head>
 
<body>
 
  <article>
      <main>
          <strong contenteditable>Hi, there's not much content, yet. You can write in here to expand the container.</strong>
      </main>
      <footer>
          All rights reversed.
          <br>
          <small>I am always at the bottom of the page</small>
      </footer>
  </article>
 
</body>
</html>

css easy center div box content vertical and horizontal align

  display: flex;
  justify-content: center;
  align-items: center;

advanced

      body {
        margin: 0 !important;
        padding: 0 !important;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        opacity: 1;
        height: 100vh;
      }

css

sweet font styling

font-family: consolas,Menlo-Regular,Menlo,Monaco,monospace;
    font-size: 125%;
    line-height: 135%;

media queries, page greater than 600px

      @media (min-width: 600px) {
        article {
          min-width: 600px;
        }
      }

popover menu

.main-navigation ul li ul.sub-menu {
	opacity: 0;
	position: absolute;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
	transition:opacity 250ms ease-out;
	padding: 20px;
	z-index: 2;
	left: 17px;
	background: white;
}
 
.main-navigation ul li:hover ul.sub-menu {
	opacity: 1;
	transition:opacity 250ms ease-out;
}

responsive grid layout

ul {
	display: grid;
	grid-gap: 50px 40px;
	grid-template-columns: repeat(auto-fit, minmax(290px, 1fr));
}

php

enable debugging / error log

/etc/php/conf.d/debug.ini
display_startup_errors = true
display_errors = true
html_errors = true
log_errors = true
track_errors = true
error_log = /var/log/php-errors.log
touch /var/log/php-errors.log
chmod a+w+r /var/log/php-errors.log

foreach loop

foreach($this->service->findAll($this->userId) as $station) {
	$this->logger->error($station);
	$track = $trackList->addChild('track');
	$track->addChild('location', 'http://localhost/test.mp3');
	$track->addChild('title', 'Radio Test 404fm');
	$track->addChild('image', 'http://localhost/favicon.ico');
}

get array length

var_dump(count($a));

get type of variable

foreach($data as $episode) {
	$this->logger->error(gettype($episode));	
}

convert string to int

intval("12345");

convert array to string

foreach($data as $episode) {
	$this->logger->error(implode(",", $episode));	
}

nextcloud app dev

logging, available methods: emergency, alert, critical, error, warning, notice, info, debug

use OCP\ILogger;
 
class EpisodeController extends Controller {
 
	/** @var ILogger */
	private $logger;
 
[...]
 
	public function __construct(IRequest $request,
								EpisodeService $service,
								FyydApiService $fyydapi,
								ILogger $logger,
								$userId) {
		parent::__construct(Application::APP_ID, $request);
		$this->service = $service;
		$this->fyydapi = $fyydapi;
		$this->logger = $logger;
		$this->userId = $userId;
	}
 
[...]
 
        public function log($message) {
            $this->logger->error($message);
            /* $this->logger->error($message, ['extra_context' => 'my extra context']); */
        }

wordpress

registering menus

functions.php
if ( ! function_exists( 'iaro_setup' ) ) :
 
	function iaro_setup() {
 
                [...]
 
		register_nav_menus(
			array(
				'menu-1' => esc_html__( 'Primary', 'iaro' ),
				'menu-2' => esc_html__( 'Secondary', 'iaro' ),
			)
		);
 
                [...]
 
endif;
 
add_action( 'after_setup_theme', 'iaro_setup' );

customize menu entries, wrap entry into span element

functions.php
		add_filter('nav_menu_item_args', function ($args, $item, $depth) {
	    if ($args->theme_location == 'menu-1' || $args->theme_location == 'menu-2') {
	        $title             = apply_filters('the_title', $item->title, $item->ID);
	        $args->link_before = '<span>';
	        $args->link_after  = '</span>';
	    }
	    return $args;
		}, 10, 3);

check if query is front page

if ( is_front_page() ) :
    get_header( 'front' );
else :
    get_header();
endif;

add support for wide / full images

functions.php
add_theme_support( 'align-wide' );
styles.css
.alignfull {
    width: 100vw;
    margin-left: calc(50% - 50vw);
}

custom menu walker, only printing <a> tags without list items

class Nav_Footer_Walker extends Walker_Nav_Menu {
 
    function start_lvl( &$output, $depth = 0, $args = array() ) {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent\n";
    }
 
    function end_lvl( &$output, $depth = 0, $args = array() ) {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent\n";
    }
 
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
 
        $class_names = $value = '';
 
        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;
 
        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
        $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
 
        $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
        $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
 
        $output .= $indent . '';
 
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
 
        $item_output = $args->before;
        $item_output .= '<a class="navbar-item" '. $attributes .'>';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= '</a>';
        $item_output .= $args->after;
 
        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
 
 
    function end_el( &$output, $item, $depth = 0, $args = array() ) {
        $output .= "\n";
    }
 
}
 
wp_nav_menu( array(
    'menu'            => 'primary',
    'container_id'    => 'mainNavbar',
    'container_class' => 'navbar-menu',
    'items_wrap'      => '<div class="navbar-end">%3$s</div>',
    'walker'          => new Nav_Footer_Walker(),
) );

customizer add option custom text

function theme_customize_register( $wp_customize ) {
 
    $wp_customize->add_setting( 'fachwerksauna_footer-text', array(
        'default' => '',
        'type' => 'option',
        'capability' => 'edit_theme_options'
    ),);
 
    $wp_customize->add_control( new WP_Customize_Control(
        $wp_customize, 'footer-text_control', array(
            'label'      => __( 'Footer text', 'fachwerksauna' ),
            'description' => __( 'Text in footer area', 'fachwerksauna' ),
            'settings'   => 'fachwerksauna_footer-text',
            'priority'   => 10,
            'section'    => 'title_tagline',
            'type'       => 'text',
        )
    ) );
 
}
 
add_action( 'customize_register', 'theme_customize_register' );

add custom javascript js

function twentytwentytwo_enqueue_custom_js() {
    wp_enqueue_script('custom', get_stylesheet_directory_uri().'/inc/js/main.js');
}
 
add_action( 'wp_enqueue_scripts', 'twentytwentytwo_enqueue_custom_js' );

sql

Update field:

UPDATE forwardings SET destination='alex.bloss@online.de' WHERE 'destination=bloss@bigwood.de';

Insert field:

INSERT INTO forwardings (SOURCE, destination) VALUES ('markus.heim@wew-heim.de', 'heimmarkus@yahoo.de');
INSERT INTO forwardings VALUES ('markus.heim@wew-heim.de', 'heimmarkus@yahoo.de');

Delete row:

DELETE FROM domains WHERE DOMAIN='alex-vt.de';
mysql> \P /usr/bin/less
PAGER SET TO /usr/bin/less

Delete all rows:

TRUNCATE my_table;

Create database:

CREATE DATABASE roundcubemail;
GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@'http-new' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

delete user:

DROP USER gitlab@'http.pi';

mysql

delete specific row

delete from oc_storages where numeric_id=58;

remove user

DROP USER 'bloguser'@'localhost';

adjust permissions to table

CREATE USER 'ninja'@'http.pi' IDENTIFIED BY '****';
GRANT ALL PRIVILEGES ON ninja.* TO 'ninja'@'http.pi' IDENTIFIED BY '123';
GRANT ALL PRIVILEGES ON ninja.* TO 'ninja'@'http.pi';
FLUSH PRIVILEGES;

update statement

UPDATE wp_options SET option_value = 'info@example.org' WHERE option_name = 'admin_email';

postgresql

drop database

sudo -u postgres -i
dropdb onlyoffice

list databases

psql# \l

create and delete user

DROP ROLE gitlab;
CREATE USER gitlab WITH PASSWORD '5V0hD0KWX81g5dhKGHsbqU4a';

grant permissions

ALTER USER gitlab SUPERUSER;
CREATE DATABASE gitlabhq_production OWNER gitlab;
ALTER DATABASE gitlabhq_production OWNER TO gitlab;
onny/notizen/programmierung.1664134097.txt.gz · Last modified: 2022/09/25 19:28 by 10.25.40.1