Resource Not Found Exception in pyglet - pyglet

I'm using Python 2.6.6 and pyglet 1.1.4. In my "Erosion" folder, I have "Erosion.py" and a folder named "Images." Inside images, there are .png images. One image is named "Guard.png."
In "Erosion.py" there is a segment that goes like so:
pyglet.resource.path = ['Images']
pyglet.resource.reindex()
self.image = pyglet.resource.image('%s%s' % (character, '.png'))
When I run this, I am given
File "C:\Python26\lib\site-packages\pyglet\resource.py", line 394, in file raise ResourceNotFoundException(name)
ResourceNotFoundException: Resource "Guard.png" was not found on the path. Ensure that the filename has the correct captialisation.
I have tried changing the path to ['./Images'] and ['../Images']. I've also tried removing the path and the reindex call and putting Erosion.py and Guard.png in the same folder.

This is what i do to be able to load resources:
pyglet.resource.path = ['C:\\Users\\myname\\Downloads\\temp']
pyglet.resource.reindex()
pic = pyglet.resource.image('1.jpg')
texture = pic.get_texture()
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
texture.width = 960
texture.height = 720
texture.blit(0, 0, 0)

try this
pyglet.image.load('path/to/image.png')

If the relative path is not working you can try with the absolute path using the os module.
import pyglet
import os
working_dir = os.path.dirname(os.path.realpath(__file__))
pyglet.resource.path = [os.path.join(working_dir,'Images')]
pyglet.resource.reindex()
image = pyglet.resource.image('character.png'))
It's better to use the os.path.join method instead of writing it as a string for a better cross-platform support.

I get a problem like this using pyglet and pyscripter.(the text editor) In order for the file to be found I have to restart the editor before running the program.
This might be a problem with pyscripter however.

It is worth looking into: http://pyglet.readthedocs.io/en/pyglet-1.3-maintenance/programming_guide/resources.html
You should include all the directories into:
pyglet.resource.path = [...]
Then pass the ONLY the file name when you call:
pyglet.resource.image("ball_color.jpeg")
Try:
import os
import pyglet
working_dir = os.path.dirname(os.path.realpath(__file__))
image_dir = os.path.join(working_dir, 'images')
sound_dir = os.path.join(working_dir, 'sound')
print working_dir
print "Images are in: " + image_dir
print "Sounds are in: " + sound_dir
pyglet.resource.path = [working_dir, image_dir, sound_dir]
pyglet.resource.reindex()
try:
window = pyglet.window.Window()
image = pyglet.resource.image("ball_color.jpeg")
#window.event
def on_draw():
window.clear()
image.blit(0, 0)
pyglet.app.run()
finally:
window.close()
The use of try and finally are not necessary, but they are recommended. You might end up with a lot of open windows and pyglet back processes if you don't close the window when there are errors.

pyglet 1.4.4 format: HUD_img = pyglet.resource.image('ui\ui_gray_block_filled.png')
pyglet 1.4.8 format: HUD_img = pyglet.resource.image('ui/ui_gray_block_filled.png')
I was using pyglet 1.4.4 and was able to use this the first format.
After upgrading to pyglet 1.4.8 I had the error: pyglet.resource.ResourceNotFoundException: Resource "your_resource_path" was not found on the path.
Switching to the 2nd format with forward slashes solved this issue for me. Not sure why this change was made...I'm sure there was a good reason for it.

Related

How do I encoding musescore in Music21?

from music21 import *
us = environment.UserSettings()
us["musicxmlPath"] = r"C:/Program Files/MuseScore 3/bin/MuseScore3.exe"
us["musescoreDirectPNGPath"] = r"C:/Program Files/MuseScore 3/bin/MuseScore3.exe"
.
.
.
xml_file_name = f'output_dance_{str(int(time.time()))}.musicxml'
xml_file_path = f'app/data/output_audio/{xml_file_name}'
midi_stream.write('musicxml', fp=xml_file_path)
When I make musicxml in music21, how can I encode musiccore instead of music21?
music21 did actually encode the output from scratch, so that's why it's listed in <software>, but if you wish to change it:
from music21 import *
beach_score = corpus.parse('beach')
beach_score.metadata.software = ['Musescore']
If .metadata doesn't return anything for your score, you may need to insert a metadata.Metadata object into the beginning of your score and manipulate that.

Yocto - git revision in the image name

