How can I set my include files in clang with c++? - c++17

[platform] MacOS M1 Max with llvm installed by homebrew
Homebrew clang version 13.0.1.
Target: arm64-apple-darwin21.4.0.
Thread model: posix.
InstalledDir: /opt/homebrew/opt/llvm/bin
xcode-select version 2395.
I do like this:
inline Action * getAction(const string& path)
{
llvm::LLVMContext *llvmcx;
static llvm::LLVMContext MyGlobalContext;
llvmcx = &MyGlobalContext;
string inputPath = path;
vector<const char *> args;
args.push_back(inputPath.c_str());
llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> opt(new clang::DiagnosticOptions());
clang::DiagnosticConsumer *client(new DiagnosticConsumer());
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID(new clang::DiagnosticIDs());
clang::DiagnosticsEngine * Diags = new DiagnosticsEngine(DiagID, opt, client);
// Create the compiler invocation
shared_ptr<clang::CompilerInvocation> CI(new clang::CompilerInvocation());
clang::CompilerInvocation::CreateFromArgs(*CI, args,*Diags);
clang::LangOptions * langOptions = new LangOptions();
langOptions->LangStd = LangStandard::Kind::lang_cxx17;
clang::FileSystemOptions * fileSystemOptions = new FileSystemOptions();
clang::FileManager * fileManager = new FileManager(*fileSystemOptions);
clang::SourceManager * sourceManager = new SourceManager(*Diags,*fileManager);
shared_ptr<HeaderSearchOptions> headerSearchOptions(new clang::HeaderSearchOptions());
headerSearchOptions->ResourceDir = "/opt/homebrew/opt/llvm";
headerSearchOptions->AddPath("/opt/homebrew/opt/llvm/bin/../include/c++/v1", frontend::Angled, false, false);
auto targetOptions = make_shared<clang::TargetOptions>();
targetOptions->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo * targetInfo = clang::TargetInfo::CreateTargetInfo(
*Diags,
targetOptions
);
clang::HeaderSearch headerSearch(
headerSearchOptions,
*sourceManager,
*Diags,
*langOptions,
targetInfo
);
CI->HeaderSearchOpts = headerSearchOptions;
clang::CompilerInstance Clang;
Clang.setInvocation(CI);
Clang.setDiagnostics(Diags);
Clang.setTarget(targetInfo);
Clang.setSourceManager(sourceManager);
Clang.createPreprocessor(clang::TU_Complete);
Clang.getDiagnostics().setClient(new TextDiagnosticPrinter(llvm::errs(), opt.get()));
if (!Clang.hasDiagnostics())
return NULL;
Action *Act = new Action();
if (!Clang.ExecuteAction(*Act))
{
llvm::outs() << Clang.getFrontendOpts().StatsFile;
Clang.getDiagnostics().getClient()->finish();
return NULL;
}
return Act;
}
The parsed file have some includes:
#include<iostream>
#include<vector>
...(some self-defined headers)
but it shows:
In file included from /Users/sl/projs/C++_proj/clion/GAMES101/pa6/Ray.hpp:7:
In file included from /Users/sl/projs/C++_proj/clion/GAMES101/pa6/Vector.hpp:8:
In file included from /opt/homebrew/opt/llvm/bin/../include/c++/v1/iostream:36:
/opt/homebrew/opt/llvm/bin/../include/c++/v1/__config:1151:46: fatal error: cannot open file '/opt/homebrew/opt/llvm/bin/../include/c++/v1/pthread.h': No such file or directory
(defined(__MINGW32__) && __has_include(<pthread.h>))
^
1 error generated.
I've tried to add more different header file to "HearderSearchOptions",but it didn't work,it threw some include error different.
I think it's most likely due to the incorrect setting of headersearchoptions,but I'm not so sure.
How to solve it? :-(

Related

Copy database outside APK

I am trying to copy database from Asset folder , but ufortunetly i've got the errror: System.UnauthorizedAccessException: 'Access to the path "/storage/emulated/0/Northwind.sqlite" is denied.' I added Runtime Permission. Could you tell me what am i doing wrong? Below is my source code:
string dbName = "Northwind.sqlite";
string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName);
// Check if your DB has already been extracted.
if (!File.Exists(dbPath))
{
using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(dbName)))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
{
byte[] buffer = new byte[2048];
int len = 0;
while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write(buffer, 0, len);
}
}
}
}
You could follow the stpes below. It works well on my side.
My database in Assets folder.
Set the Build Action as AndroidAssect.
You could use the following code to copy the file from Assects folder to Android Application folder
// Android application default folder.
var dbFile = GetDefaultFolderPath();
// Check if the file already exists.
if (!File.Exists(dbFile))
{
using (FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write))
{
// Assets is comming from the current context.
await Assets.Open(databaseName).CopyToAsync(writeStream);
}
}
Download the source file from the link below.
https://github.com/damienaicheh/CopyAssetsProject

