i am trying to create an ARFF file using ArffSaver. (i am actually converting an non-arff file that is very large.)
i am trying to write the file incrementally using the writeIncremental(Instance insntance) method. unfortunately, each call to writeIncremental() results in data being written to System.out -- not to the designated file.
here is a clip of my code:
FileOutputStream out = new FileOutputStream(outFilename);
ArffSaver saver = new ArffSaver();
saver.setDestination(out);
saver.setRetrieval(Saver.INCREMENTAL);
saver.setStructure(instances);
String s = null;
while ((s = in.readLine()) != null) {
Instance instance = toInstance(s, instances);
saver.writeIncremental(instance);
}
saver.writeIncremental(null);
any ideas on how i can get the ArffSaver to write incrementally to the file?
I'm using this and works fine:
saver.setFile(new File(outputFile));
saver.setDestination(new File(outputFile));
Related
I'm trying to display the length of audio files in a Playlist component for an application.
I've not used Juce or C++ before, and I can't understand how to do that from Juce documentation.
I want to make a function that takes an audio file's URL and returns the length in seconds of that audio without playing that file or doing anything else with that file.
I've tried a lot of things, and all of them didn't work, and this is the last thing I've tried:
void PlaylistComponent::trackStats(URL audioURL)
{
AudioFormatManager formatManager;
std::unique_ptr<AudioFormatReaderSource> readerSource;
AudioTransportSource transportSource;
auto* reader = formatManager.createReaderFor(audioURL.createInputStream(false));
if (reader != nullptr)
{
std::unique_ptr<AudioFormatReaderSource> newSource(new AudioFormatReaderSource(reader, true));
transportSource.setSource(newSource.get(), 0, nullptr, reader->sampleRate);
readerSource.reset(newSource.release());
DBG("PlaylistComponent::trackStats(URL audioURL): " << transportSource.getLengthInSeconds());
}
else
{
DBG("Something went wrong loading the file");
}
}
And this is the PlaylistComponent header file:
class PlaylistComponent : public juce::Component,
public juce::TableListBoxModel,
public Button::Listener,
public FileDragAndDropTarget
{
...
}
juce::AudioFormatReaderSource has a method called getTotalLength() which returns the total amount of samples.
Divide that by the sample rate of the file and you have the total length in seconds. Something like this:
if (auto* reader = audioFormatReaderSource->getAudioFormatReader())
double lengthInSeconds = static_cast<double> (audioFormatReaderSource->getTotalLength()) / reader->sampleRate;
You can do this very early on in the audio file opening procedure. You only need an AudioFormatReader instance (no need to create an AudioFormatReaderSource):
// create juce::File from a path juce::String (from a drag & drop event etc).
File file{filePath};
// make sure it is a file and not a directory, etc.
if (!file.existsAsFile()) return;
// create the AudioFormatReader that contains the data
AudioFormatReader *reader = formatManagerInstance.createReaderFor(file);
// make sure a valid reader can be created (not an unsupported file)
if (reader == nullptr) return;
// log the length in seconds
std::cout << reader->lengthInSamples / reader->sampleRate << "\n";
Note: for this to work you will need to
have access to your AudioFormatManager instance and
have already registered the format(s) of the file type (usually through a .registerBasicFormats() call on your AudioFormatManager instance.
IMPORTANT: if successful the createReaderFor() method uses new to create a new AudioFormatReaderInstance, so make sure to use delete on it when you are finished using it to avoid memory leaks
I am new to using the FBX SDK and I am trying to convert an OBJ file to an FBX ASCII file in C++. However, when running the following code it outputs a Binary FBX file and the file seems to be incorrect/"corrupted." The reason I say it is corrupted is because when I insert it into the FBX conversion program that Autodesk provides, it says the input binary file I got as an output from my program is corrupted. Can anyone help me solve this issue please? Thank you in advance.
//Creates a SDK manager
FbxManager* fbxmanager = FbxManager::Create();
//Set the Input/Output Settings for the SDK Manager
//EXP_ = export settings; IMP_ = import setting
FbxIOSettings* ios_settings = FbxIOSettings::Create(fbxmanager, IOSROOT);
ios_settings->SetBoolProp(EXP_ASCIIFBX, true);
fbxmanager->SetIOSettings(ios_settings);
//Creates a Scene
FbxScene* fbxscene = FbxScene::Create(fbxmanager, "");
//Creates an importer object
FbxImporter* fbximporter = FbxImporter::Create(fbxmanager, "");
//Path to the obj file
const char* obj_path = "objs/airboat.obj";
//Path to the saved fbx file
const char* fbx_path = "fbxs/global_mesh.fbx";
//Initilaize the Importer Object with the path and name of the file
bool import_stat = fbximporter->Initialize(obj_path, -1, fbxmanager->GetIOSettings());
import_stat = fbximporter->Import(fbxscene);
//Creates an exporter object
FbxExporter* fbxexporter = FbxExporter::Create(fbxmanager, "");
//Initilaize the Exporter Object with the path and name of the file
bool export_stat = fbxexporter->Initialize(fbx_path, -1,fbxmanager->GetIOSettings());
export_stat = fbxexporter->Export(fbxscene);
EDIT: Sorry forgot to provide debugging output:
All boolean functions result in true.
I created a DLL that takes a Word template, I have code that edits the document using openXML then the result is sent via memory stream to a web service where the documents is downloaded to the user. The issue is that the memory stream is sending is either the original template document without the updates OR sends the updated Word document XML format where the document is obviously corrupted. Here is the code:
string strTemplate = AppDomain.CurrentDomain.BaseDirectory + "Report Template.docx";
WordprocessingDocument wdDocument;
//stream the template
byte[] fileBytes = File.ReadAllBytes(strTemplate);
MemoryStream memstreamDocument = new MemoryStream();
memstreamDocument.Write(fileBytes, 0, (int)fileBytes.Length);
wdDocument = WordprocessingDocument.Open(memstreamDocument, true);
//CODE TO UPDATE TEMPLATE
//Save entire document
wdDocument.MainDocumentPart.Document.Save();
After saving the document, if using the following code the memory stream returns the original template without any updates to the document:
return memstreamDocument;
If using the following code the memory stream returns the openXML data with the updates but the document is corrupted:
MemoryStream memstreamUpdatedDocument = new MemoryStream();
Stream streamDocument = wdDocument.MainDocumentPart.GetStream();
streamDocument.CopyTo(memstreamUpdatedDocument);
return memstreamUpdatedDocument;
Here is my code in the web service which works fine:
HttpResponse response = HttpContext.Current.Response;
MemoryStream stream = GR.GetReport("", intReportID, Culture, ConnectionString, false);
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("content-disposition", "attachment; filename=\"" + "Report_" + intReportID+ ".docx\"");
response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
stream.Position = 0;
stream.CopyTo(response.OutputStream);
response.End();
return response;
After reviewing the supplied code I have provided a modified code snippet that should fit your needs of returning a modified MemoryStream from a file template using the WordprocessingDocument class by OpenXML. Your web service code snippet provided should work as is.
// file path of template
string strTemplate = AppDomain.CurrentDomain.BaseDirectory + "Report Template.docx";
// create FileStream to read from template
FileStream fsTemplate = new FileStream(strTemplate, FileMode.Open, FileAccess.Read);
// create MemoryStream to copy template into and modify as needed
MemoryStream msDocument = new MemoryStream();
// copy template FileStream into document MemoryStream
fsTemplate.CopyTo(msDocument);
// close the template FileStream as it is no longer necessary
fsTemplate.Close();
// reset cursor position of document MemoryStream back to top
// before modifying
msDocument.Position = 0;
// create WordProcessingDocument using the document MemoryStream
using (WordprocessingDocument wdDocument = WordprocessingDocument.Open(msDocument, true)) {
//Access the main Workbook part, which contains all references.
MainDocumentPart mainPart = wdDocument.MainDocumentPart;
/* ... CODE TO UPDATE TEMPLATE ... */
// save modification to main document part
wdDocument.MainDocumentPart.Document.Save();
// close wdDocument as it is no longer needed
wdDocument.Close();
}
// reset cursor position of document MemoryStream back to top
msDocument.Position = 0;
// return memory stream as promised
return msDocument;
I want to create power-point presentation using power-point-template(which may be already exists or may be generated by poi.) for creating power point template file which have a background image in the slides, I write the following code which creates template file which opens in open-office but giving error to opening in Microsoft-power-point.
The Code is
private static void generatePOTX() throws IOException, FileNotFoundException {
String imgPathStr = System.getProperty("user.dir") + "/src/resources/images/TestSameChnl_001_t.jpeg";
File imgFile = new File(imgPathStr);
File potxFile = new File(System.getProperty("user.dir") + "/src/resources/Examples/layout.potx");
FileOutputStream out = new FileOutputStream(potxFile);
HSLFSlideShow ppt = new HSLFSlideShow();
HSLFSlide slide = ppt.createSlide();
slide.setFollowMasterBackground(false);
HSLFFill fill = slide.getBackground().getFill();
HSLFPictureData pd = ppt.addPicture(imgFile, PictureData.PictureType.JPEG);
fill.setFillType(HSLFFill.FILL_PICTURE);
fill.setPictureData(pd);
ppt.write(out);
out.close();
}
After that I tried to create a PPT file using the generated POTX file but
But it's giving error. I am trying bellow code for this.
And the code is
private static void GeneratePPTXUsingPOTX() throws FileNotFoundException, IOException {
File imgFile = new File(System.getProperty("user.dir")+"/src/resources/images/TestSameChnl_001_t.jpeg");
File potx_File = new File(System.getProperty("user.dir") + "/src/resources/Examples/layout.potx" );
File pptx_File = new File(System.getProperty("user.dir") + "/src/resources/Examples/PPTWithTemplate.pptx" );
File movieFile = new File(System.getProperty("user.dir") + "/src/resources/movie/Dummy.mp4");
FileInputStream ins = new FileInputStream(potx_File);
FileOutputStream out = new FileOutputStream(pptx_File);
HSLFSlideShow ppt = new HSLFSlideShow(ins);
List<HSLFSlide> slideList = ppt.getSlides();
int movieIdx = ppt.addMovie(movieFile.getAbsolutePath(), MovieShape.MOVIE_MPEG);
HSLFPictureData pictureData = ppt.addPicture(imgFile, PictureData.PictureType.JPEG);
MovieShape shape = new MovieShape(movieIdx, pictureData);
shape.setAnchor(new java.awt.Rectangle(300,225,420,280));
slideList.get(0).addShape(shape);
shape.setAutoPlay(true);
ppt.write(out);
out.close();
}
And the exception which is coming is as fallows:
java.lang.NullPointerException
at org.apache.poi.hslf.usermodel.HSLFPictureShape.afterInsert(HSLFPictureShape.java:185)
at org.apache.poi.hslf.usermodel.HSLFSheet.addShape(HSLFSheet.java:189)
I am currently working on passing image as Base64 to a rest service. But I am not able to read the file. Here is my code:
if (requestCode == iPictureCode && resultCode == RESULT_OK) {
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
String image = processPictureWhenReady(picturePath);
}
`private String processPictureWhenReady(final String picturePath) {
final File pictureFile = new File(picturePath);
if (pictureFile.exists()) {
// The picture is ready; process it.
Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
bitmap = CameraUtils.resizeImageToHalf(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream);
String base64Image = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
return base64Image;
}
}`
it never enters the if block for 'pictureFile.exists()'
What could be the problem?
It looks like you adapted your code from the example in the developer docs, but you removed the else clause where a FileObserver is used to detect when the image is actually available. You need that part as well because the full-sized image may not be ready immediately when the activity returns.