Search

OakieTags

Who's online

There are currently 0 users and 23 guests online.

Recent comments

Oakies Blog Aggregator

Python Pass the Pigs

So I don’t doubt that many parents are bleeding out money for kid’s school fees, supplies, clothing and other demands this time of year.  How many of you are in their local Target, Walmart or other store and after filling the cart with the necessary, the kids eye up the toy aisle and start to ask for something?

Even teens are not immune and may be asking for games.  If you could turn around and say to them, “If you want the game, then why don’t you build it instead of buying it?”

Now as many of you have figured out, I’m starting to build an arsenal of Raspberry Pi content to teach in classes and meetups.  The following is to simulate the game “Pass the Pigs”.  If you’ve ever played this popular game that uses plastic pigs in the place of dice, it required my brain to rethink how I was coding my dice games to how I would code a game that used the fall placement of a plastic pig.  This demonstrated one of the greatest things about Python-  I still was using the same module, but I just used it in a different way to code my new game!

So let’s say we want to code a simple roll of dice game.

#Dice Roll
import random
#Insert space between import and code...
for x in range(1, 2):
dice_1 = random.randint(1, 6)
dice_2 = random.randint(1, 6)
print(dice_1 + ' + ' + dice_2)

The above code will do the following:

  1. Import the RANDOM module.
  2. Will “roll” the dice 2 times
  3. Will use two dice, with random calls of 1-6.
  4. Will output the first dice ‘+’ the second dice.

Now to change the code and create the Pass the Pigs game, we get to use the RANDOM module again,  but the code changes as we are going to use a function to tell Random what “word options” will be used instead of random numbers to return.  It will then use two pigs and then will output the roll, (which is a function).

#Pass the Pigs
import random

pig_fall = ['Razorback', 'Trotter', 'Snouter', 'Leaning Jowl', 'Pig Out', 'Oinker']
def pick_pigs():
        Pig1 = random.randint(0, len(pig_fall) -1)
        Pig2 = random.randint(0, len(pig_fall) -1)
        return pig_fall[Pig1] + ' + ' + pig_fall[Pig2]
print (pick_pigs())

This code is different from the first one, even though it really ends up doing the same thing.  Notice that there are six options, just like there are six sides to a die.  This is really very similar to the dice game, we’ve just used different code that works more efficiently with our requirements.  By execution the code, we can then play the game!

>sudo python3 .py
Leaning Jowl + Pig Out

Trotter + Pig Out

Leaning Jowl + Razorback

We can use the game instructions, (can be found online) to then add up our scores for our three players-

passthepigs

So there you have it and next time your kids ask you for toys and games, consider getting them a Raspberry Pi instead and make it pay forward, creating projects and games with it instead!

Until next time…

raspion

 

 



Tags:  ,


Del.icio.us



Facebook

TweetThis

Digg

StumbleUpon




Copyright © DBA Kevlar [Python Pass the Pigs], All Right Reserved. 2015.

Where is my tracefile

As a developer, you might have have been reading about SQL trace. After all, we all want to be able to diagnose and improve the performance of the code we write. So if you’ve googled on Oracle performance, you will have no doubt stumbled upon SQL trace.

So if you’ve run “alter session set sql_trace = true”, or perhaps “DBMS_MONITOR.SESSION_TRACE_ENABLE”.  you’re probably itching to get your hands on that trace file.  The question is – where is it ?  And that is the subject of my next quick tip…Enjoy

https://youtu.be/Xoq3lvxUTmY

Automation for DBA - Vagrant part 1

