Tensorboard Error - NameError: name 'tensorboard' is not defined - tensorboard

I am now learning tensorflow but am unable to get tensorboard to work. I tried the simple program below with no luck. The program works before I use the tensorboard code but when I use the tensorboard code I get the following error:
NameError: name 'tensorboard' is not defined
Please any assistance is apppreciated.
import tensorflow as tf
a = tf.constant(5, name="input_a")
b = tf.constant(3, name="input_a")
c = tf.multiply(a,b, name="mul_c")
d = tf.add(a,b, name="add_d")
e = tf.add(c,d, name="add_e")
sess = tf.Session()
sess.run(e)
output = sess.run(e)
writer = tf.summary.FileWriter('/tmp/newtest', graph=sess.graph)
print(sess.run(e))
tensorboard --logdir /tmp/newtest

I believe this is already 'answered', but, to give a sample of what I did, regarding this, and I hope it helps you or others.
This is just covering ending overhead of triggering & showing tensorboard.
import subprocess
import webbrowser
import time
logLocation = 'tflearn_logs'
print("\r\nWould you like to see the visual results (y/N)? ", end='', flush=True)
answer = input()
if answer.strip().lower() == "y":
port = str(8018)
print("Starting Tensorboard to visualize... ")
process = subprocess.Popen(['tensorboard', "--logdir='" + logLocation + "'", '--port=' + port])
# Wait for a few seconds, give the tensorboard a headstart
time.sleep(5)
print("Opening Tensorboard webpage... ")
url = 'http://127.0.0.1:' + port + '/'
# Path differs per OS (Windows, Linux, iOS)
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open(url)
print("Press enter to quit... ", end='', flush=True)
answer = input()
if process is not None:
process.kill()

Related

Wolframalpha in python with GTTS

I am trying to make a Friday like virtual assistant using this code
import os
from gtts import gTTS
import time
import playsound
import speech_recognition as sr
while True:
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
text = get_audio()
if "who are you" in text:
speak(" I am Monday the virtual assistant")
And i was wondering how to put wolfram alpha in it so i would, say search for ..., then it would speak the answer from wolfram alpha.
Any help would be amazing :)
Install wolframalpha
Then add the following to your code:
import wolframalpha
if 'search for ' in text:
text = text.replace("search for ", "")
client = wolframalpha.Client(app_id)
res = client.query(text)
print(next(res.results).text)
speak(next(res.results).text)
To use the API, you have to go to the homepage, sign up for an account, create an app and get an app id.
To avoid getting any errors, keep the indentation in your 'speak' function uniform.

P4Python Perforce API does not honor P4_TRUST when running as a Collectd Python (2.7) Plugin

