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

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
onny:notizen:programmierung [2019/08/08 13:56] – [python] 2a02:8071:3eba:0:75ee:fbe6:60c3:be81onny:notizen:programmierung [2023/10/24 10:51] – [css] 127.0.0.1
Line 1: Line 1:
 +===== python =====
 +using argparse
 +<code python>
 +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"):
 +[...]
 +</code>
 +beautifulsoup example
 +<code python>
 +from bs4 import BeautifulSoup
 +soup = BeautifulSoup(req.content, features="lxml")
 +token = soup.findAll("input", {"name": "_token"})[0]['value']
 +</code>
 +record, play and save sound
 +<code python>
 +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)
 +</code>
 +load json config
 +<code python>
 +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']
 +</code>
 +<code json>
 +{
 +  "lit-eratur": {
 +    "preferences": {
 +      "suburl": "",
 +      "password": "password"
 +    }
 +  }
 +}
 +</code>
 +current date
 +<code python>
 +import datetime
 +date = datetime.datetime.now().strftime("%d.%m.%Y")
 +</code>
 +
 +requests
 +
 +<code python>
 +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","")
 +</code>
 +
 +class example
 +
 +<code python>
 +class Planday:
 +  auth_url = 'https://id.planday.com/connect/token'
 +  client_id = '1234'
 +  access_token = ''
 +
 +  def authenticate(self):
 +    payload = {
 +      'client_id': self.client_id,
 +      'refresh_token': 'qyS6qt9yNEqygE1mMQtRzA',
 +      'grant_type': 'refresh_token'
 +    }
 +    headers = {
 +      'Content-Type': 'application/x-www-form-urlencoded'
 +    }
 +    session = requests.session()
 +    session.trust_env = False
 +    response = session.request("POST", self.auth_url, headers=headers, data=payload)
 +    response = json.loads(response.text)
 +    self.access_token = response['access_token']
 +
 +planday = Planday()
 +planday.authenticate()
 +</code>
 +==== ponyorm ====
 +<code python>
 +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"])
 +</code>
 +==== bottle ====
 +<code python>
 +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
 +</code>
 +template syntax
 +<code>
 +      %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
 +</code>
 +==== regex ====
 +regex match between two special chars
 +<code python>
 +pat = r'.*?\[(.*)].*'             #See Note at the bottom of the answer
 +s = "foobar['infoNeededHere']ddd"
 +match = re.search(pat, s)
 +match.group(1)
 +"'infoNeededHere'"
 +</code>
 +regex findall
 +<code python>
 +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))
 +</code>
 +find/search text html tags
 +<code python>
 +re_search_pat = r'.*(<title>.*</title>).*'
 +match = re.search(re_search_pat, upstream_response)
 +site_title = match.group(1)
 +</code>
 +strip all specific html tags
 +<code python>
 +upstream_response = re.sub(r'<script.+?</script>', '', upstream_response, flags=re.DOTALL)
 +</code>
 +===== javascript =====
 +
 +split up javascript files
 +
 +<code javascript>
 +var MODULE = (function (my) {
 +     var privateToThisFile = "something";
 +
 +    // add capabilities...
 +
 +     my.publicProperty = "something";
 +     
 +     my.publicPropertyFunc = function(){
 +        alert("something");
 +     });
 +
 +    return my;
 +}(MODULE || {}));
 +</code>
 +
 +on document ready
 +
 +<code javascript>
 +document.addEventListener("DOMContentLoaded", function() {
 +  your_function(...);
 +});
 +
 +</code>
 +
 +change content text
 +
 +<code javascript>
 +    var webgl_field = document.getElementById('webgl');
 +    if (webgl_support()) {
 +      webgl_field.textContent = "JA";
 +    } else {
 +      webgl_field.textContent = "NOE";
 +    }
 +</code>
 +
 +ajax post form
 +
 +<code javascript>
 +    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);
 +    }
 +</code>
 +
 +change style element
 +
 +<code javascript>
 +    function show_create_post() {
 +      var x = document.getElementById("create_post");
 +      if (x.style.display === "block") {
 +        x.style.display = "none";
 +      } else {
 +        x.style.display = "block";
 +      }
 +    }
 +</code>
 +
 +trim string to max length
 +
 +<code javascript>
 +var string = string.substring(0,100);
 +</code>
 +
 +onclick class element
 +
 +<code javascript>
 +document.getElementsByClassName('navbar-burger')[0].onclick = function(){
 +  console.log('ready');
 +};
 +</code>
 +
 +onclick on all class elements
 +
 +<code javascript>
 +# old: var anchors = document.getElementsByClassName('wp-block-navigation-item__content');
 +let allCheckBox = document.querySelectorAll('.shapes')
 +
 +  allCheckBox.forEach((checkbox) => { 
 +  checkbox.addEventListener('change', (event) => {
 +    if (event.target.checked) {
 +      console.log(event.target.value)
 +    }
 +  })
 +})
 +</code>
 +
 +remove class from element
 +
 +<code javascript>
 +var element = document.getElementsByClassName('wp-block-navigation__responsive-container')[0];
 +element.classList.remove("is-menu-open");
 +</code>
 +
 +get url and pathname
 +
 +<code javascript>
 +console.log(window.location.url)
 +console.log(window.location.pathname)
 +</code>
 +
 +querySelector, get child element
 +
 +<code javascript>
 +var h3 = document.querySelector('div.multicolumn ul li:nth-child(1) h3')
 +console.log(h3.textContent);
 +h3.querySelector('span');
 +</code>
 +
 +querySelectorAll
 +
 +<code javascript>
 +var productAccordion = document.querySelectorAll('div.product__accordion');
 +productAccordion[1].style.display = "none";
 +</code>
 +
 +get next or previous element
 +
 +<code javascript>
 +document.getElementById('foo2').nextSibling; // #foo3
 +document.getElementById('foo2').previousSibling; // #foo1
 +</code>
 +==== vuejs ====
 +
 +add data to attribute string, for example ``<a href``
 +<code javascript>
 +<a :href="`#/browse/show/${getEpisode.podcastid}/${getEpisode.id}`">{{ getEpisode.title }}</a>
 +</code>
 +
 +on click change route
 +<code javascript>
 +<div
 + v-lazy:background-image="getEpisode.imgURL"
 + class="playerThumb"
 + @click="$router.push(`/browse/show/${getEpisode.podcast_id}/${getEpisode.id}`)" />
 +</code>
 +
 +watch data or property change
 +<code javascript>
 +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
 + }
 + },
 +},
 +</code>
 +
 +reference html element
 +<code javascript>
 +<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)
 +    }
 +  }
 +};
 +</code>
 +
 +commit / pass more than one parameter to store action-method
 +<code javascript>
 +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)
 + [...]
 + },
 +</code>
 +
 +==== frameworks ====
 +
 +  * pushy animated side menu https://chrisyee.ca/pushy/#
 +
 +===== html =====
 +starting template
 +<code html>
 +<!doctype html>
 +<html lang="de">
 +<head>
 +  <meta data-react-helmet="true" charset="utf-8"/>
 +  <meta name="viewport" content="width=device-width, initial-scale=1">
 +</code>
 +include remote js file
 +<code html>
 +<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 +</code>
 +include remote css file
 +<code html>
 +<link rel="stylesheet" type="text/css" href="/lib/exe/css.php?t=dokuwiki&amp;tseed=b35240351d681d3969980f5cbb368ff4"/>
 +</code>
 +include javascript inside html document
 +<code html>
 +<script language="javascript">
 +alert("hello");
 +</script>
 +</code>
 +css within html
 +<code css>
 +  <style type="text/css">
 +    nav.main {
 +      background-color: green; /* will be overridden by body internal styles */
 +    }
 +  </style>
 +</code>
 +footer bottom page
 +<code html>
 +<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>
 +</code>
 +css easy center div box content vertical and horizontal align
 +<code css>
 +  display: flex;
 +  justify-content: center;
 +  align-items: center;
 +</code>
 +advanced
 +<code css>
 +      body {
 +        margin: 0 !important;
 +        padding: 0 !important;
 +        display: flex;
 +        justify-content: center;
 +        align-items: center;
 +        flex-direction: column;
 +        opacity: 1;
 +        height: 100vh;
 +      }
 +</code>
 +
 +===== php =====
 +enable debugging / error log
 +<file - /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
 +</file>
 +<code>
 +touch /var/log/php-errors.log
 +chmod a+w+r /var/log/php-errors.log
 +</code>
 +foreach loop
 +<code php>
 +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');
 +}
 +</code>
 +get array length
 +<code php>
 +var_dump(count($a));
 +</code>
 +
 +get type of variable
 +<code php>
 +foreach($data as $episode) {
 + $this->logger->error(gettype($episode));
 +}
 +</code>
 +
 +convert string to int
 +<code php>
 +intval("12345");
 +</code>
 +convert array to string
 +<code php>
 +foreach($data as $episode) {
 + $this->logger->error(implode(",", $episode));
 +}
 +</code>
 +
 +==== nextcloud app dev ====
 +logging, available methods: emergency, alert, critical, error, warning, notice, info, debug
 +<code php>
 +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']); */
 +        }
 +</code>
 +
 +==== wordpress ====
 +registering menus
 +<code php 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' );
 +</code>
 +
 +customize menu entries, wrap entry into span element
 +<code php 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);
 +</code>
 +
 +check if query is front page
 +<code php>
 +if ( is_front_page() ) :
 +    get_header( 'front' );
 +else :
 +    get_header();
 +endif;
 +</code>
 +
 +add support for wide / full images
 +<code php functions.php>
 +add_theme_support( 'align-wide' );
 +</code>
 +
 +<code css styles.css>
 +.alignfull {
 +    width: 100vw;
 +    margin-left: calc(50% - 50vw);
 +}
 +</code>
 +
 +custom menu walker, only printing <a> tags without list items
 +<code php>
 +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(),
 +) );
 +</code>
 +
 +customizer add option custom text
 +<code php>
 +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' );
 +</code>
 +
 +add custom javascript js
 +
 +<code php>
 +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' );
 +</code>
 +===== sql =====
 +Update field:
 +<code sql>
 +update forwardings set destination='alex.bloss@online.de' where 'destination=bloss@bigwood.de';
 +</code>
 +Insert field:
 +<code sql>
 +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');
 +</code>
 +Delete row:
 +<code sql>
 +delete from domains where domain='alex-vt.de';
 +</code>
 +<code sql>
 +mysql> \P /usr/bin/less
 +PAGER set to /usr/bin/less
 +</code>
 +Delete all rows:
 +<code sql>
 +truncate my_table;
 +</code>
 +Create database:
 +<code sql>
 +CREATE DATABASE roundcubemail;
 +GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@'http-new' IDENTIFIED BY 'password';
 +FLUSH PRIVILEGES;
 +</code>
 +delete user:
 +<code sql>
 +DROP user gitlab@'http.pi';
 +</code>
 +
 +==== mysql ====
 +
 +delete specific row
 +<code>
 +delete from oc_storages where numeric_id=58;
 +</code>
 +
 +remove user
 +<code sql>
 +DROP USER 'bloguser'@'localhost';
 +</code>
 +
 +adjust permissions to table
 +<code sql>
 +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;
 +</code>
 +
 +update statement
 +
 +<code sql>
 +UPDATE wp_options SET option_value = 'info@example.org' WHERE option_name = 'admin_email';
 +</code>
  
onny/notizen/programmierung.txt · Last modified: 2023/11/07 15:40 by 127.0.0.1