Vagrant is an open source tool for building a virtual environment. It is based on text based configuration file and concept of prebuilt OS boxes.
One can find a lot of boxes on Atlas webpage (https://atlas.hashicorp.com/boxes/search), ready to download and use.  Although if there are any security concerns about using a OS from 3rd party webpage, I published a blog post about creating a new Vagrant box using Oracle Linux here and Oracle Virtual Box.

For simplicity of this series, predefined Linux box will be used in all examples.
There are two boxes that I’m using in my own work.
First one “kikitux/oracle6-racattack” created by Alvaro Miranda (https://github.com/kikitux) member of Rac Attack team. The other one is “racattack/oracle65” created by Jeremy Schneider who is also member of RacAttack team.

Vagrant itself is not a Virtualization provider. It can control different virtualization tools, including:
-    Virtual Box
-    AWS EC2 (with an additional plugin)
-    KVM (with an additional plugin)
-    VMWare Fusion / Workstation (paid version of Vagrant)

Most of the differences between providers are hidden by Vagrant workflow, and a configuration file defining a Vagrant box is similar between different providers.
Vagrant user is using same set of commands to start, stop or destroy virtual machine and does not have to know which provider is used for that.

There is a list of typical Vagrant commands:

-    vagrant init – creating a basic configuration file
-    vagrant up – starting a virtual machine
-    vagrant halt – stopping a virtual machine
-    vagrant destroy – delete a virtual machine
-    vagrant ssh – open a ssh session to vagrant user on virtual machine

After this short introduction let’s get started with a Vagrant on Laptop/Desktop (using Virtual Box as a provider)

Prerequisites:
-    vagrant software – https://www.vagrantup.com/downloads.html
-    Virtual Box - https://www.virtualbox.org/

In the first step a new directory will be created and used for Vagrant to initiate build of new virtual machine.

mkdir machine1
cd machine1


In the next step Vagrant machine will be initialized

vagrant init racattack/oracle65
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.


A new Vagrantfile has been created with basic configuration. By default Vagrant is trying to change a default set of public / private key with a new pair generated on user machine. But there are some problem with that on latest version of Vagrant, so as a workaround please add this line to Vagrantfile (see https://github.com/mitchellh/vagrant/issues/5186)

config.ssh.insert_key = false


This is how Vagrantfile looks like without commented lines

Vagrant.configure(2) do |config|
config.vm.box = "racattack/oracle65"
config.ssh.insert_key = false
end

Now this machine can be started. If a box selected in an init stage is not existing yet in the provider catalog, it will be automatically downloaded and cloned to a new machine.

mprzepiorowski$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'racattack/oracle65' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
==> default: Loading metadata for box 'racattack/oracle65'
default: URL: https://atlas.hashicorp.com/racattack/oracle65
==> default: Adding box 'racattack/oracle65' (v14.11.01) for provider: virtualbox
default: Downloading: https://atlas.hashicorp.com/racattack/boxes/oracle65/versions/14.11.01/p...
==> default: Successfully added box 'racattack/oracle65' (v14.11.01) for 'virtualbox'!
==> default: Importing base box 'racattack/oracle65'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'racattack/oracle65' is up to date...
==> default: Setting the name of the VM: machine1_default_1439847872931_79029
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
default: /vagrant => /Users/mprzepiorowski/Documents/machine1

Is this that simple? Yes it is – a new virtual machine with Oracle Linux is installed and ready. Next step is to ssh into a new created machine. There is no need to know neither a password nor an IP address,

mprzepiorowski$ vagrant ssh
[vagrant@oracle6-racattack ~]$


Now it is a time to customize this machine a little bit. Before that an existing machine has to be stopped using a Vagrant command

mprzepiorowski$ vagrant halt
==> default: Attempting graceful shutdown of VM...


As it was mentioned at the beginning of the post, Vagrant is using a text based configuration file. All customizations can be done by editing this file.
The configuration file structure can be divided into two sections.
First section defines a provider configuration and this part will change when a provider will be changed. Other section is provider independent and describes all other parameters.

Vagrant.configure(2) do |config|

# this part is common for all providers

config.vm.box = "racattack/oracle65"
config.ssh.insert_key = false
config.vm.hostname = "machine1"

# provider specific configuration

config.vm.provider "virtualbox" do |vb|
vb.memory = 1024
vb.cpus = 2
end

end


Starting a machine with a new configuration

mprzepiorowski$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'racattack/oracle65' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 => 2222 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Connection timeout. Retrying...
default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Mounting shared folders...
default: /vagrant => /Users/mprzepiorowski/Documents/machine1
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: flag to force provisioning. Provisioners marked to run always will still run.


Checking changes

[vagrant@machine1 ~]$ free
total used free shared buffers cached
Mem: 1020696 121356 899340 0 10980 42100
-/+ buffers/cache: 68276 952420
Swap: 8191996 0 8191996
[vagrant@machine1 ~]$ cat /proc/cpuinfo | grep processor
processor : 0
processor : 1

All looks good there. Virtual machine has 1 GB of RAM and two vCPU. Machine name has been changed to machine1 as well.

The last change tested here will be a new disk assigned to virtual machine. The box used for an example already has a “sdb” device and an “u01” file system defined inside a box. In this case device “sdc” will be added to the box and can be configured later as a “u02” file system if necessary. The file system creation and configuration will be presented in the next posts about Ansible.

disk_filename = 'disk-u02.vdi'

Vagrant.configure(2) do |config|

# this part is common for all providers

config.vm.box = "racattack/oracle65"
config.ssh.insert_key = false
config.vm.hostname = "machine1"

# provider specific configuration

config.vm.provider "virtualbox" do |vb|
vb.memory = 1024
vb.cpus = 2
unless File.exist?(disk_filename)
vb.customize ['createhd', '--filename', disk_filename, '--size', (5*1024), '--variant', 'Standard']
end
vb.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 2, '--device', 0, '--type', 'hdd', '--medium', disk_filename]
end

end

Options specified in vb.customize are options of VBoxManage command of Virtual Box installation.

mprzepiorowski$ vagrant ssh
Last login: Mon Aug 17 22:01:36 2015 from 10.0.2.2
[vagrant@machine1 ~]$ ls -l /dev/sdc*
brw-rw---- 1 root disk 8, 32 Aug 17 22:25 /dev/sdc
[vagrant@machine1 ~]$


New disk is added and ready for other activities.

This is end of this post and I will present similar steps for KVM and EC2 virtual machines in the next one.

regards,
Marcin

Automation for DBA - Vagrant part 1

Vagrant is an open source tool for building a virtual environment. It is based on text based configuration file and concept of prebuilt OS boxes.
One can find a lot of boxes on Atlas webpage (https://atlas.hashicorp.com/boxes/search), ready to download and use.  Although if there are any security concerns about using a OS from 3rd party webpage, I published a blog post about creating a new Vagrant box using Oracle Linux here and Oracle Virtual Box.

For simplicity of this series, predefined Linux box will be used in all examples.
There are two boxes that I’m using in my own work.
First one “kikitux/oracle6-racattack” created by Alvaro Miranda (https://github.com/kikitux) member of Rac Attack team. The other one is “racattack/oracle65” created by Jeremy Schneider who is also member of RacAttack team.

Vagrant itself is not a Virtualization provider. It can control different virtualization tools, including:
-    Virtual Box
-    AWS EC2 (with an additional plugin)
-    KVM (with an additional plugin)
-    VMWare Fusion / Workstation (paid version of Vagrant)

Most of the differences between providers are hidden by Vagrant workflow, and a configuration file defining a Vagrant box is similar between different providers.
Vagrant user is using same set of commands to start, stop or destroy virtual machine and does not have to know which provider is used for that.

There is a list of typical Vagrant commands:

-    vagrant init – creating a basic configuration file
-    vagrant up – starting a virtual machine
-    vagrant halt – stopping a virtual machine
-    vagrant destroy – delete a virtual machine
-    vagrant ssh – open a ssh session to vagrant user on virtual machine

After this short introduction let’s get started with a Vagrant on Laptop/Desktop (using Virtual Box as a provider)

Prerequisites:
-    vagrant software – https://www.vagrantup.com/downloads.html
-    Virtual Box - https://www.virtualbox.org/

In the first step a new directory will be created and used for Vagrant to initiate build of new virtual machine.

mkdir machine1
cd machine1


In the next step Vagrant machine will be initialized

vagrant init racattack/oracle65
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.


A new Vagrantfile has been created with basic configuration. By default Vagrant is trying to change a default set of public / private key with a new pair generated on user machine. But there are some problem with that on latest version of Vagrant, so as a workaround please add this line to Vagrantfile (see https://github.com/mitchellh/vagrant/issues/5186)

config.ssh.insert_key = false


This is how Vagrantfile looks like without commented lines

Vagrant.configure(2) do |config|
config.vm.box = "racattack/oracle65"
config.ssh.insert_key = false
end

Now this machine can be started. If a box selected in an init stage is not existing yet in the provider catalog, it will be automatically downloaded and cloned to a new machine.

mprzepiorowski$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'racattack/oracle65' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
==> default: Loading metadata for box 'racattack/oracle65'
default: URL: https://atlas.hashicorp.com/racattack/oracle65
==> default: Adding box 'racattack/oracle65' (v14.11.01) for provider: virtualbox
default: Downloading: https://atlas.hashicorp.com/racattack/boxes/oracle65/versions/14.11.01/p...
==> default: Successfully added box 'racattack/oracle65' (v14.11.01) for 'virtualbox'!
==> default: Importing base box 'racattack/oracle65'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'racattack/oracle65' is up to date...
==> default: Setting the name of the VM: machine1_default_1439847872931_79029
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
default: /vagrant => /Users/mprzepiorowski/Documents/machine1

Is this that simple? Yes it is – a new virtual machine with Oracle Linux is installed and ready. Next step is to ssh into a new created machine. There is no need to know neither a password nor an IP address,

mprzepiorowski$ vagrant ssh
[vagrant@oracle6-racattack ~]$


Now it is a time to customize this machine a little bit. Before that an existing machine has to be stopped using a Vagrant command

mprzepiorowski$ vagrant halt
==> default: Attempting graceful shutdown of VM...


As it was mentioned at the beginning of the post, Vagrant is using a text based configuration file. All customizations can be done by editing this file.
The configuration file structure can be divided into two sections.
First section defines a provider configuration and this part will change when a provider will be changed. Other section is provider independent and describes all other parameters.

Vagrant.configure(2) do |config|

# this part is common for all providers

config.vm.box = "racattack/oracle65"
config.ssh.insert_key = false
config.vm.hostname = "machine1"

# provider specific configuration

config.vm.provider "virtualbox" do |vb|
vb.memory = 1024
vb.cpus = 2
end

end


Starting a machine with a new configuration

mprzepiorowski$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'racattack/oracle65' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 => 2222 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Connection timeout. Retrying...
default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Mounting shared folders...
default: /vagrant => /Users/mprzepiorowski/Documents/machine1
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: flag to force provisioning. Provisioners marked to run always will still run.


Checking changes

[vagrant@machine1 ~]$ free
total used free shared buffers cached
Mem: 1020696 121356 899340 0 10980 42100
-/+ buffers/cache: 68276 952420
Swap: 8191996 0 8191996
[vagrant@machine1 ~]$ cat /proc/cpuinfo | grep processor
processor : 0
processor : 1

All looks good there. Virtual machine has 1 GB of RAM and two vCPU. Machine name has been changed to machine1 as well.

The last change tested here will be a new disk assigned to virtual machine. The box used for an example already has a “sdb” device and an “u01” file system defined inside a box. In this case device “sdc” will be added to the box and can be configured later as a “u02” file system if necessary. The file system creation and configuration will be presented in the next posts about Ansible.

disk_filename = 'disk-u02.vdi'

Vagrant.configure(2) do |config|

# this part is common for all providers

config.vm.box = "racattack/oracle65"
config.ssh.insert_key = false
config.vm.hostname = "machine1"

# provider specific configuration

config.vm.provider "virtualbox" do |vb|
vb.memory = 1024
vb.cpus = 2
unless File.exist?(disk_filename)
vb.customize ['createhd', '--filename', disk_filename, '--size', (5*1024), '--variant', 'Standard']
end
vb.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 2, '--device', 0, '--type', 'hdd', '--medium', disk_filename]
end

end

Options specified in vb.customize are options of VBoxManage command of Virtual Box installation.

mprzepiorowski$ vagrant ssh
Last login: Mon Aug 17 22:01:36 2015 from 10.0.2.2
[vagrant@machine1 ~]$ ls -l /dev/sdc*
brw-rw---- 1 root disk 8, 32 Aug 17 22:25 /dev/sdc
[vagrant@machine1 ~]$


New disk is added and ready for other activities.

This is end of this post and I will present similar steps for KVM and EC2 virtual machines in the next one.

regards,
Marcin

Oops

I made a mistake a few days ago following up a question on the OTN database forum. The question was about a problem creating a hash/list composite partitioned table, and one of the respondants suggested that perhaps the problem appeared because hash/list wasn’t a legal combination.

Spot on: so I confirmed that observation and supplied a link to the official Oracle white paper that listed the combinations that were legal in 11.2 for composite partitioning.  In fact, although I was fairly sure that hash/list wasn’t legal, I had even run up a quick test to check that the attempt would fail before I’d searched online for the document.

Fortunately other people had different ideas about the original failure, and one of them supplied a link to a thread on AskTom which actually included some SQL to create a hash/list composite partitioned table. Naturally I tested it (even though it was from Tom Kyte) and obviously it worked (after all it was from Tom Kyte) – and then I spotted the syntax error in the example I had created for myself.

Trust but verify … and then …

I had fallen into two traps – and one of them was documented in my own “Trust” posting from 2006.

The white paper was dated September 2009 (Tom’s example was dated June 2013) and as it says in my Trust note:

  • If its date is more than about 18 months old – don’t assume it’s (still) true
  • If it’s not your exact version number – don’t assume it’s (still) true

The second trap was an example of confirmation bias, I was fairly sure that my test was supposed to fail with Oracle error “ORA-00922: missing or invalid option”, so when it failed with exactly that error I didn’t check why it had failed and didn’t notice that I had swapped the order of a couple of clauses in the create table statement. It’s very easy to think you’ve done enough when testing – especially when your test results match your expectation.

Update – later that day

So I’ve had an email asking me how I got the ORA-00922.  Here’s the SQL as I wrote it – don’t give the answer in the comments, but how quickly can you spot what I did wrong ?

create table t1
(
        object_name,
        object_type,
        created
)
partition by hash(object_name) partitions 4
subpartition by list(object_type)
subpartition template (
        subpartition sp1 values ('TABLE'),
        subpartition sp2 values ('INDEX'),
        subpartition sp3 values (default)
)
as
select  object_name, object_type, created
from    all_objects
;

It’s a deceptive error (to me, at least) because even though I know it’s wrong it still looks right.

The Evolution of a Programmer and the Pythonic Way of Thinking

There’s an old joke about the evolution of a programmer. It starts with the programmer in their infancy and typing:

Print “Hello World” and so the output returns:

helloworld

The programmer continues to evolve. His coding knowledge increases and his code in the end of his evolution becomes a script of 5000 to 10,000 lines. What does the output return? You guessed it:

helloworld

I often joked that I’d make a terrible developer. I over think everything, but the truth is, I may have just evolved too much and need to devolve to improve. There used to be a sign up on my door of my office years ago, put there by an Operations Manager that read-

Go away before I write an efficient script to replace you.

It wasn’t far off from the truth. My shell scripts made the world go round, but they also were built with a certain mindset design. There was almost always a wrapper shell script that called subsequent scripts to perform different tasks and arguments to do what was expected. This was the design and mindset of shell scripting I’d been taught by a great scripting teacher.

Now that I’ve been working in Python for the last four months, I’ve had to admit to myself that my mindset has to change. I need to move to the Pythonic way of thinking. What is Pythonic thinking?  It is the particular style that has emerged over time trhough experience using the language by those that know it best.  This challenge is also quite normal for anyone coming to Python. Doesn’t matter if the programmer is skilled at Java, C++ or Ruby Rails, they all go through it. Python is very efficient, but below, you’ll find a perfect example of how one can really work hard instead of smart, i.e. the Pythonic way.

Coding Hard, Not Coding Smart

For my latest project, after noting the lights and built in sounds for the Pibrella board add-on for the Raspberry Pi, I decided I wanted to create a gaming script that when combined with kids imagination, could be used in a variety of ways. The game, “Red Light, Green Light” was the source of the inspiration.

The requirements were as follows:

  1. Use the lights on the board to have different variations and times lit to mark movement.
  2. Use different sounds in conjunction with the lights to signal a change or an alarm when the game play must stop, (i.e. red light.)
  3. The game play must be random so that the players wouldn’t know which light would execute, (green for go, yellow for slow motion and red for stop movement) without human intervention.

Now I created the initial script to test the process without issue. I used the Pibrella and time modules-

import pibrella
import time

#start game with success and green light. During green, (25 seconds) people will move as fast as want.
pibrella.buzzer.success()
time.sleep(3)
pibrella.buzzer.off()
pibrella.light.green.on()
time.sleep(25)
pibrella.light.green.off()
pNow lets go in slow motion. Signal the yellow alarm and then light for 15 seconds of slow motion movement.
pibrella.buzzer.buzz( frequency )
pibrella.buzzer.note( 1 ) #this is the frequency for the Note A
time.sleep(2)
pibrella.buzzer.off()
pibrella.light.yellow.on()
time.sleep(15)
pibrella.light.yellow.off()
#Now for a stop movement or red light in the game.
pibrella.light.red.pulse(2,4,2,1) #we’ll make the light pulse instead of just light up
pibrella.buzzer.fail()
time.sleep(2)
pibrella.buzzer.off()
pibrella.light.red.off()

 

Now this seems pretty straight forward, but now I wanted to add in the logic to have random runs on times and variations of colored light sequence. I started by duplicating the script and adding in different rotations and time. I planned on six different scripts with different amount of time included in it and rotations…about 150 lines of code when I finished.

Why? Because this is how I would have built in the logic to Shell scripts. I would have had a wrapper script that would call the other scripts to run different rotations to keep the players on their toes.

What’s the problem with this logic? It’s not the Pythonic way of doing things- secondary scripts called from a main script and adds to complexity that doesn’t belong in the code. It’s also the wrong way to teach python coding and would have added confusion to the class.

So how should these requirements be coded?

Pythonic Smart Instead of Coding Hard

The latest Python script looks very different from the first and it includes everything in one script, using three modules. I’ve added the Random module, which allows me to build out a random number generator that acts like a throw of a dice. Depending on the results, a different light and duration occurs. I chose six variations, three green, two yellow and one red. With the red, (throw on a six) there is a break to leave the execution of the script, but the code is built to run for 30 times as is.

import random
import pibrella
import time

for x in range(1, 31): #run for 30 iterations
   dice_1 = random.randint(1, 6) #options, just like a die.
   if dice_1 == 1:
       pibrella.buzzer.success()
       time.sleep(3)
       pibrella.buzzer.off()
       pibrella.light.green.on()
       time.sleep(25) #green for 25 seconds
       pibrella.light.green.off()
   if dice_1 == 2:
       pibrella.buzzer.success()
       time.sleep(3)
       pibrella.buzzer.off()
       pibrella.light.green.on()
       time.sleep(15) #green for 15 seconds
        pibrella.light.green.off()
   if dice_1 == 3:
       pibrella.buzzer.success()
       time.sleep(3)
       pibrella.buzzer.off()
       pibrella.light.green.on()
       time.sleep(10) #green for 10 seconds
       pibrella.light.green.off()
   if dice_1 == 4:
      pibrella.buzzer.note( 1 ) #solid note for tone
       time.sleep(2)
       pibrella.buzzer.off()
      pibrella.light.yellow.on()
       time.sleep(25) #yellow for 25 seconds
       pibrella.light.yellow.off()
   if dice_1 == 5: 
      pibrella.buzzer.note( 1 ) #solid note for tone
       time.sleep(2)
       pibrella.buzzer.off()
       pibrella.light.yellow.on()
       time.sleep(15) #yellow for 15 seconds
       pibrella.light.yellow.off()
   if dice_1 == 6:
       pibrella.light.red.pulse(2,4,2,1) #red, you’re done!
       pibrella.buzzer.fail()
       time.sleep(2)
       pibrella.buzzer.off()
       pibrella.light.red.off()
       break #escape out of the loop

What the Code Does

This code now randomly runs different variations of green and yellow with their notifying buzzer, up to 30 times or until it results in a “6”, which then will alarm, pulse the red light and exit out of the script. No other scripts or logic is required because I coded it with the Pythonic way of thinking.

To execute the code, looks like this:

sudo python .py

Playing a Game with the Code

So what does this code look like when I remove the extended times in the lights so the random generations goes at an accelerated rate of change between each?

Just like this video

Now I want you to imagine playing the game of Musical Chairs to this. Green means go fast for the time elapsed, (10, 15, 20 or 25 seconds…) Yellow requests all the players must go in slow motion, (which is also amusing for the spectators… :)) and then the red light, (and alarm) signifies everyone tries to immediately find a seat before there isn’t one left!

In a larger room, you could use it to play “Red Light, Green Light”.  You could still expect the players to go in slow motion during the yellow iterations and just as in the standard game, anyone still moving when the alarm and red light go off, must return to the starting line.

The completion of the project, after working with the kids to create the code, test and verify, is then to ask them to use their imagination on how they would use the code or enhance it to play other games.  The random libraries could easily be used for dice games, displaying the role and even incorporate more than one die for the game.

Until next time…

raspion



Tags:  ,


Del.icio.us



Facebook

TweetThis

Digg

StumbleUpon




Copyright © DBA Kevlar [The Evolution of a Programmer and the Pythonic Way of Thinking], All Right Reserved. 2015.

WordPress 4.3 “Billie”

WordPress 4.3 “Billie” has arrived.

I was on my blog admin pages doing something else and I noticed the update was available before the auto-updater kicked in and updated the site automatically, so I gave it a nudge and now I’m upgraded.

Like most of the recent WordPress updates, there is little new that interests me, but it’s always a good idea to be up to date, so whatever… :)

Cheers

Tim…


WordPress 4.3 “Billie” was first posted on August 18, 2015 at 9:02 pm.
©2012 "The ORACLE-BASE Blog". Use of this feed is for personal non-commercial use only. If you are not reading this article in your feed reader, then the site is guilty of copyright infringement.

(X)Query OPatch Information From The Database

There are cool posts out there regarding querying the OPatch info in Oracle 12 which…

A couple of up-coming user group meetings

There are a couple of user group meetings in the UK that I’ll be attending (and talking at) in September.

On the 15th September I’ll be presenting at the UKOUG Database Server SIG in the Oracle London City office, talking about PL/SQL & SQL performance. I’m not exactly sure what I’ll be covering yet, I have a few areas I’d like to talk about so I’ll have to pick one to do it justice. The meeting starts at 09:30 and is of course free to anyone with UKOUG membership (excepting the Bronze membership which only a few people have) – anyone can pay a small fee to come along. Contact the UKOUG or ask me if you want details. I’m pretty sure there will be some of us in a nearby public house after the event too.

The next meeting is the Yorkshire Database meeting on Tuesday 22nd September, from 18:30. This is the third YoDB event and I know they have been very good. I’ll be doing my talk on the fundamentals of Oracle’s architecture. I’m really quite excited about this meeting {and I know it is often a false “sell” thing to say about any IT event} because (a) it is a small, local grass-roots user group that I’ve helped promote and yet will be the first I’ll manage to get to and(b) I was at college in Leeds and so have a soft spot for the place. I still have some friends up there. This event is free to all but you DO have to register using the link above.

As ever, it’s great to meet people so please come over and say “hi” if you are at either event.

I’m hoping the postponed cluboracle meeting will happen in September too but either a new date has not been announced or it went by me.

If you want to see what events I’ll be at in the later quarter of the year, you can check out the “appearances and meetings” tab. It’s mostly smaller things like OOW and UKOUG Tech15 :-)

Oracle 12.1.0.2.x – JSON Database Patch Bundle(s)

It has been a while I patched a local development database, but nowadays stuff gets…