Using Collectd Python Plugin to collect Graphite Metrics from Perforce using their P4Python API. All is good with the exception of ssl based connections which require a P4_TRUST command to assert the fingerprint for the given server prior to the login() command.
Specifically:
import collectd
from P4 import P4
def configer(configobj):
collectd.info('Configuring Perforce Plugin')
def initer():
collectd.info('Initializing Perforce Plugin')
def reader():
p4 = P4()
p4.port = "ssl:perforce1.lab.dell.com:1666"
p4.user = "perforce"
p4.charset = 'utf8'
p4.password = "Password"
p4.connect()
p4.run_trust("-i", '60:27:3E:E0:A6:58:8E:13:4F:9E:8C:C8:BF:C3:26:C2:91:2F:78:33')
p4.run_login()
result = p4.run('license', '-u')
collectd.info("User limit is :" + result[0].get('userLimit'))
#
p4.disconnect()
# -- Hook Callbacks, Order is important! ==#
collectd.register_config(configer)
collectd.register_init(initer)
collectd.register_read(reader)
will result in the following run time errors noted in collectd.log
`[2017-04-27 11:33:58] Unhandled python exception in read callback: P4Exception: [P4#run] Errors during command execution( "p4 login" )
[Error]: "The authenticity of '10.99.248.42:1666' can't be established,\nthis may be your first attempt to connect to this P4PORT.\nThe fingerprint for the key sent to your client is\n60:27:3E:E0:A6:58:8E:13:4F:9E:8C:C8:BF:C3:26:C2:91:2F:78:33\nTo allow connection use the 'p4 trust' command."
[2017-04-27 11:33:58] read-function of plugin `python.PerforceMetrics' failed. Will suspend it for 20.000 seconds.
`
The same code run outside the collectd context runs as expected.
from P4 import P4
import logging
FORMAT = '%(asctime)-15s: %(name)s: %(levelname)s : %(message)s'
logging.basicConfig(format=FORMAT, filename='/var/log/pytest.log', level=logging.INFO)
def reader():
p4 = P4()
p4.port = "ssl:perforce1.cec.lab.emc.com:1666"
p4.user = "perforce"
p4.charset = 'utf8'
p4.password = "Password"
p4.connect()
p4.run_trust("-i", '80:25:3E:E0:A6:58:8E:13:4F:9E:8C:C8:BF:C3:26:C2:91:2F:78:33')
p4.run_login()
result = p4.run('license', '-u')
logging.info ("User limit is :" + result[0].get('userLimit'))
#
p4.disconnect()
reader()
NOTE: None SSL connections that do not require "P4 Trust" work correctly under collectd.
Any clues, idea's or how to approach this?
Okay so worked with Perforce support and while they struggled with getting collectd running they did point me in the right direction. Specifically P4TRUST as an environment variable can be defined that points to the .p4trust file that is typically used and by default created with the application of the p4.run_trust p4Python API call.
So the trick is to define the environment P4TRUST environment variable with in your python plugin:
import collectd
import os
from P4 import P4
def configer(configobj):
collectd.info('Configuring Perforce Plugin')
def initer():
collectd.info('Initializing Perforce Plugin')
def reader():
os.environ["P4TRUST"]="/root/.p4trust"
p4 = P4()
p4.port = "ssl:perforce1.lab.dell.com:1666"
p4.user = "perforce"
p4.charset = 'utf8'
p4.password = "Password"
p4.connect()
p4.run_trust("-i", '60:27:3E:E0:A6:58:8E:13:4F:9E:8C:C8:BF:C3:26:C2:91:2F:78:33')
p4.run_login()
result = p4.run('license', '-u')
collectd.info("User limit is :" + result[0].get('userLimit'))
#
p4.disconnect()
# -- Hook Callbacks, Order is important! ==#
collectd.register_config(configer)
collectd.register_init(initer)
collectd.register_read(reader)
Note: the inclusion of the os library and the use of
os.environ["P4TRUST"]="/root/.p4trust"
That's the ticker!

Using gdal_calc multiple times within a Python Script, Issues with Visual C++ for Python 2.7

I've exhausted what I'm capable of currently regarding the script that I have posted below. I am unable to properly call gdal_calc.py with this script. I have received various error message regarding a lack of .dll files to a win32 error.
I have installed and reinstalled GDAL, however I continue to receive an error message that suggests I don't have osgeo, and I cannot install GDAL properly within my Python27 pathway because of an issue with Visual C++ for Python because I either don't have the proper .bat file OR I get this message.
fatal error C1083: Cannot open include file: 'cpl_port.h': No such file or directory
I would appreciate even a direction to be point in, because I am a novice and this is over my head.
Thanks,
import os
import sys
from osgeo import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import PIL
from PIL import Image
# constants
gdalTranslate = r'C:\\Program Files (x86)\\GDAL\\gdal_translate.exe'
src = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img"
srcVH = r"C:\Users\jack\Desktop\RUA_FIL\IMG-VH-ALOS2110871010-160611-HBQR1.5RUA.img"
dstVH = r"C:\Users\jack\Desktop\New_Trash\vhFloat32-3.img"
dst = r"C:\\Users\jack\Desktop\\New_Trash\hvFloat32-3.img"
cmd = "-ot Float32 -of HFA" # hopefully this works
#gdalCalc = r'C:\Python27\ArcGIS10.4\Scripts\dist\gdal_calc.exe'
#hvFloat32 = r"C:\Users\jack\Desktop\New_Trash\hvFloat32-1.img"
#vhFloat32 = r"C:\Users\jack\Desktop\New_Trash\hvFloat32-1.img"
#prevName = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA"
#newName = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img"
#os.rename(prevName,newName)
# setting def
#def gdal_Translate (item):
#return item
hvfullCmd = ' '.join([gdalTranslate, cmd, gdal_Translate(src), gdal_Translate(dst)])
subprocess.Popen(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd,gdal_Translate(srcVH),gdal_Translate(dstVH)])
subprocess.Popen(vhfullCmd)
# Run gdal_calc.py for HV
try:
os.system('C:\Users\jack\Python\QGIS Python Scripts\ridofZs.py')
except:
print ("This isn't working")
sys.exit()
subprocess.call([sys.executable,'C:\Program Files (x86)\GDAL\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\hvFloat32.img', '--outfile=C:\Users\jack\Desktop\New_Trash\NEWCALCHV-2.img','--calc=A*(A>=1)'])
# Run gdal_calc.py for VH
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\vhFloat32.img', '--outfile=C:\Users\jack\Desktop\New_Trash\NEWCALCVH-2.img','--calc=A*(A>=1)'])
# Run gdal_calc.py to dB for HV
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\NEWCALCHV-2.img', '--outfile=C:\Users\jack\Desktop\New_Trash\HVindB.img','--calc=10*log10(power(A,2))-83'])
# Run gdal_calc.py to dB for HV
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\NEWCALCVH-2.img', '--outfile=C:\Users\jack\Desktop\New_Trash\VHindB.img','--calc=10*log10(power(A,2))-83'])
# Open Rasters using GDAL
hvRaster = gdal.Open("C:\\Users\\jack\\Desktop\\New_Trash\\hvFloat32.img")
vhRaster = gdal.Open("C:\\Users\\jack\\Desktop\\New_Trash\\vhFloat32.img")
# Get RasterBand
hvRasterBand = hvRaster.GetRasterBand(1)
vhRasterBand = vhRaster.GetRasterBand(1)
# Get Raster Mean
hvMean = hvRasterBand.GetStatistics(0,1)[2]
vhMean = vhRasterBand.GetStatistics(0,1)[2]
#### Maybe not needed
print hvMean
print vhMean
# calculate stDev
rasterList = (hvMean,vhMean)
stDev = np.std(rasterList)
#print stDev
if stDev >= 0.06:
print "The imagery isn't acceptable"
if stDev <= 0.06:
print "The imagery is acceptable"

Determining wait time while executing a binary on QNX prompt using telnet

I am processing certain output binary files using sloginfo on QNX, I have used ftp/telnet/vmware to get to a point where I upload the binary from my machine to the vmware instance and then run the sloginfo command.
The issue is that binary files which need to be processed are of inconsistent size (ranging from 50mb to 200mb), and the time needed to process each of these files is different, thus making it impossible to determine the wait/sleep time required.
I need to know if sloginfo returns a value which can be used as a flag. I tried using tn.read_until(), without getting desired results.
#
import os, sys, telnetlib, time
from ftplib import FTP
def upload(ftp, filed):
ext = os.path.splitext(filed)[1]
if ext in (".txt", ".htm", ".html"):
ftp.storlines("STOR " + filed, open(filed))
else:
ftp.storbinary("STOR " + filed, open(filed, "rb"), 1024)
def gettext(ftp, filename, outfile=None):
# fetch a text file
if outfile is None:
outfile = sys.stdout
# use a lambda to add newlines to the lines read from the server
ftp.retrlines("RETR " + filename, lambda s, w=outfile.write: w(s+"\n"))
if __name__ == '__main__':
dbfile = "LOG1"
nonpassive = False
remotesite = '192.168.0.128'
ftp_port = '21'
tel_port = '23'
password = 'root'
ftp = FTP()
ftp.connect(remotesite, ftp_port)
ftp.login('root','root')
print 'Uploading the Log file... Please wait...'
upload (ftp, dbfile)
print 'File Uploaded Successfully...'
tn = telnetlib.Telnet(remotesite, tel_port)
tn.read_until("login: ")
tn.write('root' + "\n")
if password:
tn.write(password + "\n")
tn.write("sloginfo LOG1 >> LOG1.txt\n")
**#need to get more control on this sleep time**
time.sleep(300)
print 'Downloading text file...'
gettext(ftp, "LOG1.txt", open(r'LOG1.txt','wb'))
ftp.close()
tn.close()
tn.write("sloginfo LOG1 >> LOG1.txt\n") modified the above comment with tn.write ('sloginfo '+ strdbfile + '>> ' + strdbfiletxt+ '; echo Done!\n') and this has resolved the issue

Program for Backup - Python

Im trying to execute the following code in Python 2.7 on Windows7. The purpose of the code is to take back up from the specified folder to a specified folder as per the naming pattern given.
However, Im not able to get it work. The output has always been 'Backup Failed'.
Please advise on how I get resolve this to get the code working.
Thanks.
Code :
backup_ver1.py
import os
import time
import sys
sys.path.append('C:\Python27\GnuWin32\bin')
source = 'C:\New'
target_dir = 'E:\Backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr {0} {1}".format(target,''.join(source))
print('This is a program for backing up files')
print(zip_command)
if os.system(zip_command)==0:
print('Successful backup to', target)
else:
print('Backup FAILED')
See if escaping the \'s helps :-
source = 'C:\\New'
target_dir = 'E:\\Backup'