39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
39 changes: 39 additions & 0 deletions FaceRecognition.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
##Face Recognition With Python

#Install openCV with "import cv2" inb python command line


# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)


# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)


print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)


cv2.imshow("Faces found" ,image)
cv2.waitKey(0)

python face_detect.py abba.png haarcascade_frontalface_default.xml
82 changes: 82 additions & 0 deletions dice-roller/dice.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
"""Dice roller for any number of dice and sides"""
# random int generator
from random import randint

def main():
"""main function"""
pass

if __name__ == "__main__":
main()

def dice_input():
"""Get the number of dice."""
global dice
# input for dice number variable
dice = int(raw_input('How many dice would you like to roll? '))
# Validate for positive integers
dice_int = False
while not dice_int:
if dice <= 0:
print "Error! Please enter a positive number of dice."
dice_input()
else:
dice_int = True
print "Ok, I will roll %s dice." % (dice)
return


def sides_input():
"""Get the number of sides"""
global sides
sides = int(raw_input('How many sides does each dice have? '))
# Validate for positive integers
sides_int = False
while not sides_int:
if sides <= 0:
print "Error! Please enter a positive number of sides."
sides_input()
else:
sides_int = True
return


def roll_dice():
"""Loop through number of dice, randomly generate numbers"""
print "Ok, rolling %s dice with %s sides." % (dice, sides)
roll = 0
for roll in range(0, dice):
print "[%s]" % (randint(1, sides))

again = raw_input('Would you like to roll, make a change, or end r/c/e? ')

if again == 'r':
roll_dice()
elif again == 'e':
print "Ok, thanks!"
return
elif again == 'c':
change()
else:
print "Please respond with r, c, or e"
roll_dice()


def change():
"""Change number of dice or sides"""
which = raw_input('Change dice or sides d/s? ')
if which == 'd':
dice_input()
roll_dice()
else:
if which == 's':
sides_input()
roll_dice()
else:
print 'Please input only d or s'
change()


dice_input()
sides_input()
roll_dice()
32 changes: 32 additions & 0 deletions random_password.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
'''
The password generator will take the length of password (always greater than 3) and output a random password containing at least:
1. An Aphabet( either lowercase or uppercase)
2. A number.

3. A special character.

The postion of all these characters will also be random i.e. the number might be the first to come.
Constraints:
The length of password is at least 3 and maximum will be 100.

'''
from random import choice,sample

l=0
while l<3 or l>100 or int(l)!=l:
l=int(input('Enter password length (an integer between 3 and 100)\n'))

num=list(range(48,58))
char=list(range(65,91))+list(range(97,123))
spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126))
all=num+char+spec

passw=[choice(num),choice(char),choice(spec)]

while len(passw)<l:
passw.append(choice(all))
passw=sample(passw,l)
password=''
for i in range(l):
password+=chr(passw[i])
print('This is your password: ',password)
121 changes: 121 additions & 0 deletions spam_classifier.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
import re
import math

def getwords(doc):
splitter = re.compile("\\W*")
#Split the words by non-alpha characters
words = [s.lower() for s in splitter.split(doc)
if len(s)>2 and len(s)<20]
return dict((w,1) for w in words)


def sampletrain(cl):
cl.train('Nobody owns the water.', 'good')
cl.train('the quick rabbit jumps fences','good')
cl.train('buy pharmaceuticals now', 'bad')
cl.train('make quick money at online casino', 'bad')
cl.train('the quick brown fox jumps.', 'good')


class classifier:
def __init__(self, getfeatures, filename=None):
#Counts of feature/category combinations
self.fc = {}
#Counts of docs in each category
self.cc={}
self.getfeatures = getfeatures

#Increase the count of a feature-category pair
def incf(self, f, cat):
self.fc.setdefault(f, {})
self.fc[f].setdefault(cat, 0)
self.fc[f][cat]+=1

#Increase the count of a category
def incc(self, cat):
self.cc.setdefault(cat, 0)
self.cc[cat]+=1

#The number of times a feature has appeared in a category
def fcount(self, f, cat):
if f in self.fc and cat in self.fc[f]:
return float(self.fc[f][cat])
return 0.0

#The number of items in a category
def catcount(self, cat):
if cat in self.cc:
return float(self.cc[cat])
return 0

#The total number of items
def totalcount(self):
return sum(self.cc.values())

#List of all categories
def categories(self):
return self.cc.keys()

def train(self, item, cat):
features= self.getfeatures(item)
#Increment the count for every feature with this category
for f in features:
self.incf(f, cat)

#Increment the count for this category
self.incc(cat)

def fprob(self, f, cat):
if self.catcount(cat)==0: return 0
return self.fcount(f, cat)/self.catcount(cat)

def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
# Calculate current probability
basicprob = prf(f,cat)
# Count the number of times this feature has appeared in
# all categories
totals=sum([self.fcount(f,c) for c in self.categories()])
# Calculate the weighted average
bp=((weight*ap)+(totals*basicprob))/(weight+totals)
return bp

class naivebayes(classifier):
def __init__(self, getfeatures):
classifier.__init__(self, getfeatures)
self.thresholds={}

def docprob(self, item, cat):
features = self.getfeatures(item)
#Multiply the probabilities of all features together
p = 1
for f in features : p *= self.weightedprob(f, cat, self.fprob)
return p

def prob(self, item, cat):
catprob = self.catcount(cat)/self.totalcount()
docprob = self.docprob(item, cat)
return docprob*catprob

def setthreshold(self, cat, t):
self.thresholds[cat]=t

def getthreshold(self, cat):
if not cat in self.thresholds: return 1.0
return self.thresholds[cat]

def classify(self, item, default=None):
probs = {}
#Find the category with the highest probability
max = 0.0
for cat in self.categories():
probs[cat] = self.prob(item, cat)
if probs[cat]>max:
max=probs[cat]
best=cat

#Make sure the probability exceeds threshold* next best
for cat in probs:
if cat == best: continue
if probs[cat] * self.getthreshold(best)>probs[best]:
return default
return best
40 changes: 40 additions & 0 deletions spellCheck.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('words.txt').read()))

def P(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
return WORDS[word] / N

def correction(word):
"Most probable spelling correction for word."
#print(candidates(word))
return max(candidates(word), key=P)

def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)

def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)

def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))

print("correction for 'pythob' = ", correction("pythob")) #prints 'python'