By default Yocto adds build timestamp to the output image file name, but I would like to replace it by the revision of my integration Git repository (which references all my layers and configuration files). To achieve this, I put the following code to my image recipe:
def get_image_version(d):
import subprocess
import os.path
try:
parentRepo = os.path.dirname(d.getVar("COREBASE", True))
return subprocess.check_output(["git", "describe", "--tags", "--long", "--dirty"], cwd = parentRepo, stderr = subprocess.DEVNULL).strip().decode('UTF-8')
except:
return d.getVar("MACHINE", True) + "-" + d.getVar("DATETIME", True)
IMAGE_VERSION = "${#get_image_version(d)}"
IMAGE_NAME = "${IMAGE_BASENAME}-${IMAGE_VERSION}"
IMAGE_NAME[vardepsexclude] = "IMAGE_VERSION"
This code works properly until I change Git revision (e.g. by adding a new commit). Then I receive the following error:
ERROR: When reparsing /home/ubuntu/yocto/poky/../mylayer/recipes-custom/images/core-image-minimal.bb.do_image_tar, the basehash value changed from 63e1e69797d2813a4c36297517478a28 to 9788d4bf2950a23d0f758e4508b0a894. The metadata is not deterministic and this needs to be fixed.
I understand this happens because the image recipe has already been parsed with older Git revision, but why constant changes of the build timestamp do not cause the same error? How can I fix my code to overcome this problem?
The timestamp does not have this effect since its added to vardepsexclude:
https://docs.yoctoproject.org/bitbake/bitbake-user-manual/bitbake-user-manual-metadata.html#variable-flags
[vardepsexclude]: Specifies a space-separated list of variables that should be excluded from a variable’s dependencies for the purposes of calculating its signature.
You may need to add this in a couple of places, e.g.:
https://git.yoctoproject.org/poky/tree/meta/classes/image-artifact-names.bbclass#n7
IMAGE_VERSION_SUFFIX ?= "-${DATETIME}"
IMAGE_VERSION_SUFFIX[vardepsexclude] += "DATETIME SOURCE_DATE_EPOCH"
IMAGE_NAME ?= "${IMAGE_BASENAME}-${MACHINE}${IMAGE_VERSION_SUFFIX}"
After some research it turned out the problem was in this line
IMAGE_VERSION = "${#get_image_version(d)}"
because the function get_image_version() was called during parsing. I took inspiration from the source file in aehs29's post and moved the code to the anonymous Python function which is called after parsing.
I also had to add vardepsexclude attribute to the IMAGE_NAME variable. I tried to add vardepvalue flag to IMAGE_VERSION variable as well and in this particular case it did the same job as vardepsexclude. Mentioned Bitbake class uses both flags, but I think in my case using only one of them is enough.
The final code is below:
IMAGE_VERSION ?= "${MACHINE}-${DATETIME}"
IMAGE_NAME = "${IMAGE_BASENAME}-${IMAGE_VERSION}"
IMAGE_NAME[vardepsexclude] += "IMAGE_VERSION"
python () {
import subprocess
import os.path
try:
parentRepo = os.path.dirname(d.getVar("COREBASE", True))
version = subprocess.check_output(["git", "describe", "--tags", "--long", "--dirty"], cwd = parentRepo, stderr = subprocess.DEVNULL).strip().decode('UTF-8')
d.setVar("IMAGE_VERSION", version)
except:
bb.warning("Could not get Git revision, image will have default name.")
}
EDIT:
After some research I realized it's better to define a global variable in layer.conf file of the layer containing the recipes referencing the variable. The variable is set by a python script and is immediately expanded to prevent deterministic build warning:
layer.conf:
require conf/image-version.py.inc
IMAGE_VERSION := "${#get_image_version(d)}"
image-version.py.inc:
def get_image_version(d):
import subprocess
import os.path
try:
parentRepo = os.path.dirname(d.getVar("COREBASE", True))
return subprocess.check_output(["git", "describe", "--tags", "--long", "--dirty"], cwd = parentRepo, stderr = subprocess.DEVNULL).strip().decode('UTF-8')
except:
bb.warn("Could not determine image version. Default naming schema will be used.")
return d.getVar("MACHINE", True) + "-" + d.getVar("DATETIME", True)
I think this is cleaner approach which fits BitBake build system better.

How do I save a TFDV stats in the correct format for them to be loaded back in?

