markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
How many total predictions of "True" ("non functional" or "functional needs repair") ? We don't have "budget" to take action on all these predictions- But we can get predicted probabilities, to rank the predictions. - Then change the threshold, to change the number of positive predictions, based on our budget. Get p...
from ipywidgets import interact, fixed y_prob = y_pred_proba[:,1] def set_threhold(y_true, y_prob, thresh): y_pred = y_prob > thresh ax = sns.distplot(y_prob, kde=False) ax.axvline(thresh, color='r') plt.show() plot_confusion_matrix(y_true, y_pred) print(classification_report(y_true, y_pred)) ...
_____no_output_____
MIT
module3-confusion-matrix/confusion_matrix.ipynb
alex000kim/DS-Unit-2-Tree-Ensembles
El módulo datetime
import datetime
_____no_output_____
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
El objeto datetime
dt = datetime.datetime.now() # Ahora dt dt.year # año dt.month # mes dt.day # día dt.hour # hora dt.minute # minutos dt.second # segundos dt.microsecond # microsegundos dt.tzinfo # zona horaria, nula por defecto print("{}:{}:{}".format(dt.hour, dt.minute, dt.second)) print("{}/{}/{}".format(dt.day, dt.month, dt.year))
18/6/2016
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
Crear un datetime manualmente (year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)*Notad que sólo son obligatorios el año, el mes y el día*
dt = datetime.datetime(2000,1,1) dt dt.year = 3000 # Error en asignación dt = dt.replace(year=3000) # Asignación correcta con .replace() dt
_____no_output_____
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
Formateos Formato automático ISO (Organización Internacional de Normalización)
dt = datetime.datetime.now() dt.isoformat()
_____no_output_____
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
Formateo munual (inglés por defecto)https://docs.python.org/3/library/datetime.htmlstrftime-and-strptime-behavior
dt.strftime("%A %d %B %Y %I:%M")
_____no_output_____
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
Códigos de idiomashttps://msdn.microsoft.com/es-es/es/library/cdax410z.aspx
import locale locale.setlocale(locale.LC_ALL, 'es-ES') # Establece idioma en "es-ES" (español de España) dt.strftime("%A %d %B %Y %I:%M") dt.strftime("%A %d de %B del %Y - %H:%M") # %I 12h - %H 24h
_____no_output_____
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
Sumando y restando tiempo con timedelta
dt = datetime.datetime.now() dt t = datetime.timedelta(days=14, hours=4, seconds=1000) dentro_de_dos_semanas = dt + t dentro_de_dos_semanas dentro_de_dos_semanas.strftime("%A %d de %B del %Y - %H:%M") hace_dos_semanas = dt - t hace_dos_semanas.strftime("%A %d de %B del %Y - %H:%M")
_____no_output_____
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
Extra: Zonas horarias con pytz*pip3 install pytz*
import pytz pytz.all_timezones dt = datetime.datetime.now(pytz.timezone('Asia/Tokyo')) dt.strftime("%A %d de %B del %Y - %H:%M") # %I 12h - %H 24h
_____no_output_____
MIT
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
Python Collections * Lists* Tuples * Dictionaries * Sets lists
x = 10 x = 20 x x = [10, 20] x x = [10, 14.3, 'abc', True] x print(dir(x)) l1 = [1, 2, 3] l2 = [4, 5, 6] l1 + l2 # concat l3 = [1, 2, 3, 4, 5, 6] l3.append(7) l3 l3.count(2) l3.count(8) len(l3) sum(l3), max(l3), min(l3) l1 l2 l_sum = [] # l_sum = list() if len(l1) == len(l2): for i in range(len(l1)): l_s...
_____no_output_____
Apache-2.0
notebooks/python_collections.ipynb
MaiMahdi1994/login-ds
tuple tupe is immutable list
point = (3, 5) print(dir(point)) l1[0] point[0]
_____no_output_____
Apache-2.0
notebooks/python_collections.ipynb
MaiMahdi1994/login-ds
comparison in tuples
(2, 3) > (1, 7) (1, 4) > (5, 9) (1, 10) > (5, 9) (5, 10) > (5, 9) (5, 7) > (5, 9)
_____no_output_____
Apache-2.0
notebooks/python_collections.ipynb
MaiMahdi1994/login-ds
dictionaries
s = [134, 'Ahmed', 'IT'] s[1] s[2] # dic = {k:v, k:v, ....} student = {'id' : 123, 'name': 'Ahmed', 'dept': 'IT'} student student['name'] print(dir(student)) student['age'] if 'age' in student: print(student['age']) student['age'] student['age'] = 22 # add item student student['age'] = 24 # update item student st...
_____no_output_____
Apache-2.0
notebooks/python_collections.ipynb
MaiMahdi1994/login-ds
set
set1 = {'a', 'b', 'c'} print(dir(set1)) set1.add('d') set1 set1.add('a') set1 'a' in set1 for e in set1: print(e)
d a b c
Apache-2.0
notebooks/python_collections.ipynb
MaiMahdi1994/login-ds
count word freq
text = ''' middletons him says Garden offended do shoud asked or ye but narrow are first knows but going taste by six zealously said weeks come partiality great simplicity mr set By sufficient an blush enquire of Then projection into mean county mile garden with up people should shameless little Started get bed agreeme...
_____no_output_____
Apache-2.0
notebooks/python_collections.ipynb
MaiMahdi1994/login-ds
Generate and Perform Tiny Performances from the MDRNN- Generates unconditioned and conditioned output from RoboJam's MDRNN- Need to open `touchscreen_performance_receiver.pd` in [Pure Data](http://msp.ucsd.edu/software.html) to hear the sound of performances.- To test generated performances, there need to be example p...
from __future__ import absolute_import from __future__ import division from __future__ import print_function # little path hack to get robojam from one directory up in the filesystem. from context import * # imports robojam # import robojam # alternatively do this. import pandas as pd import numpy as np import random ...
_____no_output_____
MIT
notebooks/generate_and_perform_with_robojam.ipynb
cpmpercussion/robojam
Plotting MethodsMainly using "plot_and_perform" method to generate 2D and 3D plots.
input_colour = 'darkblue' gen_colour = 'firebrick' plt.style.use('seaborn-talk') osc_client = robojam.TouchScreenOscClient() def plot_2D(perf_df, name="foo", saving=False): """Plot in 2D""" ## Plot the performance swipes = divide_performance_into_swipes(perf_df) plt.figure(figsize=(8, 8)) for swip...
_____no_output_____
MIT
notebooks/generate_and_perform_with_robojam.ipynb
cpmpercussion/robojam
Generate and play a performancePerformances are generated using the `generate_random_tiny_performance` method which is set to produce performances up to 5 seconds. The LSTM state and first touch can optionally be kept from the last evaluation or re-initialised.This block can be run multiple times to generate more perf...
# Generate and play one unconditioned performance # Hyperparameters: HIDDEN_UNITS = 512 LAYERS = 3 MIXES = 16 # Network net = robojam.MixtureRNN(mode=robojam.NET_MODE_RUN, n_hidden_units=HIDDEN_UNITS, n_mixtures=MIXES, batch_size=1, sequence_length=1, n_layers=LAYERS) osc_client.setSynth(instrument = "chirp") model_fil...
_____no_output_____
MIT
notebooks/generate_and_perform_with_robojam.ipynb
cpmpercussion/robojam
Condition and GenerateConditions the MDRNN on a random touchscreen performance, then generates a 5 second response.This requires example performances (`.csv` format) to be in `../performances`. See `TinyPerformanceLoader` for more details.
# Load the sample touchscreen performances: loader = robojam.TinyPerformanceLoader(verbose=False) # Fails if example performances are not in ../performance # Generate and play one conditioned performance # Hyperparameters: HIDDEN_UNITS = 512 LAYERS = 3 MIXES = 16 net = robojam.MixtureRNN(mode=robojam.NET_MODE_RUN, n_hi...
_____no_output_____
MIT
notebooks/generate_and_perform_with_robojam.ipynb
cpmpercussion/robojam
*Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICEN...
%load_ext watermark %watermark -a 'Sebastian Raschka' -v -p torch
Sebastian Raschka CPython 3.6.8 IPython 7.2.0 torch 1.0.1.post2
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
tongni1975/deep-learning-book
- Runs on CPU (not recommended here) or GPU (if available) Model Zoo -- Convolutional Neural Network (VGG19 Architecture) Implementation of the VGG-19 architecture on Cifar10. Reference for VGG-19: - Simonyan, K., & Zisserman, A. (2014). Very deep convolutional networks for large-scale image recognition. arXiv pre...
import numpy as np import time import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader
_____no_output_____
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
tongni1975/deep-learning-book
Settings and Dataset
########################## ### SETTINGS ########################## # Device DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print('Device:', DEVICE) # Hyperparameters random_seed = 1 learning_rate = 0.001 num_epochs = 20 batch_size = 128 # Architecture num_features = 784 num_classes = 10 ##...
Device: cuda:0 Files already downloaded and verified Image batch dimensions: torch.Size([128, 3, 32, 32]) Image label dimensions: torch.Size([128])
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
tongni1975/deep-learning-book
Model
########################## ### MODEL ########################## class VGG16(torch.nn.Module): def __init__(self, num_features, num_classes): super(VGG16, self).__init__() # calculate same padding: # (w - k + 2*p)/s + 1 = o # => p = (s(o-1) - w + k)/2 self...
_____no_output_____
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
tongni1975/deep-learning-book
Training
def compute_accuracy(model, data_loader): model.eval() correct_pred, num_examples = 0, 0 for i, (features, targets) in enumerate(data_loader): features = features.to(DEVICE) targets = targets.to(DEVICE) logits, probas = model(features) _, predicted_labels = torc...
Epoch: 001/020 | Batch 0000/0391 | Cost: 1061.4152 Epoch: 001/020 | Batch 0050/0391 | Cost: 2.3018 Epoch: 001/020 | Batch 0100/0391 | Cost: 2.0600 Epoch: 001/020 | Batch 0150/0391 | Cost: 1.9973 Epoch: 001/020 | Batch 0200/0391 | Cost: 1.8176 Epoch: 001/020 | Batch 0250/0391 | Cost: 1.8368 Epoch: 001/020 | Batch 0300/0...
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
tongni1975/deep-learning-book
Evaluation
with torch.set_grad_enabled(False): # save memory during inference print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader))) %watermark -iv
numpy 1.15.4 torch 1.0.1.post2
MIT
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
tongni1975/deep-learning-book
%pylab inline from flowpm import linear_field, lpt_init, nbody, cic_paint import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from scipy.interpolate import InterpolatedUnivariateSpline as iuspline klin = np.loadtxt('../flowpm/data/Planck15_a1p00.txt').T[0] plin = np.loadtxt('../flowpm/data/Planck15_a1p00.txt'...
_____no_output_____
MIT
notebooks/flowpm-MultiGrid.ipynb
Maxelee/flowpm
When To Stop FuzzingIn the past chapters, we have discussed several fuzzing techniques. Knowing _what_ to do is important, but it is also important to know when to _stop_ doing things. In this chapter, we will learn when to _stop fuzzing_ – and use a prominent example for this purpose: The *Enigma* machine that was ...
import fuzzingbook_utils import Fuzzer import Coverage
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The Enigma MachineIt is autumn in the year of 1938. Turing has just finished his PhD at Princeton University demonstrating the limits of computation and laying the foundation for the theory of computer science. Nazi Germany is rearming. It has reoccupied the Rhineland and annexed Austria against the treaty of Versaill...
import string import numpy from numpy.random import choice from numpy.random import shuffle from numpy import log
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We start with creating the set of trigrams:
letters = list(string.ascii_letters[26:]) # upper-case characters trigrams = [str(a + b + c) for a in letters for b in letters for c in letters] shuffle(trigrams) trigrams[:10]
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
These now go into the Kenngruppenbuch. However, it was observed that some trigrams were more likely chosen than others. For instance, trigrams at the top-left corner of any page, or trigrams on the first or last few pages were more likely than one somewhere in the middle of the book or page. We reflect this differenc...
k_book = {} # Kenngruppenbuch for i in range(1, len(trigrams) + 1): trigram = trigrams[i - 1] # choose weights according to Benford's law k_book[trigram] = log(1 + 1 / i) / log(26**3 + 1)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Here's a random trigram from the Kenngruppenbuch:
random_trigram = choice(list(k_book.keys()), p=list(k_book.values())) random_trigram
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
And this is its probability:
k_book[random_trigram]
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Fuzzing the EnigmaIn the following, we introduce an extremely simplified implementation of the Naval Enigma based on the trigrams from the K-book. Of course, the encryption mechanism of the actual Enigma machine is much more sophisticated and worthy of a much more detailed investigation. We encourage the interested re...
from Fuzzer import RandomFuzzer from Fuzzer import Runner class EnigmaMachine(Runner): def __init__(self, k_book): self.k_book = k_book self.reset() def reset(self): """Resets the key register""" self.msg2key = {} def internal_msg2key(self, message): """Inte...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
To "fuzz" the `naval_enigma()`, our job will be to come up with a key that matches a given (encrypted) message. Since the keys only have three characters, we have a good chance to achieve this in much less than a seconds. (Of course, longer keys will be much harder to find via random fuzzing.)
class EnigmaMachine(EnigmaMachine): def run(self, tri): """PASS if cur_msg is encoded with trigram tri""" if self.naval_enigma(self.cur_msg, tri): outcome = self.PASS else: outcome = self.FAIL return (tri, outcome)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Now we can use the `EnigmaMachine` to check whether a certain message is encoded with a certain trigram.
enigma = EnigmaMachine(k_book) enigma.cur_msg = "BrEaK mE. L0Lzz" enigma.run("AAA")
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The simplest way to crack an encoded message is by brute forcing. Suppose, at Bletchley park they would try random trigrams until a message is broken.
class BletchleyPark(object): def __init__(self, enigma): self.enigma = enigma self.enigma.reset() self.enigma_fuzzer = RandomFuzzer( min_length=3, max_length=3, char_start=65, char_range=26) def break_message(self, message): ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
How long does it take Bletchley park to find the key using this brute forcing approach?
from Timer import Timer enigma = EnigmaMachine(k_book) bletchley = BletchleyPark(enigma) with Timer() as t: trigram = bletchley.break_message("BrEaK mE. L0Lzz")
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Here's the key for the current message:
trigram
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
And no, this did not take long:
'%f seconds' % t.elapsed_time() 'Bletchley cracks about %d messages per second' % (1/t.elapsed_time())
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Turing's ObservationsOkay, lets crack a few messages and count the number of times each trigram is observed.
from collections import defaultdict n = 100 # messages to crack observed = defaultdict(int) for msg in range(0, n): trigram = bletchley.break_message(msg) observed[trigram] += 1 # list of trigrams that have been observed counts = [k for k, v in observed.items() if int(v) > 0] t_trigrams = len(k_book) o_trigr...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Given a sample of previously used entries, Turing wanted to _estimate the likelihood_ that the current unknown entry was one that had been previously used, and further, to estimate the probability distribution over the previously used entries. This lead to the development of the estimators of the missing mass and estim...
class BletchleyPark(BletchleyPark): def break_message(self, message): """Returning the trigram for an encoded message""" # For the following experiment, we want to make it practical # to break a large number of messages. So, we remove the # loop and just return the trig...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Let's crack 2000 messages and compute the GT-estimate.
n = 2000 # messages to crack bletchley = BletchleyPark(enigma) (observed, timeseries) = bletchley.break_n_messages(n)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Let us determine the Good-Turing estimate of the probability that the next trigram has not been observed before:
singletons = len([k for k, v in observed.items() if int(v) == 1]) gt = singletons / n gt
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We can verify the Good-Turing estimate empirically and compute the empirically determined probability that the next trigram has not been observed before. To do this, we repeat the following experiment repeats=1000 times, reporting the average: If the next message is a new trigram, return 1, otherwise return 0. Note tha...
repeats = 1000 # experiment repetitions newly_discovered = 0 for cur_msg in range(n, n + repeats): trigram = bletchley.break_message(cur_msg) if(observed[trigram] == 0): newly_discovered += 1 newly_discovered / repeats
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Looks pretty accurate, huh? The difference between estimates is reasonably small, probably below 0.03. However, the Good-Turing estimate did not nearly require as much computational resources as the empirical estimate. Unlike the empirical estimate, the Good-Turing estimate can be computed during the campaign. Unlike t...
1 - gt
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The *inverse* of the GT-estimate (1/GT) is a _maximum likelihood estimate_ of the expected number of messages that we can decrypt with previously observed trigrams before having to find a new trigram to decrypt the message. In our setting, the number of messages for which we can expect to reuse previous trigrams befor...
1 / gt
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
But why is GT so accurate? Intuitively, despite a large sampling effort (i.e., cracking $n$ messages), there are still $f_1$ trigrams that have been observed only once. We could say that such "singletons" are very rare trigrams. Hence, the probability that the next messages is encoded with such a rare but observed trig...
%matplotlib inline import matplotlib.pyplot as plt frequencies = [v for k, v in observed.items() if int(v) > 0] frequencies.sort(reverse=True) # Uncomment to see how often each discovered trigram has been observed # print(frequencies) # frequency of rare trigrams plt.figure(num=None, figsize=(12, 4), dpi=80, facecolor...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The *majority of trigrams* have been observed only once, as we can see in Figure 1 (left). In other words, a the majority of observed trigrams are "rare" singletons. In Figure 2 (right), we can see that discovery is in full swing. The trajectory seems almost linear. However, since there is a finite number of trigrams (...
print("Trigram : Frequency") for trigram in sorted(observed, key=observed.get, reverse=True): if observed[trigram] > 10: print(" %s : %d" % (trigram, observed[trigram]))
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We'll speed up the code breaking by _trying the abundant trigrams first_. First, we'll find out how many messages can be cracked by the existing brute forcing strategy at Bledgley park, given a maximum number of attempts. We'll also track the number of messages cracked over time (`timeseries`).
class BletchleyPark(BletchleyPark): def __init__(self, enigma): super().__init__(enigma) self.cur_attempts = 0 self.cur_observed = 0 self.observed = defaultdict(int) self.timeseries = [None] * max_attempts * 2 def break_message(self, message): """Returns...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
`original` is the number of messages cracked by the bruteforcing strategy, given 100k attempts. Can we beat this?
max_attempts = 100000 bletchley = BletchleyPark(enigma) original = bletchley.break_max_attempts(max_attempts) original
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Now, we'll create a boosting strategy by trying trigrams first that we have previously observed most often.
class BoostedBletchleyPark(BletchleyPark): def break_message(self, message): """Returns the trigram for an encoded message, and track #trigrams observed as #attempts increases.""" self.enigma.cur_msg = message # boost cracking by trying observed trigrams first ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
`boosted` is the number of messages cracked by the boosted strategy.
boostedBletchley = BoostedBletchleyPark(enigma) boostedBletchley.prior = observed boosted = boostedBletchley.break_max_attempts(max_attempts) boosted
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We see that the boosted technique cracks substantially more messages. It is worthwhile to record how often each trigram is being used as key and try them in the order of their occurence.***Try it***. *For practical reasons, we use a large number of previous observations as prior (`boostedBletchley.prior = observed`). Y...
# print plots line_old, = plt.plot(bletchley.timeseries, label="Bruteforce Strategy") line_new, = plt.plot(boostedBletchley.timeseries, label="Boosted Strategy") plt.legend(handles=[line_old, line_new]) plt.xlabel('# of cracking attempts') plt.ylabel('# of trigrams discovered') plt.title('Trigram Discovery Over Time');
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We see that the boosted fuzzer is constantly superior over the random fuzzer. Estimating the Probability of Path DiscoverySo, what does Turing's observation for the Naval Enigma have to do with fuzzing _arbitrary_ programs? Turing's assistant I.J. Good extended and published Turing's work on the estimation procedures ...
from Coverage import Coverage, cgi_decode encoded = "Hello%2c+world%21" with Coverage() as cov: decoded = cgi_decode(encoded) decoded print(cov.coverage());
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Trace CoverageFirst, we will introduce the concept of execution traces, which are a coarse abstraction of the execution path taken by an input. Compared to the definition of path, a trace ignores the sequence in which statements are exercised or how often each statement is exercised.* `pickle.dumps()` - serializes an ...
import pickle import hashlib def getTraceHash(cov): pickledCov = pickle.dumps(cov.coverage()) hashedCov = hashlib.md5(pickledCov).hexdigest() return hashedCov
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Remember our model for the Naval Enigma machine? Each message must be decrypted using exactly one trigram while multiple messages may be decrypted by the same trigram. Similarly, we need each input to yield exactly one trace hash while multiple inputs can yield the same trace hash. Let's see whether this is true for ou...
inp1 = "a+b" inp2 = "a+b+c" inp3 = "abc" with Coverage() as cov1: cgi_decode(inp1) with Coverage() as cov2: cgi_decode(inp2) with Coverage() as cov3: cgi_decode(inp3)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The inputs `inp1` and `inp2` execute the same statements:
inp1, inp2 cov1.coverage() - cov2.coverage()
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The difference between both coverage sets is empty. Hence, the trace hashes should be the same:
getTraceHash(cov1) getTraceHash(cov2) assert getTraceHash(cov1) == getTraceHash(cov2)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
In contrast, the inputs `inp1` and `inp3` execute _different_ statements:
inp1, inp3 cov1.coverage() - cov3.coverage()
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Hence, the trace hashes should be different, too:
getTraceHash(cov1) getTraceHash(cov3) assert getTraceHash(cov1) != getTraceHash(cov3)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Measuring Trace Coverage over TimeIn order to measure trace coverage for a `function` executing a `population` of fuzz inputs, we slightly adapt the `population_coverage()` function from the [Chapter on Coverage](Coverage.ipynbCoverage-of-Basic-Fuzzing).
def population_trace_coverage(population, function): cumulative_coverage = [] all_coverage = set() cumulative_singletons = [] cumulative_doubletons = [] singletons = set() doubletons = set() for s in population: with Coverage() as cov: try: function(s) ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Let's see whether our new function really contains coverage information only for *two* traces given our three inputs for `cgi_decode`.
all_coverage = population_trace_coverage([inp1, inp2, inp3], cgi_decode)[0] assert len(all_coverage) == 2
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Unfortunately, the `cgi_decode()` function is too simple. Instead, we will use the original Python [HTMLParser](https://docs.python.org/3/library/html.parser.html) as our test subject.
from Fuzzer import RandomFuzzer from Coverage import population_coverage from html.parser import HTMLParser trials = 50000 # number of random inputs generated
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Let's run a random fuzzer for $n=50000$ times and plot trace coverage over time.
# create wrapper function def my_parser(inp): parser = HTMLParser() # resets the HTMLParser object for every fuzz input parser.feed(inp) # create random fuzzer fuzzer = RandomFuzzer(min_length=1, max_length=100, char_start=32, char_range=94) # create population of fuzz inputs population ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Above, we can see trace coverage (left) and code coverage (right) over time. Here are our observations.1. **Trace coverage is more robust**. There are less sudden jumps in the graph compared to code coverage.2. **Trace coverage is more fine grained.** There more traces than statements covered at the end (y-axis)3. **Tr...
repeats = 500 # experiment repetitions measurements = 100 # experiment measurements emp_timeseries = [] all_coverage = set() step = int(trials / measurements) for i in range(0, trials, step): if i - step >= 0: for j in range(step): inp = population[i - j] with Coverage() as co...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Now, we compute the Good-Turing estimate over time.
gt_timeseries = [] singleton_timeseries = population_trace_coverage(population, my_parser)[2] for i in range(1, trials + 1, step): gt_timeseries.append(singleton_timeseries[i - 1] / i)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Let's go ahead and plot both time series.
line_emp, = plt.semilogy(emp_timeseries, label="Empirical") line_gt, = plt.semilogy(gt_timeseries, label="Good-Turing") plt.legend(handles=[line_emp, line_gt]) plt.xticks(range(0, measurements + 1, int(measurements / 5)), range(0, trials + 1, int(trials / 5))) plt.xlabel('# of fuzz inputs') plt.ylabel('disco...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Again, the Good-Turing estimate appears to be *highly accurate*. In fact, the empirical estimator has a much lower precision as indicated by the large swings. You can try and increase the number of repetitions (repeats) to get more precision for the empirical estimates, however, at the cost of waiting much longer. Dis...
trials = 400000 fuzzer = RandomFuzzer(min_length=2, max_length=4, char_start=32, char_range=32) population = [] for i in range(trials): population.append(fuzzer.fuzz()) _, trace_ts, f1_ts, f2_ts = population_trace_coverage(population, my_parser) time = int(trials / 2) time f1 = f1_ts[time] f2...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
After executing `time` fuzz inputs (half of all), we have covered these many traces:
time Sn
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We can estimate there are this many traces in total:
hat_S
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Hence, we have achieved this percentage of the estimate:
100 * Sn / hat_S
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
After executing `trials` fuzz inputs, we have covered these many traces:
trials trace_ts[trials - 1]
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The accuracy of Chao's estimator is quite reasonable. It isn't always accurate -- particularly at the beginning of a fuzzing campaign when the [discovery probability](WhenIsEnough.ipynbMeasuring-Trace-Coverage-over-Time) is still very high. Nevertheless, it demonstrates the main benefit of reporting a percentage to ass...
prediction_ts = [None] * time f0 = hat_S - Sn for m in range(trials - time): assert (time * f0 + f1) != 0 , 'time:%s f0:%s f1:%s' % (time, f0,f1) prediction_ts.append(Sn + f0 * (1 - (1 - f1 / (time * f0 + f1)) ** m)) plt.figure(num=None, figsize=(12, 3), dpi=80, facecolor='w', edgecolor='k') plt.subplot(1, 3, ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
The prediction from Chao's extrapolator looks quite accurate. We make a prediction at $time=trials/4$. Despite an extrapolation by 3 times (i.e., at trials), we can see that the predicted value (black, dashed line) closely matches the empirical value (grey, solid line).***Try it***. Again, try setting and `trials` to 1...
from Coverage import population_coverage, Coverage ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
**Solution.** Here we go:
def population_stmt_coverage(population, function): cumulative_coverage = [] all_coverage = set() cumulative_singletons = [] cumulative_doubletons = [] singletons = set() doubletons = set() for s in population: with Coverage() as cov: try: function(s) ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Part 2: PopulationUse the random `fuzzer(min_length=1, max_length=1000, char_start=0, char_range=255)` from [the chapter on Fuzzers](Fuzzer.ipynb) to generate a population of $n=10000$ fuzz inputs.
from Fuzzer import RandomFuzzer from html.parser import HTMLParser ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
**Solution.** This is fairly straightforward:
trials = 2000 # increase to 10000 for better convergences. Will take a while..
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We create a wrapper function...
def my_parser(inp): parser = HTMLParser() # resets the HTMLParser object for every fuzz input parser.feed(inp)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
... and a random fuzzer:
fuzzer = RandomFuzzer(min_length=1, max_length=1000, char_start=0, char_range=255)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
We fill the population:
population = [] for i in range(trials): population.append(fuzzer.fuzz())
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Part 3: Estimating ProbabilitiesExecute the generated inputs on the Python HTML parser (`from html.parser import HTMLParser`) and estimate the probability that the next input covers a previously uncovered statement (i.e., the discovery probability) using the Good-Turing estimator. **Solution.** Here we go:
measurements = 100 # experiment measurements step = int(trials / measurements) gt_timeseries = [] singleton_timeseries = population_stmt_coverage(population, my_parser)[2] for i in range(1, trials + 1, step): gt_timeseries.append(singleton_timeseries[i - 1] / i)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Part 4: Empirical EvaluationEmpirically evaluate the accuracy of the Good-Turing estimator (using $10000$ repetitions) of the probability to cover new statements using the experimental procedure at the end of [the section on estimating discovery probability](Estimating-the-Discovery-Probability). **Solution.** This is...
# increase to 10000 for better precision (less variance). Will take a while.. repeats = 100 emp_timeseries = [] all_coverage = set() for i in range(0, trials, step): if i - step >= 0: for j in range(step): inp = population[i - j] with Coverage() as cov: try: ...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Exercise 2: Extrapolate and Evaluate Statement CoverageIn this exercise, we use Chao's extrapolation method to estimate the success of fuzzing. Part 1: Create PopulationUse the random `fuzzer(min_length=1, max_length=1000, char_start=0, char_range=255)` to generate a population of $n=400000$ fuzz inputs. **Solution.*...
trials = 400 # Use 400000 for actual solution. This takes a while! population = [] for i in range(trials): population.append(fuzzer.fuzz()) _, stmt_ts, Q1_ts, Q2_ts = population_stmt_coverage(population, my_parser)
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Part 2: Compute EstimateCompute an estimate of the total number of statements $\hat S$ after $n/4=100000$ fuzz inputs were generated. In the extended model, $\hat S$ is computed as\begin{align}\hat S_\text{Chao1} = \begin{cases}S(n) + \frac{Q_1^2}{2Q_2} & \text{if $Q_2>0$}\\S(n) + \frac{Q_1(Q_1-1)}{2} & \text{otherwis...
time = int(trials / 4) Q1 = Q1_ts[time] Q2 = Q2_ts[time] Sn = stmt_ts[time] if Q2 > 0: hat_S = Sn + Q1 * Q1 / (2 * Q2) else: hat_S = Sn + Q1 * (Q1 - 1) / 2 print("After executing %d fuzz inputs, we have covered %d **(%.1f %%)** statements.\n" % (time, Sn, 100 * Sn / hat_S) + "After executing %d fuzz inp...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Part 3: Compute and Evaluate ExtrapolatorCompute and evaluate Chao's extrapolator by comparing the predicted number of statements to the empirical number of statements. **Solution.** Here's our solution:
prediction_ts = [None] * time Q0 = hat_S - Sn for m in range(trials - time): prediction_ts.append(Sn + Q0 * (1 - (1 - Q1 / (time * Q0 + Q1)) ** m)) plt.figure(num=None, figsize=(12, 3), dpi=80, facecolor='w', edgecolor='k') plt.subplot(1, 3, 1) plt.plot(stmt_ts, color='white') plt.plot(stmt_ts[:time]) plt.xticks(r...
_____no_output_____
MIT
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
Introduction to 2D plotsThis notebook demonstrates how plot some latitude by longitude maps of some key surface variables. Most features are available in the preinstalled `geog0111` environment. But updated plotting that removes white meridional lines around the Greenwich Meridian, requires the `geog0121` virtual envi...
'''Import packages for loading data, analysing, and plotting''' import xarray as xr import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline import cartopy import cartopy.crs as ccrs import matplotlib from netCDF4 import Dataset from mpl_toolkits.axes_grid1 import make_axes_locatable ...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Change in annual temperature under the SSP585 scenarioHere we use the CVDP output files to look at the change in annual mean surface temperature
#define filenames and their directories end_period='2071-2100' start_period='1851-1900' ssp='ssp585' directory_a='/data/aod/cvdp_cmip6/geog0121/UKESM1-0-LL_ssps.wrt_%s' %end_period filename_a='%s/UKESM1_%s_%s.cvdp_data.1850-2100.nc'%(directory_a,ssp,end_period) directory_b='/data/aod/cvdp_cmip6/geog0121/UKESM1-0-LL_ss...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Using xarray's simplest plotting routine
diff.plot()
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Whilst this plot clearly show what is going on. It is missing several useful features:* A sensible colormap* The coastline (or country borders) to help orientate you* A logical scale for the colors to useWhatever you decide to plot, it is always worth selecting a relevant colormap. All of the easily available colormaps...
# Define the map projection through an "axes" call plt.figure(figsize=(10,7)) #make the map itself nice and big projection = ccrs.Robinson() #specify the Robinson projection ax = plt.axes(projection=projection) #create the axes ax.coastlines() # add the coastlines ax.gridlines() # add some gray gridlines ax.add_featur...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
UKESM's El Nino temperature patternHere we use the CVDP output files to plot the temperature response to an El Nino. First we will load in the data
#generate filename directory='/data/aod/cvdp_cmip6/geog0121/UKESM1-0-LL_historical.vsObs' filename='%s/UKESM1-0-LL_PresentDay.cvdp_data.1850-2014.nc'%(directory) # load files expt_file=xr.open_dataset(filename,decode_times=False) # load the coordinates lat=expt_file['lat'] lon=expt_file['lon'] # load the variables the...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Then we will specify the colorscale and map
#temperatures cmap=plt.get_cmap('bwr') #define colormap #define colormap's range and scale cmap_limits=[-5,5] bounds = np.linspace(cmap_limits[0], cmap_limits[1], 21) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Now we will make a global plot of the El Nino pattern
# Choose the map and projection projection = ccrs.Robinson() transform=ccrs.PlateCarree() # Plot the axes plt.figure(figsize=(10,7)) ax = plt.axes(projection=projection) ax.coastlines() ax.gridlines() # Make the actual figure fig=ax.contourf(lon,lat,enso_pattern,levels=bounds, transform=transform,cmap=cmap,norm=norm)...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
And then lets zoom into a smaller region of it
#Regional map region=[100,280,-30,30] #[lon_min,lon_max,lat_min,lat_max] # note the specification of the central longitude, so that is spans the dateline projection = ccrs.PlateCarree(central_longitude=180., globe=None) transform=ccrs.PlateCarree() plt.figure(figsize=(10,7)) ax = plt.axes(projection=projection) ax.c...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Seasonal precipitation anomaliesThe CVDP files can be used to create maps of the changes in seasonal precipitation. First we select the variable
#seasonal precipitation anomalies variable_name='pr_spatialmean_djf' expt_a=expt_a_file[variable_name] expt_b=expt_b_file[variable_name] diff=expt_a-expt_b
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Then we define the colormap, and give it a non-linear interval
#precipitations cmap=plt.get_cmap('BrBG') #define colormap #define colormap's range and scale bounds = [-5,-2,-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1,2,5] norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Then we can create a global map with...
#Global map projection = ccrs.Robinson() transform=ccrs.PlateCarree() plt.figure(figsize=(10,7)) ax = plt.axes(projection=projection) ax.coastlines() ax.gridlines() fig=ax.contourf(lon,lat,diff,levels=bounds, transform=transform,cmap=cmap,norm=norm) cax,kw = matplotlib.colorbar.make_axes(ax,location='bottom',pad=0.0...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
Or a regional map with...
#Regional map region=[-20,70,20,90] #[lon_min,lon_max,lat_min,lat_max] projection = ccrs.PlateCarree(central_longitude=0.0, globe=None) transform=ccrs.PlateCarree() plt.figure(figsize=(10,7)) ax = plt.axes(projection=projection) ax.coastlines() gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,alpha=0.5, li...
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
If your regional plot (like this one) happens to cross the Greenwich meridian, then you will end up with a white line going straight up the middle of your regional plot. This can be fixed by adding a "cyclic point" to loop the data around the globe. To understand this, think about how you need to overlap the wrapping p...
diff, lon = add_cyclic_point(diff, coord=lon)
_____no_output_____
MIT
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
**Deel 1**
# def checkstoelen(wr, count): # count += 1 # nwr = [] # o = 0 # for i,v in enumerate(wr): # nrij = '' # if (i < 5) | (i > (len(wr)-5)): # nrij = v # else: # for j,s in enumerate(v): # if (j < 5) | (j > (len(v)-5)): # nr...
_____no_output_____
Apache-2.0
Dag11.ipynb
isepri/Adventofcode2020
**Deel 2**
def checkaangrenzend(d, m, n, l): ll =[] r = list(range(1,l)) for x in r: cellen = [d[m-x][n-x], d[m-x][n], d[m-x][n+x], d[m][n-x], d[m][n+x], d[m+x][n-x], d[m+x][n], d[m+x][n+x]] ll += [cellen] ll_list = [[row[z] for row in ll] for z in range(len(cellen))] ad = [] for richtin...
2121
Apache-2.0
Dag11.ipynb
isepri/Adventofcode2020