How can I convert a Wavefront's .obj file to a .off file ?
You can use the open source GUI software Meshlab.
File > Import Mesh (Ctrl-I)
File > Export Mesh As and chose "Object file format (.off)"
You can use the CLI, closed source, binary only, meshconv
chmod u+x meshconv
./meshconv input.obj -c off -o output.off
Howether the result seems to be a bit different from what I get in my answer using Meshlab because I could not load the resulting .off file in CGAL (the error look like this one).
This should work for triangular meshes
def conv_obj(file):
x = open(file)
k = 0
while "\n" in x.readline():
k += 1
x = open(file)
out = str()
v = 0
f = 0
for i in range(k) :
y = x.readline().split()
if len(y) > 0 and y[0] == "v" :
v += 1
out += str(y[1]) + " " + str(y[2]) + " " + str(y[3]) + "\n"
if len(y) > 0 and y[0] == "f" :
f += 1
out += "3 " + str(int(y[1])-1) + " " + str(int(y[2])-1) + " " + str(int(y[3])-1) + "\n"
out1 = "OFF\n" + str(v) + " " + str(f) + " " + "0" + "\n" + out
w = open(file.strip("obj") + "off", "w")
w.write(out1)
w.close()
x.close()
return "done"
Related
How can I debug a cgi script executing just 1 command offlineimap ?
The script uses just input from the user containing source and destination details and executes the offlineimap command. Sometimes if the source has some issues, the migration doesn't happen to the destination mailbox. I need to catch all these exceptions. Is there a way to do it? Main part of the script as follows:
f = open(os.path.join(mfolder_path,mfile),"w+")
f.write(
"[general]\n"
"accounts = " + muserpart + '\n'
"[Account " + muserpart + "]\n"
"localrepository = " + muserpart + "-Local\n"
"remoterepository = " + muserpart + "-Remote\n\n"
"[Repository "+ muserpart + "-Local]\n"
"type = IMAP\n"
"remotehost = " + mremote_host + "\n"
"remoteuser = " + mremote_user + "\n"
"remotepass = " + mremote_pass + "\n"
"ssl = no" + "\n"
"starttls = yes" + "\n"
"#createfolders = no" + "\n\n"
"[Repository "+ muserpart + "-Remote]\n"
"type = IMAP\n"
"remotehost = " + mhost + "\n"
"remoteuser = " + musername + "\n"
"remotepass = " + mpassword + "\n\n"
"ssl = " + mssl + "\n"
+ mstring +
"readonly = yes\n"
'nametrans = lambda f: "Old-" + f\n'
)
f.close()
'''
# py3.5 upwards
process = subprocess.Popen(['offlineimap', '-c', mfile],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
#stdout, stderr = process.communicate()
'''
try:
message = 'Started syncing the mails...'
#py2.7
subprocess.call(['offlineimap', '-c', mfile],
stdout=subprocess.PIPE)
except Exception as e:
print(e)
message = e
n = 0
I am working on classifying sounds with Deep Learning and my problem is that I run out of memory when I try to convert .wav files to spectrograms using lib.load() from librosa.
split = ['train','val']
categories=['URTI', 'Healthy', 'Asthma', 'COPD', 'LRTI', 'Bronchiectasis','Pneumonia', 'Bronchiolitis']
files_loc = "path"
i=0
for s in split:
for cat in categories:
print('-' * 100)
print('working on ' + cat +" "+str(s)+" "+ '...')
print('-' * 100)
files = [f for f in listdir(files_loc + s + '/' + cat + '/') if isfile(join(files_loc + s + '/' + cat + '/', f)) and is_wav(f)]
for f in files:
convert_to_spec_image(file_loc = files_loc, category=cat, filename=f, is_train=(s == 'train'), verbose=False)
i=i+1
print("We have processed: "+str(i)+" "+ str((i/773*100))+" % "+" so far")
The function convert_to_spec_image is this:
#create images using librosa spectogram
def convert_to_spec_image(file_loc, filename, category, is_train=False, verbose=False):
'''
Converts audio file to spec image
Input file includes path
Saves the file to a png image in the save_directory
'''
train_ = 'train/'
val_ = 'val/'
loc = file_loc + train_ + category + '/' + filename
if is_train == False:
loc = file_loc + val_ + category + '/' + filename
if verbose == True:
print('reading and converting ' + filename + '...')
y, sr = lb.load(loc)
#Plot signal in
plt.figure(figsize=(10,3))
src_ft = lb.stft(y)
src_db = lb.amplitude_to_db(abs(src_ft))
specshow(src_db, sr=sr, x_axis='time', y_axis='hz')
plt.ylim(0, 5000)
save_directory = "C:/Users/raulf/Desktop/espectograms2/"
filename_img = filename.split('.wav')[0]
save_loc = save_directory + train_ + category + '/' + filename_img + '.png'
if is_train == False:
save_loc = save_directory + val_ + category + '/' + filename_img + '.png'
plt.savefig(save_loc)
plt.close('all')
if verbose == True:
print(filename + ' converted!')
plt.close('all')
I am trying to reuse the code from this Kaggle Notebook:
https://www.kaggle.com/danaelisanicolas/cnn-part-3-create-spectrogram-images
Thanks in advance
So I have been following this code and placed it in and it all seemed to be going well until the last line where I was printing the final string and a TypeError came up. Where is my mistake?
kingName = input("Yo King! Please type in your name at the prompt")
numJewels = input("Hey " + kingName + ", how many jewels are there?")
numJewels = int(numJewels)
costOfEachJewel = input("Yo " + kingName + ", how much does each jewel cost?")
costOfEachJewel = int(costOfEachJewel)
print (costOfEachJewel * numJewels)
dudeNames = ["Athos", "Pothos", "Aramis"]
dudeAges = [55,34, 67]
dudeNames.insert(0, "D'Artagnan")
print (dudeNames)
dudeAges.append(16)
print (dudeAges)
tempVariable = dudeNames.pop(0)
tempVariable
dudeNames.append(tempVariable)
print (dudeNames)
print (dudeAges)
print ("Total number of dudes: " + str(len(dudeNames)))
dudeToKill = input("Yo " + kingName + "please enter the # of the dude to kill")
print ("zapping all history of " + str(len(dudeNames[dudeToKill-1])))
dudeToKill must be an int, convert the input to int before performing dudeToKill - 1 operation.
dudeToKill = int(input("Yo " + kingName + "please enter the # of the dude to kill"))
kingName = input("Yo King! Please type in your name at the prompt")
numJewels = int(input("Hey " + kingName + ", how many jewels are there?"))
costOfEachJewel = int(input("Yo " + kingName + ", how much does each jewel cost?"))
print(costOfEachJewel * numJewels)
dudeNames = ["Athos", "Pothos", "Aramis"]
dudeAges = [55, 34, 67]
dudeNames.insert(0, "D'Artagnan")
print(dudeNames)
dudeAges.append(16)
print(dudeAges)
tempVariable = dudeNames.pop(0)
tempVariable
dudeNames.append(tempVariable)
print(dudeNames)
print(dudeAges)
print("Total number of dudes: " + str(len(dudeNames)))
dudeToKill = int(input("Yo " + kingName + "please enter the # of the dude to kill"))
print("zapping all history of " + str(len(dudeNames[dudeToKill-1])))
hope this will help
I'm trying to generate Mandelbrot set and dump image in the directory .py file is saved
import math
width = 640
height = 480
image = [[[255 for c in range(3)] for x in range(width)] for y in range(height)]
for y in range(height):
imag = (y-(height/2)) / float(height)*2.5
for x in range(width):
real = ((x-(width/2)) / float(width)*2.5)-0.5
z = complex ( real, imag )
c = z
for i in range(255):
z = z*z + c
if ( abs(z)>2.5 ):
image[y][x]=[i,i,i]
break
output = open ( 'mandelbrot_set.ppm', 'w' )
output.write("P6 " + str(width) + " " + str(height) + " 255\n")
for y in range(height):
for x in range(width):
output.write(bytearray(image[y][x]))
output.close()
Expected output is image of mandelbrot set in directory, where I do get a file but it shows nothing and there is error in terminal, which is as following
Traceback (most recent call last):
File "mandelbrot.py", line 21, in <module>
output.write(bytearray(image[y][x]))
TypeError: write() argument must be str, not bytearray
If you want to write binary data to the file you have to open it in binary mode:
output = open ( 'mandelbrot_set.ppm', 'wb' )
But, in that case, you wont be able to write text, so the line:
output.write("P6 " + str(width) + " " + str(height) + " 255\n")
will throw an error. You should encode such string:
output.write(("P6 " + str(width) + " " + str(height) + " 255\n").encode())
That will convert the string to an array of bytes (a bytes object) using the specified encoding, which is utf-8 by-default.
precommit hook returns list of checked marked files in tortoiseHg
So Basically i am writing a pre-commit hook which, will static analysis the code and give me HTML output of error report.
What I had done:
I am done with
Get a list MODIFIED and ADDED files and run static code analyzer on it.
get Result in the form of HTML.
Most of the work is done,
But issue is, How to get list file which are marked check in TortoiseHg, Not all the list of ADDED and MODIFIED files
So in list of files, only get 2 files in this example:
1. .classpath
2. servlet-api.jar
Basically I want to read tortoiseHg Ui in python script :)
Thanks in advance
After years of years research and after reading Ayurvedic books
Just kidding...............
So finally I was able to write pre-commit hooks script, after few days after posting the question here!
Pre-requisite:
Python above version 2 or any distribution of version 3
SonarQube running instance
a sonar-scanner.properties file
So the pre-commit hook is
import subprocess
import re
import os
import json
from tkinter import *
print(os.getcwd())
#get current working directory echo pwd
repoPath = os.getcwd()
#hg status -a -m gives the modified files and added files
#git status --porcelain
cmd = "hg status -a -m"
#this is the html file name to show report errors
sonarScannedReport = 'SonarScannedReport.html'
# returns output as byte string
returned_output = subprocess.check_output(cmd)
# List of Modified and Added files
fileList = returned_output.splitlines()
fileList = list(fileList)
# iterate over list and find .java files
# seperate list with "." seprator
javaFilesAbsolutePaths = []
for file in fileList:
fileExtList = file.decode("utf-8").split(".")
if fileExtList[1] == "java":
fileRelativePath = re.split('A |M ', file.decode("utf-8"))
javaFilesAbsolutePaths.append(os.path.abspath(fileRelativePath[1].replace('/', '\\')))
# Working Directory to PMD working Directory
def getOutputFileName(java_file):
fileArr = java_file.split("\\")
return fileArr[len(fileArr) - 1].split('.')[0]
issue_found = False
javaFiles = ""
i = 0
for javaFile in javaFilesAbsolutePaths:
if i == 0:
javaFiles = javaFile
else:
javaFiles = javaFiles + "," + javaFile
# javaFiles comma separated string and now run sonar command on it.
cmd1 = " -Dsonar.analysis.mode=preview -Dsonar.issuesReport.console.enable=true "
cmd2 = "-Dsonar.java.binaries=" + repoPath.replace('\\',
'/') + "/CatalystOne/res/WEB-INF/classes -Dsonar.issuesReport.json.enable"
cmd = "sonar-scanner -Dsonar.sources=" + javaFiles + cmd1 + cmd2
outputJsonFile = ""
AbsPath = ""
try:
p2 = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output2, err2) = p2.communicate()
p2_status = p2.wait()
output = output2.decode("utf-8").splitlines()
for o in output:
if "INFO: Export issues to" in o:
AbsPath = os.getcwd() + "\\.scannerwork\\sonar-report.json"
break
if AbsPath == "":
print("Problem with Sonar Scanner Connections")
exit(1)
with open(AbsPath, 'r') as f:
array = json.load(f)
issues = array['issues']
f = open(sonarScannedReport, 'w')
HTML_OPEN = "<html><head><title>Sonar scanner report </title></head><body align='center'>"
TABLE_OPEN = "<table>"
TR_OPEN = "<tr>"
TR_CLOSE = "</tr>"
TH_OPEN = "<th>"
TH_CLOSE = "</th>"
TD_OPEN = "<td>"
TD_CLOSE = "</td>"
TABLE_CLOSE = "</table>"
HTML_CLOSE = "</body></html>"
table_header = TR_OPEN + TH_OPEN + "FILE" + TH_CLOSE + TH_OPEN + "L. NO" + TH_CLOSE + TH_OPEN + "Message" + TH_CLOSE + TH_OPEN + "Severity" + TH_CLOSE + TH_OPEN + "Rule" + TH_CLOSE + TR_CLOSE
f.write(HTML_OPEN)
f.write(TABLE_OPEN)
f.write(table_header)
for issue in issues:
fileName = issue['component'].split(':')[1]
if 'line' in issue:
lineNo = str(issue['line'])
else:
lineNo = ""
if 'rule' in issue:
rule = str(issue['rule'])
else:
rule = ""
issue_found = True;
tr = TR_OPEN + TD_OPEN + fileName + TD_CLOSE + \
TD_OPEN + lineNo + TD_CLOSE + \
TD_OPEN + issue['message'] + TD_CLOSE + \
TD_OPEN + issue['severity'] + TD_CLOSE + \
TD_OPEN + rule + TD_CLOSE + \
TR_CLOSE
f.write(tr)
f.write(TABLE_CLOSE)
f.write(HTML_CLOSE)
f.close()
except ValueError:
print(ValueError)
if issue_found:
errorMsg = "Please open following file to problems with your code :) "
reportFilePath = os.getcwd() + "\\" + sonarScannedReport
window = Tk()
window.title("Error report")
window.geometry('550x100')
lbl = Label(window, text=errorMsg + " \n " + reportFilePath)
lbl.grid(column=0, row=0)
window.mainloop()
exit(1)
else:
exit(0)
Soon I will write Github readme or can make a tutorial