Relative paths for portable notebooks in mathematica - windows

I Cannot find how to use relative paths in mathematica. My directory structure is simple.
Import["G:\\Research\\Acc and Vel Runs\\5-24\\Mathematica\\Data\\250 \
Acc.xls"][[1]] // TableForm
That Demonstrates the Absolute path by using the insert path from the menus. I want this notebook to be portable. I want to give someone the "Mathematica" directory and I want them to be able to run the code. I don't want the paths to break because It will be run on a different machine. Basically I just want to use a relative path starting at the Mathematica level shown above.

In Mathematica you can get the current directory using Directory[] and you can set it to something else using SetDirectory[]. You can go back to the last location using ReserDirectory[] or check all previous locations using DirectoryStack[].
This is described in the documentation here.
You can set the current directory to the directory where the notebook is using
SetDirectory[NotebookDirectory[]]
For NotebookDirectory to work, you must be using the Front End and the notebook must be saved.
You can always use path relative to the current directory (Directory[]), for example Import["data/somedata.txt"].
Regarding directory separators: / will always works, on all of Windows/Linux/Mac. When you are typing a relative path name, it's much more convenient to just use / for portability than FileNameJoin.

I usually do this.
SetDirectory[
FileNameJoin[{$InitialDirectory, "dir1", "dir2"}]];
Quiet[Close["Log.txt"]];
logStream = Quiet[OpenWrite["xmlAreaTagsLog.txt"]];
xmlDoc = Import["XmlData.xml"];
Using $InitialDirectory gets you the .nb directory and using FileNameJoin allows you to have relative access.

Related

Server.Execute with a fixed path

I am trying to implement server.execute() via an include from a virtual functions library (<!-- #include virtual="lib/functions.asp"-->) that I can call on from any subfolder in the system. I am trying to implement a new function that should exist on all pages in our system, and it would be virtually unfeasible to go in and add it manually to every single page. And I need it to be implemented in such a way that it does not interfere with the code on any page which is why I am doing it as a server.execute() in a virtual lib that I know already exists everywhere in the system.
For example:
'location of routine.asp = https://example.com/admin/routine/routine.asp
Server.Execute("routine/routine.asp")
'Will work if I add the virtual lib from an ASP-page in the admin subfolder, but not if I call it from another subfolder
Server.Execute("https://example.com/admin/routine/routine.asp")
'Does not work, because server.execute can't handle that kind of fixed path
The documentation clearly states that colons and double-slashes are not allowed, but I can't figure out how I can make sure the execution of the file happens no matter where in the system it's called from.
Question: How can I make server.execute(path)'s path handle a fixed path, or change the path dynamically to make sure I can always target the file correctly?
If you want to use an absolute path make sure you are using an absolute path (full path from the root).
Think you simply need to specify the absolute path explicitly;
Server.Execute("/admin/routine/routine.asp")

How to load an image in MATLAB without typing the whole path

I'm using imread yo read a file, but it requires the whole path
I=imread('E:\backup\Image Analysis\test_images\barbara.png');
I just want to type
I= imread('barbara.png');
How can I do that?
Make sure barbara.png is on your current search path, i.e. use the file-navigation bar to navigate to E:\backup\Image Analysis\test_images\, thus making it your search path.
Alternatively use addpath to add it to your search directories:
addpath('E:\backup\Image Analysis\test_images')

how to reference a relative file from code and tests

I need to reference patients.json from patients.go, here's the folder structure:
If I do:
filepath.Abs("../../conf/patients.json")
it works for go test ./... but fails for revel run
If I do:
filepath.Abs("conf/patients.json")
the exact opposite happens (revel is fine but tests fail).
Is there a way to correctly reference the file so that it works both for tests and normal program run?
Relative paths are always interpreted / resolved to a base path: the current or working directory - therefore it will always have its limitations.
If you can live with always taking care of the proper working directory, you may keep using relative paths.
What I would suggest is to not rely on the working directory, but an explicitly specified base path. This may have a default value hard-coded in your application (which may be the working directory as well), and you should provide several ways to override its value.
Recommended ways to override the base path to which your "relative" paths are resolved against:
Command line flag (see flag package)
Environment variable (see os.Getenv())
(Fix named) Config file in user's home directory (see os/user/User and os/user/Current())
Once you have the base path, you can get the full path by joining the base path and the relative path. You may use path.Join() or filepath.Join(), e.g.:
// Get base path, from any or from the combination of the above mentioned solutions
base := "/var/myapp"
// Relative path, resource to read/write from:
relf := "conf/patients.json"
// Full path that identifies the resource:
full := filepath.Join(base, relf) // full will be "/var/myapp/conf/patients.json"
I've never used Revel myself but the following looks helpful to me:
http://revel.github.io/docs/godoc/revel.html
revel.BasePath
revel.AppPath
This is not the problem with path, but the problem with your design.
You should design your code more careful.
As far as I can tell, you share same path in your test file and reveal run. I guess that maybe you hard code your json path in your model package which is not suggested.
Better way is
model package get json path from global config, or init model with json path like model := NewModel(config_path). so reveal run can init model with any json you want.
hard code "../../conf/patients.json" in your xxxx_testing.go

Given two directory names, how can I get relative name of one as if another is working dir in Ruby?

In my Rails application, I need to create a symlink between two files inside RAILS_ROOT. The names of target and symlink are given as absolute paths. However, I want to create a symlink that uses relative paths, so the application folder could easily be moved.
In other words, from RAILS_ROOT/path/foo/bar and RAILS_ROOT/path/baz I want to get ../../baz as an answer.
Is there a library function (or a simple one-liner) to do that?
Try the relative_path_from method of a Pathname.

Getting started with Mathematica packages

Can someone offer some advice on how to get started with mathematica packages?
I can save the following in a file named "Foo.m". When I run the input cell in that file, I can see the effects reflected in $ContextPath variable.
BeginPackage["Foo`"]
bar::usage = "barfunction";
Begin["`private`"]
bar[w_] := w;
End[];
EndPackage[];
However, in my notebook I have the following:
#include<foo>
SetDirectory[ToFileName[{$HomeDirectory, "My Documents", "mathematica"}]];
Needs["Foo`"]
$ContextPath
But the needs call is failing for some reason, and the $ContextPath remains unchanged.
Edit
I believe that I've got a partial solution working now, the cell in my file wasn't marked as an initialization cell - and whilst I can now <<Foo', Needs["Foo"]` still isn't working correctly.
Check to make sure the saved file, "Foo.m", is on your $Path, which tells Mathematica which directories to look in when trying to load packages, much like the PATH environment variable in Unix or Windows.
EDIT: $ContextPath won't be changed unless there's an actual BeginPackage statement (or you manipulate it directly using Set or Block or something).
EDIT the second: One thing to check is what
FileNames["Foo.m", $Path]
returns. What you're describing does sound a little strange, though.
Either form should work. When a file is loaded using Get (or <<) or Needs, the directory on the top of the DirectoryStack[] is searched first, and then the $Path is searched. (SetDirectory does not change $Path, so FileNames["Foo.m", $Path]won't find Foo.m.) However, FindFile by default searches Directory[] and $Path. You can test it by doing the following:
FindFile["Foo`"]
SetDirectory[<Foo dir>]
FindFile["Foo`"]
it should return
$Failed
<Foo dir>
<Foo dir>/foo.m
If FindFile can find Foo.m then Needs should be able to find it. In general, I put my packages in $UserBaseDirectory/Applications, and Needs picks them up just fine.

Resources