It is puzzling to me that there is a tfdv.load_statistics() function, but no corresponding tfdv.write_statistics() function. How do I go about saving the statistics, and then loading them again?
e.g.
import tensorflow_data_validation as tfdv
stats = tfdv.generate_statistics_from_dataframe(df)
# how do I save?
# load back for later use
saved_stats = tfdv.load_statistics('saved_stats.stats')
I can save the string representation to a file, but this is not the format that load_statistics expects.
with open('saved_stats.stats', 'w') as o:
o.write(str(stats))
Pointers anyone?
have you tried this : tfdv.utils.stats_util.write_stats_text ?
In the current tfdv version 1.3.0 there are the following methods that can be used:
load_stats_text
write_stats_text
Example:
import tensorflow_data_validation as tfdv
stats = tfdv.generate_statistics_from_dataframe(df)
stats_path = "my-stats-file.stats"
# saving
tfdv.write_stats_text(stats, stats_path)
# loading
stats = tfdv.load_stats_text(stats_path)
Okay figure out this hacky way to do it.
df = ... # create pandas df
from tensorflow_metadata.proto.v0 import statistics_pb2
import tensorflow_data_validation as tfdv
stats = tfdv.generate_statistics_from_dataframe(df)
# save it
with open('saved_stats.stats', 'wb') as o:
o.write(stats.SerializeToString())
# load back for later use
with open('saved_stats.stats', 'rb') as i:
loaded_stats = statistics_pb2.FromString(i.read())
There's a function called tfdv.load_stats_binary that you can use to solve this problem.

Unable to run compiled Matlab code that uses "Presentation" for report generation

I am trying to convert a simple program that uses "Presentation" (from reportgen package) to a .exe.
The code is as follows:
makePPTCompilable();
import mlreportgen.ppt.*
slides = Presentation('mySlideAddPresentation.pptx');
slide1 = add(slides,'Title and Picture');
plane = Picture(which('tulips.jpg'));
plane.X = '4in';
plane.Y = '4in';
plane.Width = '5in';
plane.Height = '2in';
add(slide1,plane);
close(slides);
I get the following error on running the complied version:
" Undefined function 'Presentation' for input arguments of type 'char'"
Any idea what I am missing here?I am on 2015b, used the following link for help: https://www.mathworks.com/help/rptgen/ug/compile-a-presentation-program.html
You need to make the reportgen compilable, see here and here
In my code I put:
if ismcc || isdeployed
% Make sure DOM is compilable
makeDOMCompilable()
end
Then it compiles fine! :)

Wxpython drag and drop folder path, Popen not working with spaces on Windows

I have the below code which allows the user to drag and drop a folder to get the folder path. I then take this folder path and use it to pass through to a command line application in Windows using Popen. This all works fine except if there are spaces in the folder path, which then fails. I am currently getting round this by using win32api.GetShortPathName(folder_list) which shortens them to DOS 8.3 spec, but I would like to use the full absolute path. I know the command line application takes paths with spaces as I also use a batch file with drag and drop which works with spaces in paths. I have tried inserting escapes, etc, still no luck. How can I get this to work properly with full folder paths with spaces?
class SubmissionPane(wx.Panel):
def __init__(self, parent, queue_control):
wx.Panel.__init__(self, parent, -1)
self.parent = parent
self.queue_control = queue_control
self.selected_folder = None
self.txtTitle = wx.TextCtrl(self, pos=(125, 70), size=(215, 25), style= wx.SUNKEN_BORDER, value="Enter Series Title Here")
self.txtTitle.Show(False)
self.drop_target = MyFileDropTarget(self)
self.SetDropTarget(self.drop_target)
def SetSubmissionFolders(self, folder_list):
"""Called by the FileDropTarget when files are dropped"""
print "Setting submission folders", folder_list
self.tc_files.SetValue(','.join(folder_list))
self.selected_folders = folder_list
class MyFileDropTarget(wx.FileDropTarget):
""""""
def __init__(self, window):
wx.FileDropTarget.__init__(self)
print "Creating a drop file target..."
self.window = window
def OnDropFiles(self, x, y, filenames):
self.window.SetSubmissionFolders(filenames)
I then submit this to Popen like this:
command1 = commandLineApplication + folder_list
process = Popen(command1, shell=True, stdin=PIPE)
You probably just need to put quotes around each of the file paths. That usually works. The win32api.GetShortPathName is a neat trick though.
Here's one way to do it:
n = ['"%s"' % x for x in folderlist]
Then do the
','.join(folder_list)
You mentioned in your code.