## Calculate Square Root

0 likes • Nov 18, 2022 • 0 views
Python

## More Python Posts

#### Factorial of N

0 likes • Nov 19, 2022 • 0 views
Python
import math
def factorial(n):
print(math.factorial(n))
return (math.factorial(n))
factorial(5)
factorial(10)
factorial(15)

#### Bubble sort

0 likes • Nov 19, 2022 • 0 views
Python
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),

#### Query UNT ActiveStudents

0 likes • Nov 18, 2022 • 1 view
Python
import os
import sys
import argparse
import json
import csv
import getpass
import string
import random
import re
from datetime import datetime
import ldap
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from requests.auth import HTTPBasicAuth
import validators
import ipdb
# ldap functions
def get_ldap_group_members(ldap_group, user, passwrd, DOMAIN, DOMAIN_SEARCH_BASE):
#DOMAIN_GROUP, DOMAIN_USER, DOMAIN_PASS, DOMAIN, DOMAIN_SEARCH_BASE
'''
Input a user name and search the directory
'''
#---- Setting up the Connection
#account used for binding - Avoid putting these in version control
bindDN = str(user)
bindPass = passwrd
#set some tuneables for the LDAP library.
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
#ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, CACERTFILE)
conn = ldap.initialize('ldaps://'+str(DOMAIN))
conn.protocol_version = 3
conn.set_option(ldap.OPT_REFERRALS, 0)
#authenticate the connection so that you can make additional queries
try:
result = conn.simple_bind_s(bindDN, bindPass)
except ldap.INVALID_CREDENTIALS:
result = "Invalid credentials for %s" % user
sys.exit()
#build query in the form of (uid=user)
ldap_query = '(cn=' + ldap_group + ')'
query_result = []
lencount = True
range_start = 0
total_active_students_count = 0
while lencount:
#print(len(query_result))
range_end = range_start + 1499
member_range = ['member;range=' + str(range_start) + '-' + str(range_end)]
#print(member_range)
ldap_info = conn.search_s(str(DOMAIN_SEARCH_BASE), ldap.SCOPE_SUBTREE, filterstr=ldap_query, attrlist=member_range)
member_range = next(iter(ldap_info[0][1].keys()))
ldap_objects = ldap_info[0][1][member_range]
print("\n")
for ldap_object in ldap_objects:
decoded_member_string = ldap_object.decode("utf-8")
member_cn = re.split('=|,', decoded_member_string)[1]
print(f"User number: {total_active_students_count} in {ldap_group}: {member_cn}")
query_result.append(member_cn)
total_active_students_count = total_active_students_count + 1
if len(ldap_objects) == 1500:
lencount = True
range_start += 1500
range_end += 1500
else:
lencount = False
print(f"TOTAL USERS IN ActiveStudents: {total_active_students_count}")
return query_result
def main():
passwrd = getpass.getpass(prompt='Enter UNT bind password: ', stream=None)
if __name__ == "__main__":
main()

#### Distinct Primes Finder > 1000

0 likes • Nov 18, 2022 • 2 views
Python
primes=[]
products=[]
def prime(num):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
return False
else:
primes.append(num)
return True
for n in range(30,1000):
if len(primes) >= 20:
break;
else:
prime(n)
for previous, current in zip(primes[::2], primes[1::2]):
products.append(previous * current)
print (products)

#### ZapFinder

0 likes • Jan 23, 2021 • 0 views
Python
import subprocess #for the praat calls
import os #for ffmpeg and the pause call at the end
#Even if we wanted all videos being rendered asynchronously, we couldn't see progress or errors
import glob #for the ambiguous files
import tempfile
audioFileDirectory = 'Audio Files'
timeList = {}
fileList = glob.glob(audioFileDirectory + '\\*.wav')
pipeList = {}
for fileName in fileList:
arglist = ['Praat.exe', '--run', 'crosscorrelateMatch.praat', 'zeussound.wav', fileName, "0" , "300"]
print(' '.join(arglist))
pipe = subprocess.Popen(arglist, stdout=subprocess.PIPE)
pipeList[fileName[len(audioFileDirectory)+1:-4]] = pipe #+1 because of back slash, -4 because .wav
#for fileName, pipe in pipeList.items():
# text = pipe.communicate()[0].decode('utf-8')
# timeList[fileName] = float(text[::2])
for fileName, pipe in pipeList.items():
if float(pipe.communicate()[0].decode('utf-8')[::2]) > .0003: #.000166 is not a match, and .00073 is a perfect match. .00053 is a tested match
arglist = ['Praat.exe', '--run', 'crosscorrelate.praat', 'zeussound.wav', audioFileDirectory + '\\' + fileName + '.wav', "0" , "300"]
print(' '.join(arglist))
text = subprocess.Popen(arglist, stdout=subprocess.PIPE).communicate()[0].decode('utf-8')
timeList[fileName] = float(text[::2])
clipLength = 10
for fileName, time in timeList.items():
arglist = ['ffmpeg', '-i', '"'+fileName+'.mp4"', '-ss', str(time-clipLength), '-t', str(clipLength*2), '-acodec', 'copy' , '-vcodec', 'copy', '"ZEUS'+ fileName + '.mp4"']
print(' '.join(arglist))
os.system(' '.join(arglist))
tempFile = tempfile.NamedTemporaryFile(delete=False)
for fileName in glob.glob('ZEUS*.mp4'):
tempFile.write(("file '" + os.path.realpath(fileName) + "'\n").encode());
tempFile.seek(0)
tempFile.close()
arglist = ['ffmpeg', '-safe', '0', '-f', 'concat', '-i', '"'+tempFile.name+'"', '-c', 'copy', 'ZeusMontage.mp4']
print(' '.join(arglist))
os.system(' '.join(arglist))
#print(timeList)
os.system('PAUSE')

#### print colored text to IDE terminal

0 likes • Jun 1, 2023 • 0 views
Python
from colorama import init, Fore
# Initialize colorama
init()
print(Fore.RED + "This text is in red color.")
print(Fore.GREEN + "This text is in green color.")
print(Fore.BLUE + "This text is in blue color.")
# Reset colorama
print(Fore.RESET + "This text is back to the default color.")