From be44243136d710eec0345f8459a64da377bab357 Mon Sep 17 00:00:00 2001 From: Simeon Simeonov Date: Sun, 29 Mar 2026 13:43:38 +0200 Subject: Re-format reveal.js slides and add templates --- reveal.js/cryptographic_primitives.html | 494 +++++++ reveal.js/demo.html | 443 ++++-- reveal.js/dist/theme/statnett_compact.css | 307 ++++ reveal.js/free_software.html | 70 +- reveal.js/git.html | 73 +- reveal.js/images/cryptographic_primitives/GCM.svg | 1500 ++++++++++++++++++++ reveal.js/images/cryptographic_primitives/hmac.svg | 165 +++ .../modes_of_operation.png | Bin 0 -> 195700 bytes .../dataporten/dataporten_the_big_picture1.png | Bin 9698 -> 0 bytes reveal.js/images/dataporten/flow1.png | Bin 22182 -> 0 bytes reveal.js/images/gateway/dashboard01.png | Bin 139944 -> 0 bytes reveal.js/images/gateway/portal01.png | Bin 97986 -> 0 bytes reveal.js/images/gateway/portal02.png | Bin 91353 -> 0 bytes reveal.js/images/mqprod/flow01.png | Bin 40772 -> 0 bytes reveal.js/mqprod.html | 248 ---- reveal.js/postgresql_tuning.html | 258 ++-- reveal.js/rabbitmq.html | 311 ---- reveal.js/sqlalchemy.html | 927 ++++++------ reveal.js/template.html | 55 + reveal.js/template_statnett.html | 56 + reveal.js/timetravel.html | 127 -- 21 files changed, 3578 insertions(+), 1456 deletions(-) create mode 100644 reveal.js/cryptographic_primitives.html create mode 100644 reveal.js/dist/theme/statnett_compact.css mode change 100755 => 100644 reveal.js/git.html create mode 100644 reveal.js/images/cryptographic_primitives/GCM.svg create mode 100644 reveal.js/images/cryptographic_primitives/hmac.svg create mode 100644 reveal.js/images/cryptographic_primitives/modes_of_operation.png delete mode 100644 reveal.js/images/dataporten/dataporten_the_big_picture1.png delete mode 100644 reveal.js/images/dataporten/flow1.png delete mode 100644 reveal.js/images/gateway/dashboard01.png delete mode 100644 reveal.js/images/gateway/portal01.png delete mode 100644 reveal.js/images/gateway/portal02.png delete mode 100644 reveal.js/images/mqprod/flow01.png delete mode 100644 reveal.js/mqprod.html delete mode 100644 reveal.js/rabbitmq.html create mode 100644 reveal.js/template.html create mode 100644 reveal.js/template_statnett.html delete mode 100644 reveal.js/timetravel.html (limited to 'reveal.js') diff --git a/reveal.js/cryptographic_primitives.html b/reveal.js/cryptographic_primitives.html new file mode 100644 index 0000000..4b2e6fc --- /dev/null +++ b/reveal.js/cryptographic_primitives.html @@ -0,0 +1,494 @@ + + +
+ +Simeon Simeonov - TDE
+Cryptographic primitives are the most basic building blocks in cryptographic systems and protocols.
+Creating cryptographic routines is very hard, and testing them to be reliable takes a long time, it is essentially never sensible (nor secure) to design a new cryptographic primitive to suit the needs of a new cryptographic system.
+Since algorithms in this field are not only required to be designed well but also need to be tested well by the cryptologist community, even if a cryptographic routine looks good from a design point of view it might still contain errors. Successfully withstanding such scrutiny gives some confidence (in fact, so far, the only confidence) that the algorithm is indeed secure enough to use. Security proofs for cryptographic primitives are generally not available.
+When choosing primitive for a cryptographic system, one should always consider if the primitive:
+A hash function is any function that can be used to map data of arbitrary size to fixed-size values (or a set of fixed-size values)
+Cryptographic hash functions or cryptographically secure hash functions are hash functions with special properties (making them desirable for cryptographic systems)
+(Over)simplified list of desired properties:
+| Designers | +Ronald Rivest | +
| Published | +1992 | +
| Digest size | +128 bits (16 bytes) | +
| Block size | +512 bits | +
| Broken? | +Yes (broken collision resistance in 2^18 time) | +
Still in use in lagacy applications and in applications where collision resistance is not needed
+| Designers | +NSA | +
| Published | +1995 | +
| Digest size | +160 bits (20 bytes) | +
| Block size | +512 bits | +
| Broken? | +Yes | +
Still in use. Revision control systems such as Git, Mercurial, and Monotone use SHA-1, not for security, but to identify revisions and to ensure that the data has not changed due to accidental corruption.
+| Designers | +NSA | +
| Published | +2001 | +
| Digest sizes | +224, 256, 384 or 512 bits | +
| Block sizes | +256 bits (SHA-224 and SHA-256) or 512 bits | +
| Broken? | +No | +
| Designers | +Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles van Assche | +
| Published | +2016 | +
| Digest size | +arbitrary | +
| Block size | +variable | +
| Broken? | +No | +
Based on Keccak - winner of the NIST hash function competition after some controversial adjustments. Very fast and flexible.
+| Designers | +Jean-Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn and Christian Winnerlein | +
| Published | +2008 (BLAKE) | +
| Digest size | +up to 64 bytes (BLAKE2b), up to 32 bytes (BLAKE2s) | +
| Block size | +variable (stream) | +
| Broken? | +No | +
BLAKE2 is based on Daniel J. Bernstein's ChaCha stream cipher and is extremely fast. BLAKE2b and BLAKE2s are specified in RFC 7693.
+Cryptographic hash functions are used for many different things in cryptographic systems and protocols. Few examples:
+HMAC (hash-based message authentication code) is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key. It may be used to simultaneously verify both the data integrity and authenticity of a message. An HMAC is a type of keyed hash function that can also be used in a key derivation scheme or a key stretching scheme.
+HMAC can provide authentication using a shared secret instead of using digital signatures with asymmetric cryptography. It trades off the need for a complex public key infrastructure by delegating the key exchange to the communicating parties, who are responsible for establishing and using a trusted channel to agree on the key prior to communication.
+XOR (eXclusive OR) - is a logical operator
+With two inputs, XOR is true if and only if the inputs differ (one is true, one is false)
+PBKDF2 (Password-Based Key Derivation Function 2) is a key derivation function with a sliding computational cost, used to reduce vulnerability to brute-force attacks.
+PBKDF2 applies a pseudorandom function, such as HMAC, to the input password or passphrase along with a salt value and repeats the process many times to produce a derived key, which can then be used as a cryptographic key in subsequent operations. The added computational work makes password cracking much more difficult, and is known as key stretching.
+Most cryptographic applications require random numbers for: generating keys, initialization vectors, nonces (arbitrary numbers that can be used just once), salts, tokens etc, etc.
+The "quality" of the randomness required for these applications varies. For example, creating a nonce in some protocols needs only uniqueness. On the other hand, the generation of a master key requires a higher quality, such as more entropy.
+Entropy is obtained from a high-quality source, generally the operating system's randomness API.
+In practical situations, numbers are needed with more randomness than the available entropy can provide. Also, the processes to extract randomness from a running system are slow in actual practice. In such instances, a cryptographically secure pseudorandom number generator (CSPRNG) can sometimes be used. A CSPRNG can "stretch" the available entropy over more bits.
+CSPRNG must
+"Practical" CSPRNG schemes not only include an CSPRNG algorithm, but also a way to initialize ("seed") it while keeping the seed secret.
+Symmetric ciphers use the same cryptographic keys for both the encryption of plaintext and the decryption of ciphertext.
+“Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can’t break. It’s not even hard. What is hard is creating an algorithm that no one else can break, even after years of analysis. And the only way to prove that is to subject the algorithm to years of analysis by the best cryptographers around.” - Bruce Schneier
+A "perfect" cipher - the one-time pad has been known since 1882, but is not practically applicable in modern systems:
+There two types of modern ciphers:
+| Designer | +IBM | +
| Published | +1975 | +
| Key size | +56 bits | +
| Block size | +64 bits | +
Not used anymore. 3DES was published in 1981 (with keysize of 112 bits or 168 bits).
+| Designer | +Bruce Schneier | +
| Published | +1993 | +
| Key size | +32-448 bits | +
| Block size | +64 bits | +
Schneier has stated that "Blowfish is unpatented, and will remain so in all countries. The algorithm is hereby placed in the public domain, and can be freely used by anyone.". Still in use in legacy applications and notably in the bcrypt password hashing function.
+| Designer | +Joan Daemen, Vincent Rijmen | +
| Published | +1998 | +
| Key size | +128 bits, 192 bits or 256 bits | +
| Block size | +128 bits | +
Rijndael was thew winner of the NIST AES selection process. Currently the most widely adopted block cipher (both in hardware and software).
+A block cipher by itself is only suitable for the secure cryptographic transformation (encryption or decryption) of one fixed-length group of bits called a block. A mode of operation describes how to repeatedly apply a cipher's single-block operation to securely transform amounts of data larger than a block.
+
+ The GCM algorithm provides both data authenticity (integrity) and confidentiality and belongs to the class of authenticated encryption with associated data (AEAD) methods. This means that as input it takes a key K, some plaintext P, and some associated data AD; it then encrypts the plaintext using the key to produce ciphertext C, and computes an authentication tag T from the ciphertext and the associated data (which remains unencrypted). A recipient with knowledge of K, upon reception of AD, C and T, can decrypt the ciphertext to recover the plaintext P and can check the tag T to ensure that neither ciphertext nor associated data were tampered with.
+Stream ciphers typically execute at a higher speed than block ciphers and have lower hardware complexity. However, stream ciphers can be susceptible to security breaches, for example, when the same starting state (seed) is used twice.
+Essentially they behave as pseudorandom functions where they key is / is part of the "seed".
+| Designer | +Daniel J. Bernstein (djb) | +
| Published | +2008 | +
| Key size | +128 bits or 256 bits | +
ChaCha20-Poly1305 is an AEAD algorithm, that combines the ChaCha20 stream cipher with the Poly1305 message authentication code. It has fast software performance, and without hardware acceleration, is usually faster than AES-GCM.
+Asymmetric cryptography makes use pairs of related keys. Each key pair consists of a public key and a corresponding private key. Key pairs are generated with cryptographic algorithms based on mathematical problems termed one-way functions. Security of public-key cryptography depends on keeping the private key secret, while the public key can be openly distributed without compromising security.
+Usually we use public key cryptography for:
+| Designers | +Ron Rivest, Adi Shamir and Leonard Adleman | +
| Published | +1977, patented until 2000 :( | +
The security of RSA relies on the practical difficulty of factoring the product of two large prime numbers, the "factoring problem". Still the most widely used public key system. A key size of 2048 or 4096 bits should be used. A very good CSPRNG is needed.
+In modern cryptographic systems and protocols (like TLS >= 1.2) RSA is only used for verifying that the client is initiating session with the "right" server. Encryption / decryption is performed using common negotiated key and symmetric ciphers.
+Forward secrecy is a desired feature of specific key-agreement protocols that gives assurances that session keys will not be compromised even if long-term secrets used in the session key exchange are compromised, limiting damage. For HTTPS, the long-term secret is typically the private key of the server.
+Post-quantum cryptography (PQC), sometimes referred to as quantum-proof, quantum-safe, or quantum-resistant, is the development of cryptographic algorithms (usually public-key algorithms) that are thought to be secure against a cryptanalytic attack by a quantum computer. Most widely-used public-key algorithms rely on the difficulty of one of three mathematical problems: the integer factorization problem, the discrete logarithm problem or the elliptic-curve discrete logarithm problem. All of these problems could be easily solved on a sufficiently powerful quantum computer running Shor's algorithm or even faster and less demanding (in terms of the number of qubits required) alternatives.
+- Created by Hakim El Hattab and contributors + Created by Hakim El Hattab and + contributors
- reveal.js enables you to create beautiful interactive slide decks using HTML. This presentation will show you examples of what it can do. + reveal.js enables you to create beautiful interactive slide decks using HTML. This + presentation will show you examples of what it can do.
Slides can be nested inside of each other.
Use the Space key to navigate through all slides.
-Nested slides are useful for adding additional detail underneath a high level horizontal slide.
++ Nested slides are useful for adding additional detail underneath a high level + horizontal slide. +
That's it, time to go back up.
-- Not a coder? Not a problem. There's a fully-featured visual editor for authoring these, try it out at https://slides.com. + Not a coder? Not a problem. There's a fully-featured visual editor for authoring these, + try it out at https://slides.com.
- This slide is visible in the source, but hidden when the presentation is viewed. You can show all hidden slides by setting the `showHiddenSlides` config option to `true`. + This slide is visible in the source, but hidden when the presentation is viewed. You can + show all hidden slides by setting the `showHiddenSlides` config option to `true`.
- import React, { useState } from 'react';
+ import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
- ...
+
+ ...
+
);
}
- Code syntax highlighting courtesy of highlight.js.
++ Code syntax highlighting courtesy of + highlight.js. +
+ <img src="image.png" data-preview-image="image.png">
+
+
+
+ <img src="video.png" data-preview-video="video.mp4">
+
+
+ Add the r-fit-text class to auto-size text
Hit the next arrow...
... to step through ...
-... a fragmented slide.
++ ... a fragmented + slide. +
- You can select from different transitions, like:
- reveal.js comes with a few themes built in:
- Set
- Different background transitions are available via the backgroundTransition option. This one's called "zoom".
+ Different background transitions are available via the backgroundTransition option. This
+ one's called "zoom".
- You can override background transitions per-slide.
- You can override background transitions per-slide. Since reveal.js runs on the web, you can easily embed other web content. Try interacting with the page in the background.
+ Since reveal.js runs on the web, you can easily embed other web content. Try
+ interacting with the page in the background.
+
- These guys come in two forms, inline: There's a speaker view. It includes a timer, preview of the upcoming slide as well as your speaker notes.
+ There's a speaker view. It includes a
+ timer, preview of the upcoming slide as well as your speaker notes.
+ Press the S key to try it out. Presentations can be exported to PDF, here's an example:
+ Presentations can be exported to PDF,
+ here's an example:
+
- Additionally custom events can be triggered on a per slide basis by binding to the
- Press B or . on your keyboard to pause the presentation. This is helpful when you're on stage and want to take distracting slides off the screen.
+ Press B or . on your keyboard to pause the presentation. This is helpful when you're on
+ stage and want to take distracting slides off the screen.
- - Try the online editor Utviklerforum 14.12.2017
- Kai Vaade (KIA), Simeon Simeonov (INT)
- Vi bruker RabbitMQ med AMQP 0.9.1 til å utveksle / behandle meldinger (JSON, SCIM) Bruk av message-broker startet i 2015. I produksjon siden høsten 2017. Driftes av KIA. Cerebrum har brukt MQ et års tid på egen server satt opp av Seksjon for integrasjon og elektroniske identiteter (USITINT). Nå er driften av tjenesten flyttet fra prosjektet og inn i linja, Gruppe for drift av katalog-, integrasjon- og autentiseringstjenester (KIA). Vi har softlaunchet meldingskø-tjenesten i høst. Tjenesten er ikke "offisielt" lansert, kjører kun våre egne ting (Cerebrum/SAP) foreløpig. Antakelig gjør vi tjenesten kjent samtidig som et annet delprosjekt (API Manager) i UiO INTARK lanseres i nær fremtid. Foreløpig så har vi ikke så veldig mye erfaring med tjenesten i linja. Vi vet heller ikke så mye om behovet; dvs hvor mange som kommer til å bruke tjenesten. Hvordan kontakte oss: https://www.usit.uio.no/om/organisasjon/iti/td/kia/dokumentasjon/meldingsko/ Tilgang til grensesnittet: https://mq.uio.no Roller: Entiteter: RabbitMQ implementerer 2 rettighetsnivåer: per vhost og per entitet RabbitMQ (AMQP) definerer 3 typer operasjoner: configure - opprette / slette entiteter eller endre deres oppførsel write - skrive melding til en entitet read - lese melding fra entitet RabbitMQ bruker regular expressions til å definere rettigheter rabbitmqctl add_user cerebrum <passord> rabbitmqctl add_user uio_ad_microservice <passord> rabbitmqctl set_permissions -p /no/uio/integration cerebrum "^$" "^ex_.*" "^$" rabbitmqctl set_permissions -p /no/uio/integration uio_ad_microservice "^q_ad_ms_.*" "^q_ad_ms_.*" "^(ex_messages|q_ad_ms_.*)$" Routing key settes av sender som en del av meldingen og blir inspisert av brokeren dersom meldingen sendes til en topic exchange. Strukturen til en topic / message routing key er: <kilde>.<type>.<objekt>.<hendelse> F.eks.: cerebrum.event.person.delete
- RabbitMQ:
-
-
- http://www.rabbitmq.com - RabbitMQ sin offisielle side
-
-
-
- http://www.rabbitmq.com/configure.html - Generell konfigurasjon av RabbitMQ
-
-
-
- http://www.rabbitmq.com/management.html - Bruk av rabbitmq_management plugin i RabbitMQ
-
-
-
- http://www.rabbitmq.com/access-control.html - Tilgangskontroll i RabbitMQ
-
-
-
- http://www.rabbitmq.com/man/rabbitmqctl.1.man.html - rabbitmqctl manual side
-
-
-
- http://www.rabbitmq.com/tutorials/amqp-concepts.html - Generelt om AMQP og forskjellige exchanges
-
-
- UiO:
-
-
- Installasjon og oppsett av RabbitMQ for Cerebrum utviklere
-
-
-
- Oppsett av RabbitMQ for Office365 integrasjon mot UiA
-
-
-
- Utredning: Meldingsflyt, kø-struktur og navngiving (intern)
-
-
- Bøker:
-
-
- RabbitMQ in action - Alvaro Videla / Jason J.W. Williams - 2012 - Manning
-
-
-
- Mastering RabbitMQ - Ayanoglu / Aytas / Nahum - 2015 - PACKT Publishing
-
- Simeon Simeonov Simeon Simeonov pgBadger - a fast PostgreSQL log analysis report can be used for general analysis. pgBadger - a fast PostgreSQL log analysis report can be used for general analysis.
- https://www.postgresql.org/docs/ - The official documentation
-
- https://wiki.postgresql.org - The official Wiki
-
+ https://www.postgresql.org/docs/ - The official documentation
+
+ https://wiki.postgresql.org - The official Wiki
+
- Simeon Simeonov
- Skaffe seg maskin og SSL sertifikat(er) Bruke Ansible Opprette administrator-bruker og slette guest-brukeren Sette rettigheter og opprette entiteter Vi bruker repo UAIT/int-ansible-hosts Etter å ha installert Ansible på lokalmaskina gjør vi følgende: git clone ssh://git@bitbucket.usit.uio.no:7999/uait/int-ansible-hosts.git cd int-ansible-hosts ansible-playbook --ask-become-pass -v --extra-vars '{"hosts": "mq-hostname"}' rabbitmq_playbook.yml RabbitMQ skal nå være installert og tilgjengelig på https://mq-hostname Brukeren guest med passord guest vil eksistere etter at Ansible har kjørt I tillegg til webgrensesnittet, kan en bruke rabbitmqctl rabbitmqctl list_users (Lister alle eksisterende RabbitMQ-brukere) rabbitmqctl add_user rmq_admin <passord> (Legger til dedikert admin bruker rmq_admin) rabbitmqctl set_user_tags rmq_admin administrator (Gir administrator rolle til rmq_admin) rabbitmqctl delete_user guest (Sletter brukeren guest) vhost fungerer som en beholder (container) for RabbitMQ/AMQP objekter. Nok igjen kan en velge mellom webgrensesnitt og rabbitmqctl rabbitmqctl list_vhosts (Lister alle eksisterende vhosts) rabbitmqctl add_vhost /no/uio/integration (Oppretter vhost med navn /no/uio/integration) RabbitMQ implementerer 2 rettighetsnivåer(*): RabbitMQ definerer 3 typer operasjoner: configure - opprette / slette entiteter eller endre deres oppførsel write - skrive melding til en entitet read - lese melding fra entitet (*) - /etc/rabbitmq/rabbitmq.config gir flere muligheter RabbitMQ bruker regular expressions til å definere rettigheter rabbitmqctl add_user cerebrum <passord> rabbitmqctl add_user uio_ad_microservice <passord> rabbitmqctl set_permissions -p /no/uio/integration cerebrum "^$" "^ex_.*" "^$" rabbitmqctl set_permissions -p /no/uio/integration uio_ad_microservice "^q_ad_ms_.*" "^q_ad_ms_.*" "^(ex_messages|q_ad_ms_.*)$" Køer defineres som durable ved hjelp av webgrensesnittet. "Alle køer (både forhåndsdefinerte og de som defineres av konsument) må ha navn som starter med q_. Køen vil ha navn som uttryker mottakeren som bruker den." F.eks. q_ad_ms_all vil være et passende navn for køen som brukes av AD-microservice mottakeren. "Avsendere vil vanligvis sende meldinger til exchange ex_messages." Det er flere typer exchange, men vi vil bruke kun topic exchange. Routing keys i topic exchange Bindinger Protokoller og porter Eksempler Routing key settes av sender som en del av meldingen og blir inspisert av brokeren dersom meldingen sendes til en topic exchange. Strukturen til en topic / message routing key er: <kilde>.<type>.<objekt>.<hendelse> F.eks.: cerebrum.event.person.delete For at en melding sendt til en topic exchange skal havne i en bestemt kø, må køen være bundet (bound) til exchange. I topic exchange brukes routing key (topic) til å avgjøre hvilke av meldingene som blir sendt vil havne i køen som er bundet. Dersom vi binder køen q_ad_ms_all til topic exchange ex_messages med binding key cerebrum.event.account.* vil alle meldinger som blir sendt til ex_messages med topic som starter med cerebrum.event.account. havne i q_ad_ms_all. En kø kan bli bundet med én eller flere nøkler til en topic exchange. "AMQP 0.9.1 prioritert siden det er protokollen som mapper best mot RabbitMQs funksjonalitet. Vi har også noe erfaring med bruk av denne." RabbitMQ lytter for AMQP0.9.1 på SSL port 5671. Andre protokoller og tjenester for RabbitMQ: Python: "Well, we'll not risk another frontal assault. That rabbit's dynamite...."
- RabbitMQ:
-
-
- http://www.rabbitmq.com - RabbitMQ sin offisielle side
-
-
-
- http://www.rabbitmq.com/configure.html - Generell konfigurasjon av RabbitMQ
-
-
-
- http://www.rabbitmq.com/management.html - Bruk av rabbitmq_management plugin i RabbitMQ
-
-
-
- http://www.rabbitmq.com/access-control.html - Tilgangskontroll i RabbitMQ
-
-
-
- http://www.rabbitmq.com/man/rabbitmqctl.1.man.html - rabbitmqctl manual side
-
-
-
- http://www.rabbitmq.com/tutorials/amqp-concepts.html - Generelt om AMQP og forskjellige exchanges
-
-
- UiO:
-
-
- Installasjon og oppsett av RabbitMQ for Cerebrum utviklere
-
-
-
- Oppsett av RabbitMQ for Office365 integrasjon mot UiA
-
-
-
- Utredning: Meldingsflyt, kø-struktur og navngiving (intern)
-
-
- Bøker:
-
-
- RabbitMQ in action - Alvaro Videla / Jason J.W. Williams - 2012 - Manning
-
-
-
- Mastering RabbitMQ - Ayanoglu / Aytas / Nahum - 2015 - PACKT Publishing
-
- Simeon Simeonov Simeon Simeonov SQLAlchemy is a Python library created by Mike Bayer to provide a high-level Pythonic interface to RDBMS such as PostgreSQL, SQLite, MySQL, Oracle, DB2. SQLAlchemy includes RDBMS-independent SQL expression language and an object-relational mapper (ORM). SQLAlchemy is a Python library created by Mike Bayer to provide a high-level Pythonic interface to RDBMS such as PostgreSQL, SQLite, MySQL, Oracle, DB2. SQLAlchemy includes RDBMS-independent SQL expression language and an object-relational mapper (ORM). free software - free as in "freedom" (MIT licensed) portability - the programming interface is independent of the type of RDBMS and connector used security - no more SQL injections abstraction - no need to bother with complex JOINs object-orientation - you work with objects instead of tables and rows performance - exploits the likehood of reusing a particular query flexibility - you can override almost anything free software - free as in "freedom" (MIT licensed) portability - the programming interface is independent of the type of RDBMS and connector used security - no more SQL injections abstraction - no need to bother with complex JOINs object-orientation - you work with objects instead of tables and rows performance - exploits the likehood of reusing a particular query flexibility - you can override almost anything SQLAlchemy consists of several components, including the ORM. SQLAlchemy gives us the choice between classical mapping and the newer declarative mapping SQLAlchemy consists of several components, including the ORM. SQLAlchemy gives us the choice between classical mapping and the newer declarative mapping Tomas Robertson (team ACE-OL) & Simeon Simeonov (team Forecasts) Time travel - our ability to look at our input data at the state it was at a specific point in time (not only at its last state). Time travel is achieved by adding the record_created_time column to our DB tables and storing Kafka's created_time value (converted to UTC). The main concepts around how and why were presented by Peter Sandberg. The following spike was observed 2021-10-06 around 10:15 CET @ NO4 No spikes shown in Grafana
+ You can select from different transitions, like:
None -
Fade -
Slide -
@@ -247,19 +342,73 @@
Themes
+ reveal.js comes with a few themes built in:
- Black (default) -
- White -
- League -
- Sky -
- Beige -
- Simple
- Serif -
- Blood -
- Night -
- Moon -
- Solarized
+ Black (default)
+ -
+ White
+ -
+ League
+ -
+ Sky
+ -
+ Beige
+ -
+ Simple
+
+ Serif
+ -
+ Blood
+ -
+ Night
+ -
+ Moon
+ -
+ Solarized
Slide Backgrounds
data-background="#dddddd" on a slide to change the background color. All CSS color formats are supported.
+ Set data-background="#dddddd" on a slide to change the background color.
+ All CSS color formats are supported.
+
Image Backgrounds
<section data-background="image.png">Tiled Backgrounds
<section data-background="image.png" data-background-repeat="repeat" data-background-size="100px">Video Backgrounds
<section data-background-video="video.mp4,video.webm">Background Transitions
Reveal.configure({ backgroundTransition: 'zoom' })Background Transitions
- <section data-background-transition="zoom">Iframe Backgrounds
- Clever Quotes
The nice thing about standards is that there are so many to choose from
and block:
+ These guys come in two forms, inline:
+ The nice thing about standards is that there are so many to choose from
+ and block:
- “For years there has been a theory that millions of monkeys typing at random on millions of typewriters would
- reproduce the entire works of Shakespeare. The Internet has proven this theory to be untrue.”
+
+ “For years there has been a theory that millions of monkeys typing at random on
+ millions of typewriters would reproduce the entire works of Shakespeare. The Internet
+ has proven this theory to be untrue.”
Speaker View
- Export to PDF
- State Events
data-state name.
+ Additionally custom events can be triggered on a per slide basis by binding to the
+ data-state name.
Reveal.on( 'customevent', function() {
@@ -428,7 +641,8 @@ Reveal.on( 'customevent', function() {
Take a Moment
THE END
+ - Try the online editor
- Source code & documentation
Meldingskø for UiO
-
- Agenda
-
-
-
- Generelt
-
- Administrasjon
- Administrasjon (forts...)
- Administrasjon (forts...)
- Administrasjon (forts...)
- Roller og entiteter
-
-
- Flyt
-
-
- Rettigheter
-
-
- Rettigheter og brukere
-
-
- Routing keys i topic exchange
- Dokumentasjon og lenker
-
-
- Dokumentasjon og lenker
-
-
-
-
Q & A
- PostgreSQL tuning
- Data Science @ Beryl
+
+
+ PostgreSQL tuning
+ Data Science @ Beryl
- Agenda
+ Agenda
-
- General tools for gathering information
+ General tools for gathering information
-
-
- # shell
- # fetch information from the OS
- cat /proc/cpuinfo
- cat /proc/meminfo
- sysctl -a | grep shm # get kernel parameters of interest
-
-
- -- SQL
- -- show the current values of all settings
- SHOW ALL;
-
- -- display even more than all...
- SELECT * FROM pg_settings;
-
- -- opening postgresql.conf and reading the comments - the old school approach
-
-
- # old school: edit postgresql.conf and read the comments
-
+
+ # shell
+ # fetch information from the OS
+ cat /proc/cpuinfo
+ cat /proc/meminfo
+ sysctl -a | grep shm # get kernel parameters of interest
+
+
+ -- SQL
+ -- show the current values of all settings
+ SHOW ALL;
+
+ -- display even more than all...
+ SELECT * FROM pg_settings;
+
+ -- opening postgresql.conf and reading the comments - the old school approach
+
+
+ # old school: edit postgresql.conf and read the comments
+
Memory settings
+ Memory settings
-
- Logging and performance reports
+ Logging and performance reports
-
-
- Other tools for analysis
+
+
+ Other tools for analysis
-
- Sources
+ Sources
- Q & A
- Q & A
+ RabbitMQ
- Intern opplæring
-
- Agenda
-
-
-
- Installasjon og oppsett
-
-
-
- Ansible
-
-
-
- Administrator-bruker
-
-
-
- vhost
-
-
-
- Rettigheter
-
-
-
-
- Rettigheter og brukere
-
-
- Køer
- Exchange
- Utvikling
-
-
-
- Routing keys i topic exchange
-
- Bindinger
- Protokoller og porter
-
-
-
- Eksempler
-
-
-
-
- $ pip install pika
-
- Dokumentasjon og lenker
-
-
-
- Dokumentasjon og lenker
-
-
-
-
Q&A
- SQLAlchemy
- Data Engineering @ Statnett
+
+
+ SQLAlchemy
+ Data Engineering @ Statnett
- Agenda
+ Agenda
-
- What is SQLAlchemy?
+ What is SQLAlchemy?
- Why use SQLAlchemy?
+ Why use SQLAlchemy?
-
- Basic architecture
-
-
-
- Example
-
-
-
- # option 1: classical mapping
- # explicitly defining Table objects and mapping them to pure Python base classes
- from sqlalchemy import create_engine
-
- # engine = create_engine("postgresql+psycopg2://user:zipassword@localhost/mydb" , echo=True)
- # The string form of the URL is dialect+driver://user:password@host/dbname[?key=value..],
- # engine = create_engine("sqlite:///library.db", echo=True)
- engine = create_engine("sqlite:///:memory:", echo=True)
-
- from sqlalchemy import Column, MetaData, Table
- from sqlalchemy import DateTime, ForeignKey, Integer, Numeric, String
-
- metadata = MetaData()
-
- production_types_table = Table(
- "production_types",
- metadata,
- Column("production_type_id", Integer, primary_key=True),
- Column("code", String(3), nullable=False, unique=True),
- Column("description", String), # Column("name", String(128)) is possible
- )
-
- bidding_areas_table = Table(
- "bidding_areas",
- metadata,
- Column("bidding_area_id", Integer, primary_key=True),
- Column("code", String(3), nullable=False, unique=True),
- Column("name", String(32)),
- )
-
- production_plans_table = Table(
- "production_plans",
- metadata,
- Column("record_created_time", DateTime(timezone=False), primary_key=True),
- Column("start_time", DateTime(timezone=False), primary_key=True),
- Column("bidding_area_id", Integer, ForeignKey("bidding_areas.bidding_area_id"), primary_key=True),
- Column("production_type_id", Integer, ForeignKey("production_types.production_type_id"), primary_key=True),
- Column("value", Numeric, nullable=False),
- )
-
- metadata.create_all(engine) # creates the tables
-
- Example (cont...)
- Use of SQL expression language
-
-
-
- # option 1: classical mapping (continues)
- # Using the SQL expression language (low level interface)
- from sqlalchemy import text
-
- insert_stmt = bidding_areas_table.insert(bind=engine)
- type(insert_stmt)
- # Out: <class 'sqlalchemy.sql.dml.Insert'>
- print(insert_stmt)
- # Out: INSERT INTO bidding_areas (bidding_area_id, code, name) VALUES (?, ?, ?)
-
- compiled_stmt = insert_stmt.compile()
- print(compiled_stmt.params)
- # Out: {'bidding_area_id': None, 'code': None, 'name': None}
-
- insert_stmt.execute(bidding_area_id=1, code="NO1", name="Elspot NO1") # insert a single entry
- # ... or a list of entries
- insert_stmt.execute(
- [
- {"bidding_area_id": 2, "code": "NO2", "name": "Elspot NO2"},
- {"bidding_area_id": 3, "code": "NO3", "name": "Elspot NO3"},
- {"bidding_area_id": 4, "code": "NO4", "name": "Elspot NO4"},
- {"bidding_area_id": 5, "code": "NO5", "name": "Elspot NO5"},
- {"bidding_area_id": 6, "code": "NO6", "name": "Elspot NO6"},
- ]
- )
-
- metadata.bind = engine # no need to explicitly bind the engine from now on
- select_stmt = bidding_areas_table.select(bidding_areas_table.c.bidding_area_id==2)
- result = select_stmt.execute()
- result.fetchall()
- # Out: [(2, 'NO2', 'Elspot NO2')]
-
- del_stmt = bidding_areas_table.delete()
- del_stmt.execute(whereclause=text("name='Elspot NO6'"))
- del_stmt.execute() # delete NO6
-
- Example (cont...)
- Use of classical mapping
-
-
-
- # option 1: classical mapping (continues)
- # Defining regular base classes and mapping them to the Table objects
- from sqlalchemy.orm import mapper
-
- class ProductionType:
- def __init__(self, code, description):
- self.code = code
- self.description = description
-
- def __str__(self):
- return self.code
-
-
- class BiddingArea:
- def __init__(self, code, name):
- self.code = code
- self.name = name
-
- def __str__(self):
- return self.code
-
- mapper(ProductionType, production_types_table)
- mapper(BiddingArea, bidding_areas_table)
-
- Example (cont...)
- Use of classical mapping
-
-
-
- from sqlalchemy.orm import relationship
-
- class ProductionPlan:
- def __init__(self, record_created_time, start_time, production_type, bidding_area, value):
- self.record_created_time = record_created_time
- self.start_time = start_time
- self.production_type = production_type
- self.bidding_area = bidding_area
- self.value = value
-
- def __str__(self):
- return (
- f"{self.record_created_time} {self.start_time} "
- f"{self.production_type} {self.bidding_area} {self.value}"
- )
-
-
- mapper(
- ProductionPlan,
- production_plans_table,
- properties = {
- "production_type": relationship(ProductionType, backref="production_plans"),
- "bidding_area": relationship(BiddingArea, backref="production_plans"),
- },
- )
-
- Example (cont...)
- Doing the same thing the easy way with declarative mapping
-
-
-
- # option 2: declarative mapping
- from sqlalchemy.ext.declarative import declarative_base
-
- Base = declarative_base()
-
- class ProductionType(Base):
- __tablename__ = "production_types"
-
- production_type_id = Column(Integer, primary_key=True)
- code = Column(String(3), nullable=False, unique=True)
- description = Column(String)
-
- def __init__(self, code, description):
- self.code = code
- self.description = description
-
- def __str__(self):
- return self.code
-
- class BiddingArea(Base):
- __tablename__ = "bidding_areas"
-
- bidding_area_id = Column(Integer, primary_key=True)
- code = Column(String(3), nullable=False, unique=True)
- name = Column(String(32))
-
- def __init__(self, code, name):
- self.code = code
- self.name = name
-
- def __str__(self):
- return self.code
-
- Example (cont...)
- Doing the same thing the easy way with declarative mapping
-
-
-
- # option 2: declarative mapping (continues)
- from sqlalchemy.orm import relationship, backref
-
- class ProductionPlan(Base):
- __tablename__ = "production_plans"
-
- record_created_time = Column(DateTime(timezone=False), primary_key=True)
- start_time = Column(DateTime(timezone=False), primary_key=True)
- bidding_area_id = Column(Integer, ForeignKey("bidding_areas.bidding_area_id"), primary_key=True)
- production_type_id = Column(Integer, ForeignKey("production_types.production_type_id"), primary_key=True)
- value = Column(Numeric, nullable=False)
-
- # defining relationships.
- # the defined attributes will reference 'ProductionType' and 'BiddingArea' objects
- production_type = relationship(ProductionType, backref=backref("production_plans"))
- bidding_area = relationship(BiddingArea, backref=backref("production_plans"))
-
- def __init__(self, record_created_time, start_time, production_type, bidding_area, value):
- self.record_created_time = record_created_time
- self.start_time = start_time
- self.production_type = production_type # a 'ProductionType' object
- self.bidding_area = bidding_area # a 'BiddingArea' object
- self.value = value
-
- def __str__(self):
- return (
- f"{self.record_created_time} {self.start_time} "
- f"{self.production_type} {self.bidding_area} {self.value}"
- )
-
- Base.metadata.create_all(engine) # create tables
-
- Example (cont...)
- Creating instances
-
-
-
- # adding some data...
- import datetime
- import decimal
-
- from sqlalchemy.orm import sessionmaker
-
- Session = sessionmaker(bind=engine) # bound session
- session = Session()
-
- bidding_area1 = BiddingArea("NO1", "Elspot NO1")
- session.add(bidding_area1)
-
- session.add_all(
- [
- BiddingArea("NO2", "Elspot NO2"),
- BiddingArea("NO3", "Elspot NO3"),
- BiddingArea("NO4", "Elspot NO4"),
- BiddingArea("NO5", "Elspot NO5"),
- ]
- )
-
- production_type_B37 = ProductionType("B37", "Thermal unspecified")
- production_type_B30 = ProductionType("B30", "Wind unspecified")
-
- session.add_all(
- [
- ProductionType("B19", "Wind Onshore"),
- ProductionType("B10", "Hydro-electric pure pumped storage head installation"),
- ProductionType("B11", "Hydro Run-of-river head installation"),
- ProductionType("B12", "Hydro-electric storage head installation"),
- ProductionType("A04", "Generation"),
- production_type_B37,
- production_type_B30,
- ]
- )
-
- Example (cont...)
- Creating instances
-
-
-
- # adding some production plans...
-
- session.add(
- ProductionPlan(
- datetime.datetime.now(),
- datetime.datetime(2022, 11, 2, 1, 0),
- production_type_B37,
- bidding_area1,
- decimal.Decimal("80.5"),
- )
- )
-
- production_plan2 = ProductionPlan(
- datetime.datetime.now(),
- datetime.datetime(2022, 11, 2, 2, 0),
- production_type_B37,
- bidding_area1,
- decimal.Decimal("90.5"),
- )
-
- session.add(production_plan2)
-
- session.flush() # execute pending operations
- session.commit() # execute and commit pending operations
-
- production_plan2.value = decimal.Decimal("70.5")
- production_plan2 in session
- # Out: True
-
- session.commit()
-
- Example (cont...)
- Queries
-
-
-
- import pandas as pd
-
- session.query(ProductionPlan).order_by(ProductionPlan.start_time) # returns a Query instance
- session.query(ProductionPlan).order_by(ProductionPlan.start_time).all() # returns an object-list
-
- # return all production plans where start_time after 2022-09-01 00:00
- session.query(ProductionPlan).filter(ProductionPlan.start_time > datetime.datetime(2022, 9, 1, 0, 0)).all()
-
- # return production plans with value > 80
- query = session.query(ProductionPlan).filter(ProductionPlan.value > 80).order_by(ProductionPlan.start_time)
- query.count() # returns 1
- production_plan = query.first() # returns the first object (element)
- production_plan = query.one() # raises NoResultFound exception or MultipleResultsFound in case elements != 1
-
- # generate Pandas DataFrame from a query or entire table
- df = pd.read_sql_table("my_table", con=session.get_bind()) # or con=engine
- df = pd.read_sql_query(query.statement, engine)
-
- # return production plans with production type 'B37'
- session.query(ProductionPlan).filter(
- ProductionPlan.production_type_id == ProductionType.production_type_id
- ).filter(ProductionType.code == "B37").all()
- session.query(ProductionPlan).join(ProductionType).filter(ProductionType.code == "B37").all()
- session.query(ProductionPlan).filter(ProductionPlan.production_type == production_type_B37).all()
- session.query(
- ProductionPlan
- ).from_statement(
- text(
- "SELECT pp.* FROM production_plans pp, production_types pt "
- "WHERE pp.production_type_id = pt.production_type_id AND pt.code=:code"
- )
- ).params(code="B37").all()
-
- Q & A
- Basic architecture
+
+
+
+ Example
+
+
+
+ # option 1: classical mapping
+ # explicitly defining Table objects and mapping them to pure Python base classes
+ from sqlalchemy import create_engine
+
+ # engine = create_engine("postgresql+psycopg2://user:zipassword@localhost/mydb" , echo=True)
+ # The string form of the URL is dialect+driver://user:password@host/dbname[?key=value..],
+ # engine = create_engine("sqlite:///library.db", echo=True)
+ engine = create_engine("sqlite:///:memory:", echo=True)
+
+ from sqlalchemy import Column, MetaData, Table
+ from sqlalchemy import DateTime, ForeignKey, Integer, Numeric, String
+
+ metadata = MetaData()
+
+ production_types_table = Table(
+ "production_types",
+ metadata,
+ Column("production_type_id", Integer, primary_key=True),
+ Column("code", String(3), nullable=False, unique=True),
+ Column("description", String), # Column("name", String(128)) is possible
+ )
+
+ bidding_areas_table = Table(
+ "bidding_areas",
+ metadata,
+ Column("bidding_area_id", Integer, primary_key=True),
+ Column("code", String(3), nullable=False, unique=True),
+ Column("name", String(32)),
+ )
+
+ production_plans_table = Table(
+ "production_plans",
+ metadata,
+ Column("record_created_time", DateTime(timezone=False), primary_key=True),
+ Column("start_time", DateTime(timezone=False), primary_key=True),
+ Column("bidding_area_id", Integer, ForeignKey("bidding_areas.bidding_area_id"), primary_key=True),
+ Column("production_type_id", Integer, ForeignKey("production_types.production_type_id"), primary_key=True),
+ Column("value", Numeric, nullable=False),
+ )
+
+ metadata.create_all(engine) # creates the tables
+
+ Example (cont...)
+ Use of SQL expression language
+
+
+
+ # option 1: classical mapping (continues)
+ # Using the SQL expression language (low level interface)
+ from sqlalchemy import text
+
+ insert_stmt = bidding_areas_table.insert(bind=engine)
+ type(insert_stmt)
+ # Out: <class 'sqlalchemy.sql.dml.Insert'>
+ print(insert_stmt)
+ # Out: INSERT INTO bidding_areas (bidding_area_id, code, name) VALUES (?, ?, ?)
+
+ compiled_stmt = insert_stmt.compile()
+ print(compiled_stmt.params)
+ # Out: {'bidding_area_id': None, 'code': None, 'name': None}
+
+ insert_stmt.execute(bidding_area_id=1, code="NO1", name="Elspot NO1") # insert a single entry
+ # ... or a list of entries
+ insert_stmt.execute(
+ [
+ {"bidding_area_id": 2, "code": "NO2", "name": "Elspot NO2"},
+ {"bidding_area_id": 3, "code": "NO3", "name": "Elspot NO3"},
+ {"bidding_area_id": 4, "code": "NO4", "name": "Elspot NO4"},
+ {"bidding_area_id": 5, "code": "NO5", "name": "Elspot NO5"},
+ {"bidding_area_id": 6, "code": "NO6", "name": "Elspot NO6"},
+ ]
+ )
+
+ metadata.bind = engine # no need to explicitly bind the engine from now on
+ select_stmt = bidding_areas_table.select(bidding_areas_table.c.bidding_area_id==2)
+ result = select_stmt.execute()
+ result.fetchall()
+ # Out: [(2, 'NO2', 'Elspot NO2')]
+
+ del_stmt = bidding_areas_table.delete()
+ del_stmt.execute(whereclause=text("name='Elspot NO6'"))
+ del_stmt.execute() # delete NO6
+
+ Example (cont...)
+ Use of classical mapping
+
+
+
+ # option 1: classical mapping (continues)
+ # Defining regular base classes and mapping them to the Table objects
+ from sqlalchemy.orm import mapper
+
+ class ProductionType:
+ def __init__(self, code, description):
+ self.code = code
+ self.description = description
+
+ def __str__(self):
+ return self.code
+
+
+ class BiddingArea:
+ def __init__(self, code, name):
+ self.code = code
+ self.name = name
+
+ def __str__(self):
+ return self.code
+
+ mapper(ProductionType, production_types_table)
+ mapper(BiddingArea, bidding_areas_table)
+
+ Example (cont...)
+ Use of classical mapping
+
+
+
+ from sqlalchemy.orm import relationship
+
+ class ProductionPlan:
+ def __init__(self, record_created_time, start_time, production_type, bidding_area, value):
+ self.record_created_time = record_created_time
+ self.start_time = start_time
+ self.production_type = production_type
+ self.bidding_area = bidding_area
+ self.value = value
+
+ def __str__(self):
+ return (
+ f"{self.record_created_time} {self.start_time} "
+ f"{self.production_type} {self.bidding_area} {self.value}"
+ )
+
+
+ mapper(
+ ProductionPlan,
+ production_plans_table,
+ properties = {
+ "production_type": relationship(ProductionType, backref="production_plans"),
+ "bidding_area": relationship(BiddingArea, backref="production_plans"),
+ },
+ )
+
+ Example (cont...)
+ Doing the same thing the easy way with declarative mapping
+
+
+
+ # option 2: declarative mapping
+ from sqlalchemy.ext.declarative import declarative_base
+
+ Base = declarative_base()
+
+ class ProductionType(Base):
+ __tablename__ = "production_types"
+
+ production_type_id = Column(Integer, primary_key=True)
+ code = Column(String(3), nullable=False, unique=True)
+ description = Column(String)
+
+ def __init__(self, code, description):
+ self.code = code
+ self.description = description
+
+ def __str__(self):
+ return self.code
+
+ class BiddingArea(Base):
+ __tablename__ = "bidding_areas"
+
+ bidding_area_id = Column(Integer, primary_key=True)
+ code = Column(String(3), nullable=False, unique=True)
+ name = Column(String(32))
+
+ def __init__(self, code, name):
+ self.code = code
+ self.name = name
+
+ def __str__(self):
+ return self.code
+
+ Example (cont...)
+ Doing the same thing the easy way with declarative mapping
+
+
+
+ # option 2: declarative mapping (continues)
+ from sqlalchemy.orm import relationship, backref
+
+ class ProductionPlan(Base):
+ __tablename__ = "production_plans"
+
+ record_created_time = Column(DateTime(timezone=False), primary_key=True)
+ start_time = Column(DateTime(timezone=False), primary_key=True)
+ bidding_area_id = Column(Integer, ForeignKey("bidding_areas.bidding_area_id"), primary_key=True)
+ production_type_id = Column(Integer, ForeignKey("production_types.production_type_id"), primary_key=True)
+ value = Column(Numeric, nullable=False)
+
+ # defining relationships.
+ # the defined attributes will reference 'ProductionType' and 'BiddingArea' objects
+ production_type = relationship(ProductionType, backref=backref("production_plans"))
+ bidding_area = relationship(BiddingArea, backref=backref("production_plans"))
+
+ def __init__(self, record_created_time, start_time, production_type, bidding_area, value):
+ self.record_created_time = record_created_time
+ self.start_time = start_time
+ self.production_type = production_type # a 'ProductionType' object
+ self.bidding_area = bidding_area # a 'BiddingArea' object
+ self.value = value
+
+ def __str__(self):
+ return (
+ f"{self.record_created_time} {self.start_time} "
+ f"{self.production_type} {self.bidding_area} {self.value}"
+ )
+
+ Base.metadata.create_all(engine) # create tables
+
+ Example (cont...)
+ Creating instances
+
+
+
+ # adding some data...
+ import datetime
+ import decimal
+
+ from sqlalchemy.orm import sessionmaker
+
+ Session = sessionmaker(bind=engine) # bound session
+ session = Session()
+
+ bidding_area1 = BiddingArea("NO1", "Elspot NO1")
+ session.add(bidding_area1)
+
+ session.add_all(
+ [
+ BiddingArea("NO2", "Elspot NO2"),
+ BiddingArea("NO3", "Elspot NO3"),
+ BiddingArea("NO4", "Elspot NO4"),
+ BiddingArea("NO5", "Elspot NO5"),
+ ]
+ )
+
+ production_type_B37 = ProductionType("B37", "Thermal unspecified")
+ production_type_B30 = ProductionType("B30", "Wind unspecified")
+
+ session.add_all(
+ [
+ ProductionType("B19", "Wind Onshore"),
+ ProductionType("B10", "Hydro-electric pure pumped storage head installation"),
+ ProductionType("B11", "Hydro Run-of-river head installation"),
+ ProductionType("B12", "Hydro-electric storage head installation"),
+ ProductionType("A04", "Generation"),
+ production_type_B37,
+ production_type_B30,
+ ]
+ )
+
+ Example (cont...)
+ Creating instances
+
+
+
+ # adding some production plans...
+
+ session.add(
+ ProductionPlan(
+ datetime.datetime.now(),
+ datetime.datetime(2022, 11, 2, 1, 0),
+ production_type_B37,
+ bidding_area1,
+ decimal.Decimal("80.5"),
+ )
+ )
+
+ production_plan2 = ProductionPlan(
+ datetime.datetime.now(),
+ datetime.datetime(2022, 11, 2, 2, 0),
+ production_type_B37,
+ bidding_area1,
+ decimal.Decimal("90.5"),
+ )
+
+ session.add(production_plan2)
+
+ session.flush() # execute pending operations
+ session.commit() # execute and commit pending operations
+
+ production_plan2.value = decimal.Decimal("70.5")
+ production_plan2 in session
+ # Out: True
+
+ session.commit()
+
+ Example (cont...)
+ Queries
+
+
+
+ import pandas as pd
+
+ session.query(ProductionPlan).order_by(ProductionPlan.start_time) # returns a Query instance
+ session.query(ProductionPlan).order_by(ProductionPlan.start_time).all() # returns an object-list
+
+ # return all production plans where start_time after 2022-09-01 00:00
+ session.query(ProductionPlan).filter(ProductionPlan.start_time > datetime.datetime(2022, 9, 1, 0, 0)).all()
+
+ # return production plans with value > 80
+ query = session.query(ProductionPlan).filter(ProductionPlan.value > 80).order_by(ProductionPlan.start_time)
+ query.count() # returns 1
+ production_plan = query.first() # returns the first object (element)
+ production_plan = query.one() # raises NoResultFound exception or MultipleResultsFound in case elements != 1
+
+ # generate Pandas DataFrame from a query or entire table
+ df = pd.read_sql_table("my_table", con=session.get_bind()) # or con=engine
+ df = pd.read_sql_query(query.statement, engine)
+
+ # return production plans with production type 'B37'
+ session.query(ProductionPlan).filter(
+ ProductionPlan.production_type_id == ProductionType.production_type_id
+ ).filter(ProductionType.code == "B37").all()
+ session.query(ProductionPlan).join(ProductionType).filter(ProductionType.code == "B37").all()
+ session.query(ProductionPlan).filter(ProductionPlan.production_type == production_type_B37).all()
+ session.query(
+ ProductionPlan
+ ).from_statement(
+ text(
+ "SELECT pp.* FROM production_plans pp, production_types pt "
+ "WHERE pp.production_type_id = pt.production_type_id AND pt.code=:code"
+ )
+ ).params(code="B37").all()
+
+ Q & A
+ Solving problems using time travel
- Beryl @ Fifty
-
- What is time travel???
-
-
- Solving problems
-
-
- Solving problems (cont)
-
-
- Solving problems with time travel
-
-
-
-
-
- SELECT record_created_time, start_time, value
- FROM misc.app_odin_ace_ol_ba_10s_avro_v01
- WHERE bidding_area_name = 'NO4' AND start_time = '2021-10-06 08:14:10'
- ORDER BY record_created_time;
-
-
-
-
-
-
-
-
- record_created_time
- start_time
- value
-
-
- 2021-10-06 08:15:52.258
- 2021-10-06 08:14:10
- -370.37683609008127
-
-
- 2021-10-06 08:19:06.222
- 2021-10-06 08:14:10
- 25.183745117193457
-
-
-
- 2021-10-06 08:21:56.207
- 2021-10-06 08:14:10
- 34.78731922151518
- Q & A
-