Absolute path in Magento2

How can I get the absolute path of a media file in Magento2?
I write a function to get the absolute path, but it is not working.
public function getAbsolutePath()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** #var \Magento\Framework\Filesystem $filesystem */
$filesystem = $objectManager->get('Magento\Framework\Filesystem');
/** #var \Magento\Framework\Filesystem\Directory\WriteInterface $mediaDirectory */
$mediaDirectory = $filesystem->getDirectoryWrite(Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$mediaPath = $mediaDirectory->getAbsolutePath();
return $mediaPath;
}
app/autoloader.php
contains:
/**
* Shortcut constant for the root directory
*/
define('BP', dirname(__DIR__));
One could do something like:
$mediaPath = BP.'/pub/media/';
That said, Magento\Framework\Filesystem via dependency injection is my preferred method
You can use to get media and base Absolute path in magento 2 like:
$storeManager = $_objectMedia->get('Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$_baseurl = $storeManager->getStore()->getBaseUrl();
Try it's working fine for me....
/* #var \Magento\Framework\ObjectManagerInterface $om /
$om = \Magento\Framework\App\ObjectManager::getInstance();
$dir = $om->get('Magento\Framework\Filesystem');
$mediadir = $dir->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$path = $mediadir->create('foldername');
try it its working for me..
Relying on the BP isn't a good way to go this, BP should only be used in the low layers in Magento.
Magneto has init config values where the media directory could possibly be outside of the base path. You should rely on the \Magento\Framework\App\Filesystem\DirectoryList object instead.
In the bootstrap you can see:
\Magento\Framework\App\Bootstrap::createFilesystemDirectoryList
class Bootstrap
{
/**
* Creates instance of filesystem directory list
*
* #param string $rootDir
* #param array $initParams
* #return DirectoryList
*/
public static function createFilesystemDirectoryList($rootDir, array $initParams)
{
$customDirs = [];
if (isset($initParams[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS])) {
$customDirs = $initParams[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS];
}
return new DirectoryList($rootDir, $customDirs);
}
}
This means if you set $_SERVER variables during bootstrap:
$tmpDir = '/var/tmpfs_mount';
$applicationDir = '/var/www/html/magento';
$loggingDir = '/var/log/restricted';
$params = $_SERVER;
$filesystemsDirs = $params[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS];
$filesystemsDirs[DirectoryList::CONFIG] = [DirectoryList::PATH => $applicationDir . "/var/cache"];
$filesystemsDirs[DirectoryList::MEDIA] = [DirectoryList::PATH => $tmpDir . "/var/cache"];
$filesystemsDirs[DirectoryList::GENERATED] = [DirectoryList::PATH => $tmpDir . "/generated"];
$filesystemsDirs[DirectoryList::CACHE] = [DirectoryList::PATH => $tmpDir . "/var/cache"];
$filesystemsDirs[DirectoryList::LOG] = [DirectoryList::PATH => $loggingDir . "/var/log"];
$params[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS] = $filesystemsDirs;
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
To do via the object manager, add the DirectoryList object to the constructor:
use \Magento\Framework\App\Filesystem\DirectoryList;
class MyModuleClass
{
/**
* #var DirectoryList
*/
private $directoryList;
/**
* #param DirectoryList $directoryList
*/
public function __construct(DirectoryList $directoryList)
{
$this->directoryList = $directoryList;
}
/**
* #var DirectoryList
*/
private $mediaPath;
public function getMediaAbsolutePath(){
if (!$this->mediaPath){
$this->mediaPath = $this->directoryList->getPath(DirectoryList::MEDIA);
}
return $this->mediaPath;
}
}
Please note this will only get you the path, but it won't validate if via the PathValidator introduced in Magento 2.3. This PathValidator ensures that the path is allowed within the installation, you'll need to validate it yourself
vendor/magento/framework/Filesystem/Directory/PathValidator.php
P.S I haven't tested the code, I've just eye'd it from memory, so if it breaks let me know.
With Object manager:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$directoryList = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');
$media = $directoryList->getPath('media');
With dependency injection:
Use class `\Magento\Framework\App\Filesystem\DirectoryList
protected $_directoryList;
public function __construct(
...
\Magento\Framework\App\Filesystem\DirectoryList $directoryList
...
) {
$this->_directoryList = $directoryList;
}
For Root Folder
$this->_directoryList->getRoot();
For media Folder
$this->_directoryList->getPath('media');
Other Folders
// Get app folder
$this->_directoryList->getPath('app');
// Get etc Folder
$this->_directoryList->getPath('etc');
// Get public folder
$this->_directoryList->getPath('pub');
// Get var folder
$this->_directoryList->getPath('var');
you can use this:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$fileSystem = $om->get('Magento\Framework\Filesystem');
$mediaDirectory = $fileSystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
Use blow code for geting absolute url of an image you have uploaded in product page.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$b_url = $objectManager->get('Magento\Store\Model\StoreManagerInterface')
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
// here product_badge is custom image attribute code, replace it with yours attribute.
$_product = $block->getProduct();
$product_badge = $_product->getResource()->getAttribute('product_badge')->getFrontend()->getValue($_product);
?>
<img src="<?php echo $b_url.'/catalog/product'.$product_badge; ?>" />
$rootDirectory = Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\Filesystem')
->getDirectoryRead(DirectoryList::MEDIA);

How to convert sequence file generated in mahout to text file

I have been looking for parser to convert sequence file(.seq) generated to normal text file to get to know intermediate outputs. I am glad to know if anyone come across how to do this.
I think you can create a SequenceFile Reader in a few lines of codes as below
public static void main(String[] args) throws IOException {
String uri = "path/to/your/sequence/file";
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
Path path = new Path(uri);
SequenceFile.Reader reader = null;
try {
reader = new SequenceFile.Reader(fs, path, conf);
Writable key = (Writable) ReflectionUtils.newInstance(
reader.getKeyClass(), conf);
Writable value = (Writable) ReflectionUtils.newInstance(
reader.getValueClass(), conf);
long position = reader.getPosition();
while (reader.next(key, value)) {
System.out.println("Key: " + key + " value:" + value);
position = reader.getPosition();
}
} finally {
reader.close();
}
}
Suppose you have sequence data in hdfs in /ex-seqdata/part-000...
so the part-* data are in binary format.
now you can run command hadoop fs -text /ex-seqdata/part*
in command prompt to get the data in human readable format.

Printing multiple poscripts in one job

I need to write a Java method in order to send postscript files to a printer in one job. In other words, I need to reproduce the effect of the following Unix command:
lp -d printer file1.ps file2.ps file3.ps
First I thought I could just concatenate the PS files (using classes like ConcatInputStream and PrintJobWatcher). But the resulting merged PS file is not always valid.
If it helps, here is my current code (I have been asked to do it in Groovy):
/**
* Prints the {#code files} {#code copyCount} times using
* {#code printService}.
* <p>
* Exceptions may be thrown.
* #param printService Print service
* #param files Groovy array of {#code File} objects
* #param copyCount Number of copies to print
*/
private static void printJob(
PrintService printService,
def files,
int copyCount) {
// No multiple copy support for PS file, must do it manually
copyCount.times { i ->
InputStream inputStream = null
try {
log.debug("Create stream for copy #${i}")
inputStream = new ConcatInputStream()
for (def file in files) {
if (file != null) {
log.debug("Add '${file.absolutePath}' to the stream")
((ConcatInputStream)inputStream).addInputStream(
new FileInputStream(file))
}
}
log.debug("Create document")
Doc doc = new SimpleDoc(
inputStream, DocFlavor.INPUT_STREAM.AUTOSENSE, null)
log.debug("Create print job")
DocPrintJob docPrintJob = printService.createPrintJob()
log.debug("Create watcher")
PrintJobWatcher watcher = new PrintJobWatcher(docPrintJob)
log.debug("Print copy #${i}")
docPrintJob.print(doc, null)
log.debug("Wait for completion")
watcher.waitForDone()
} finally {
if (inputStream) log.debug("Close the stream")
inputStream?.close()
}
}
}
I’m not allowed to convert the PS into PDF.
I read here that I could insert false 0 startjob pop between the PS files. But then would there be only one job?
I may be confusing the concept of "jobs"...
I didn’t find a post on the topic (sending multiple PS files to the printer in one job). The solution may be so obvious that it blinded me, that why I posted this question.
My next attempt will be to execute lp from the class, even if it looks dirty I know I can make it work that way... If you know a simpler way, please tell me.
Edit:
Executing lp (as below) works well:
/**
* Prints the {#code files} {#code copyCount} times using an executable.
* <p>
* Exceptions may be thrown.
* #param config ConfigObject containing closures for building the
* command line to the printing executable, and to analyze the
* return code. Example of config file:
*
* print {
* commandClosure = { printerName, files ->
* [
* 'lp',
* '-d', printerName,
* files.collect{ it.absolutePath }
* ].flatten()
* }
* errorClosure = { returnCode, stdout, stderr -> returnCode != 0 }
* warnClosure = { returnCode, stdout, stderr ->
* !stderr?.isAllWhitespace() }
* }
*
* #param printerName Printer name
* #param files Groovy array of {#code File} objects
* #param copyCount Number of copies to print
*/
private static void printJob(
ConfigObject config,
String printerName,
def files,
int copyCount) {
files.removeAll([null])
Integer copyCount = job.copyCountString.toInteger()
copyCount.times { i ->
def command = config.print.commandClosure(printerName, files)
log.debug("Command: `" + command.join(' ') + "`")
def proc = command.execute()
proc.waitFor()
def returnCode = proc.exitValue()
def stdout = proc.in.text
def stderr = proc.err.text
def debugString = "`" + command.join(' ') +
"`\nReturn code: " + returnCode +
"\nSTDOUT:\n" + stdout + "\nSTDERR:\n" + stderr
if (config.print.errorClosure(returnCode, stdout, stderr)) {
log.error("Error while calling ${debugString}")
throw new PrintException("Error while calling ${debugString}")
} else if (config.print.warnClosure(returnCode, stdout, stderr)) {
log.warn("Warnings while calling ${debugString}")
} else {
log.debug("Command successful ${debugString}")
}
}
}
Even if I would prefer not to use an external executable... This issue is not anymore critical for me. I will accept an answer if it does not require the call to an external executable.
Actually, can't you just loop through the files inside your loop for the number of copies?
ie:
private static void printJob( PrintService printService, def files, int copyCount) {
// No multiple copy support for PS file, must do it manually
copyCount.times { i ->
log.debug( "Printing Copy $i" )
files.each { file ->
log.debug( "Printing $file" )
file.withInputStream { fis ->
Doc doc = new SimpleDoc( fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null )
DocPrintJob docPrintJob = printService.createPrintJob()
PrintJobWatcher watcher = new PrintJobWatcher( docPrintJob )
docPrintJob.print( doc, null )
watcher.waitForDone()
}
}
}
}
(untested)
edit
As an update to your workaround above, rather than:
def proc = command.execute()
proc.waitFor()
def returnCode = proc.exitValue()
def stdout = proc.in.text
def stderr = proc.err.text
You're probably better with:
def proc = command.execute()
def out = new StringWriter()
def err = new StringWriter()
ps.consumeProcessOutput( out, err )
ps.waitFor()
def returnCode = proc.exitValue()
def stdout = out.toString()
def stderr = err.toString()
As this won't block if the process writes a lot of information :-)
One of the issues could be related to the Document Structure Convention (DSC) comments. These comments provide metadata about the document contained in the file. A tool like ghostscript should be able to process the resulting concatenated file because it ignores DSC comments entirely and just processes the postscript. But tools that expect to work on DSC-conforming files will be confused when the first file ends (it's marked by an End comment) and there's more data in the file.
One thing that might work is to strip all comments from the files, so there's no misleading DSC information. (DSC comments will always be a full line starting with %%, so an RE substitution should do it. s/^%[^$]*$//g)

nicUpload says "Invalid Upload ID", cant make it works

Im trying to implement nicEdit with the nicupload plugin, but when I select a file to upload it says "Failed to upload image", and the server response says "Invalid Upload ID".
This is the code that calls the script and initializes:
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">//<![CDATA[
bkLib.onDomLoaded(function() {
new nicEditor({uploadURI : '../../nicedit/nicUpload.php'}).panelInstance('area1');
});
//]]>
</script>
The path to nicUpload.php is correct, and the code is the one that can be found in the documentation: http://nicedit.com/src/nicUpload/nicUpload.js
I made the upload folder changes, and set write permissions. According to the documentation (http://wiki.nicedit.com/w/page/515/Configuration%20Options), thats all, but i keep getting errors. Any ideas?
After looking for an solution a long time (lot of posts without real solution), i now fixed the code myself. I'm now able to upload an image to my own server. Thx to firebug and eclipse ;-)
The main problem is that the nicUpload.php is old and not working with the current nicEdit-Upload function.
Missing is the error handling, feel free to add this...
Add the nicEditor to your php file and configure it to use the nicEdit.php:
new nicEditor({iconsPath : 'pics/nicEditorIcons.gif', uploadURI : 'script/nicUpload.php'}
Download the nicEdit.js uncompressed and change the following lines in nicEdit.js:
uploadFile : function() {
var file = this.fileInput.files[0];
if (!file || !file.type.match(/image.*/)) {
this.onError("Only image files can be uploaded");
return;
}
this.fileInput.setStyle({ display: 'none' });
this.setProgress(0);
var fd = new FormData();
fd.append("image", file);
fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660");
var xhr = new XMLHttpRequest();
xhr.open("POST", this.ne.options.uploadURI || this.nicURI);
xhr.onload = function() {
try {
var res = JSON.parse(xhr.responseText);
} catch(e) {
return this.onError();
}
//this.onUploaded(res.upload); // CHANGE HERE
this.onUploaded(res);
}.closure(this);
xhr.onerror = this.onError.closure(this);
xhr.upload.onprogress = function(e) {
this.setProgress(e.loaded / e.total);
}.closure(this);
xhr.send(fd);
},
onUploaded : function(options) {
this.removePane();
//var src = options.links.original; // CHANGE HERE
var src = options['url'];
if(!this.im) {
this.ne.selectedInstance.restoreRng();
//var tmp = 'javascript:nicImTemp();';
this.ne.nicCommand("insertImage", src);
this.im = this.findElm('IMG','src', src);
}
var w = parseInt(this.ne.selectedInstance.elm.getStyle('width'));
if(this.im) {
this.im.setAttributes({
src : src,
width : (w && options.image.width) ? Math.min(w, options.image.width) : ''
});
}
}
Change the nicUpload.php like this
<?php
/* NicEdit - Micro Inline WYSIWYG
* Copyright 2007-2009 Brian Kirchoff
*
* NicEdit is distributed under the terms of the MIT license
* For more information visit http://nicedit.com/
* Do not remove this copyright message
*
* nicUpload Reciever Script PHP Edition
* #description: Save images uploaded for a users computer to a directory, and
* return the URL of the image to the client for use in nicEdit
* #author: Brian Kirchoff <briankircho#gmail.com>
* #sponsored by: DotConcepts (http://www.dotconcepts.net)
* #version: 0.9.0
*/
/*
* #author: Christoph Pahre
* #version: 0.1
* #description: different modification, so that this php file is working with the newest nicEdit.js (needs also modification - #see)
* #see http://stackoverflow.com/questions/11677128/nicupload-says-invalid-upload-id-cant-make-it-works
*/
define('NICUPLOAD_PATH', '../images/uploadedImages'); // Set the path (relative or absolute) to
// the directory to save image files
define('NICUPLOAD_URI', '../images/uploadedImages'); // Set the URL (relative or absolute) to
// the directory defined above
$nicupload_allowed_extensions = array('jpg','jpeg','png','gif','bmp');
if(!function_exists('json_encode')) {
die('{"error" : "Image upload host does not have the required dependicies (json_encode/decode)"}');
}
if($_SERVER['REQUEST_METHOD']=='POST') { // Upload is complete
$file = $_FILES['image'];
$image = $file['tmp_name'];
$id = $file['name'];
$max_upload_size = ini_max_upload_size();
if(!$file) {
nicupload_error('Must be less than '.bytes_to_readable($max_upload_size));
}
$ext = strtolower(substr(strrchr($file['name'], '.'), 1));
#$size = getimagesize($image);
if(!$size || !in_array($ext, $nicupload_allowed_extensions)) {
nicupload_error('Invalid image file, must be a valid image less than '.bytes_to_readable($max_upload_size));
}
$filename = $id;
$path = NICUPLOAD_PATH.'/'.$filename;
if(!move_uploaded_file($image, $path)) {
nicupload_error('Server error, failed to move file');
}
$status = array();
$status['done'] = 1;
$status['width'] = $size[0];
$rp = realpath($path);
$status['url'] = NICUPLOAD_URI ."/".$id;
nicupload_output($status, false);
exit;
}
// UTILITY FUNCTIONS
function nicupload_error($msg) {
echo nicupload_output(array('error' => $msg));
}
function nicupload_output($status, $showLoadingMsg = false) {
$script = json_encode($status);
$script = str_replace("\\/", '/', $script);
echo $script;
exit;
}
function ini_max_upload_size() {
$post_size = ini_get('post_max_size');
$upload_size = ini_get('upload_max_filesize');
if(!$post_size) $post_size = '8M';
if(!$upload_size) $upload_size = '2M';
return min( ini_bytes_from_string($post_size), ini_bytes_from_string($upload_size) );
}
function ini_bytes_from_string($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
function bytes_to_readable( $bytes ) {
if ($bytes<=0)
return '0 Byte';
$convention=1000; //[1000->10^x|1024->2^x]
$s=array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB');
$e=floor(log($bytes,$convention));
return round($bytes/pow($convention,$e),2).' '.$s[$e];
}
?>
You can manually pass an id to your script: e.g nicUpload.php?id=introPicHeader and it will become introPicHeader.jpg (or appropriate extension) in the images folder you defined.
However, I have noticed that this script is broken and cannot access the configuration option uploadURI if specified directly in nicEdit.js during the nicEditorAdvancedButton.extend({. This causes access to an relatively pathed "Unknown" resource, causing an error.
The documentation implies otherwise and the fact that the nicURI was specified here for imgur.com (maybe as a default) gave me the impression I could also add a uploadURI reference to the nicUpload.php script in a single place rather than on every editor instantiation.
Update
This works if you pass it during instantiation, which I guess does allow for easy dynamic id population.
Unfortunately, the nicUpload.php is riddled with errors and it's output is not JSON. The editor expects to parse JSON and finds a script tag and errors with unexpected token "<".
There are a raft of other errors which I will attempt to identify:
In nicEdit.js
A.append("image") should be infact A.append("nicImage")
this.onUploaded(D.upload) should become this.onUploaded(D)
this.onUploaded(D) should be moved to within the try block after var D=JSON.parse(C.responseText) to fix variable scope issues
B.image.width needs to become B.width
In nicUpload.php
JSON output is not formed correctly, comment out html output and output just json_encode($status).
JSON output needs to return a key/value pair named links rather than url although renaming the var D=B.links to var D=B.url in nicEdit.js would also suffice as a fix.
Both php and javascript code leaves a lot to be desired, I get many errors regularly and have been fixing them myself.

Resources