Naming convention for variables containing file path or its parts - path

What are standard or most self-descripting variable names for variables with following values? (Consider them from perspective of File.Ext)
// Windows environment
var0 = "C:\Folder_A\Folder_B\Folder_C\File.Ext"
var1 = "C:\"
var2 = "C:\Folder_A\"
var3 = "C:\Folder_A\Folder_B\"
var4 = "C:\Folder_A\Folder_B\Folder_C\"
var5 = "File"
var6 = "Ext"
var7 = ".Ext"
This is what comes to my unexperienced mind:
FullPath
Drive
???
???
ParentFolderPath
Filename
Extension
FullExtension
Also what is Windows standard or best practice for storing folder paths - with or without the last \?
Same for extension - with or without .?

filePath = "C:\Folder_A\Folder_B\Folder_C\File.Ext"
rootDirectory = "C:\"
directoryPath = "C:\Folder_A\"
anotherDirectoryPath = "C:\Folder_A\Folder_B\"
aThirdDirectoryPath = "C:\Folder_A\Folder_B\Folder_C\"
filenameSansSuffix = "File"
fileSuffix = "Ext"
anotherDefinitionOfFileSuffix = ".Ext"
It is more natural to define directory paths without a trailing backslash.
When it comes to file extensions I usually include the dot. Also, in Windows Batch scripting, for instance, the modifier ~x results in the file extension including the dot (when i tried it).
%~xI Expands %I to a file name extension only.
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/for

Related

How can you use the FILEOPEN in BBj to create a Filedialog?

In the Documentation it is stated like this:
'FILEOPEN'(prompt,path,name,ext[,filters[,mode]])
But what parameters do you need to use to be able to display the dialog?
Any samples?
Parameters are documented in this page
Parameter
Description
prompt
Text to display in the title bar of the dialog.
path
Default directory for the file to be opened in the dialog.
name
Default name for the file to be opened in the dialog. Use the empty string ("") to avoid setting a default filename.
ext
Default extension (usually 3 characters, do not include the dot) for the file to be opened in the dialog. Use the empty string ("") to avoid setting a default extension.
filters
One or more filters in the following format: "text description" + $0a$ + "mask" [+$0a$ + "text description" + $0a$ + "mask" ...] The mask specifies an extension, in the format ".ext" or "."; two or more masks are separated with semicolons. The filter, if included, indicates which files will appear in the list. For example: REM Illustrate the use of the FILEOPEN() function REM Build filters for brc/arc and all files FILTER$="Binary Resource Files"+$0a$+".brc;.brf" FILTER$=FILTER$+$0a$+"ASCII Resource Files"+$0a$+".arc" FILTER$=FILTER$+$0a$+"All Files (.)"+$0a$+"." REM Starting directory is the default Directory FILE_DIR$="" REM Use FILEOPEN() to get name of file to open FILE_NAME$=FILEOPEN("Open Resource File",FILE_DIR$,"","",FILTER$) REM display file name returned PRINT FILE_NAME$
rem ' clientfile.txt
precision 6
tc! = bbjapi().getThinClient()
fs! = tc!.getClientFileSystem()
filter$ = ""
filter$ = filter$ + "Text Files (*.txt)"+$0a$+"*.txt"+$0a$
filter$ = filter$ + "HTML Files (*.htm;*.html)"+$0a$+"*.htm;*.html"+$0a$
filter$ = filter$ + "Image Files (*.png;*.jpg;*.bmp;*.gif)"+$0a$+"*.png;*.jpg;*.bmp;*.gif"+$0a$
filter$ = filter$ + "All Files (*.*)"+$0a$+"*.*"+$0a$
i = msgbox("Test client fileopen + copy file from client to server")
clientfile$ = fileopen("Pick a client file","","","",filter$,mode="client")
i = msgbox(clientfile$,0,"Selected client file")
if pos("::"=clientfile$) then goto eoj
cf! = fs!.getClientFile(clientfile$)
i = msgbox("Copy "+clientfile$+" to the server")
t = tim
serverfile$ = cf!.copyFromClient()
t = tim - t
t = t * 3600
serverfile = unt
open (serverfile)serverfile$
serverfile$ = fid(serverfile)(9)
bytes = dec(fin(serverfile)(1,4))
close (serverfile)
i = msgbox("Copied client file "+clientfile$+" to server file "+serverfile$+" ("+str(bytes)+" bytes; "+str(t)+" seconds)",0,"Copied from client to server")
i = msgbox("Test server fileopen + copy file from server to client")
serverfile$ = fileopen("Pick a server file","","","",filter$)
i = msgbox(serverfile$,0,"Selected server file")
if pos("::"=serverfile$) then goto eoj
clientfile! = new java.io.File(serverfile$)
clientfile$ = clientfile!.getName()
clientfile$ = filesave("Save to client","",clientfile$,"",filter$,mode="client")
if pos("::"=clientfile$) then goto eoj
i = msgbox("Copy server file "+serverfile$+" to client file "+clientfile$)
cf! = fs!.getClientFile(clientfile$)
cf!.copyToClient(serverfile$)
i = msgbox("Copied server file "+serverfile$+" to client file "+clientfile$,0,"Copied from server to client")
eoj:
release

How do I use more then one pattern for gmatch

Hello I am trying to get some data from a text file and put it into a table.
Im not sure how to add more then one pattern while also doing what I want, I know this pattern by its self %a+ finds letters and %b{} finds brackets, but I am not sure how to combine them together so that I find the letters as a key and the brackets as a value and have them be put into a table that I could use.
text file :
left = {{0,63},{16,63},{32,63},{48,63}}
right = {{0,21},{16,21},{32,21},{48,21}}
up = {{0,42},{16,42},{32,42},{48,42}}
down = {{0,0},{16,0},{32,0},{48,0}}
code:
local function get_animations(file_path)
local animation_table = {}
local file = io.open(file_path,"r")
local contents = file:read("*a")
for k, v in string.gmatch(contents, ("(%a+)=(%b{})")) do -- A gets words and %b{} finds brackets
animation_table[k] = v
print("key : " .. k.. " Value : ".. v)
end
file:close()
end
get_animations("Sprites/Player/MainPlayer.txt")
This is valid Lua code, why not simply execute it?
left = {{0,63},{16,63},{32,63},{48,63}}
right = {{0,21},{16,21},{32,21},{48,21}}
up = {{0,42},{16,42},{32,42},{48,42}}
down = {{0,0},{16,0},{32,0},{48,0}}
If you don't want the data in globals, use the string library to turn it into
return {
left = {{0,63},{16,63},{32,63},{48,63}},
right = {{0,21},{16,21},{32,21},{48,21}},
up = {{0,42},{16,42},{32,42},{48,42}},
down = {{0,0},{16,0},{32,0},{48,0}},
}
befor you execute it.
If you insist on parsing that file you can use a something like this for each line:
local line = "left = {{0,63},{16,63},{32,63},{48,63}}"
print(line:match("^%w+"))
for num1, num2 in a:gmatch("(%d+),(%d+)") do
print(num1, num2)
end
This should be enough to get you started. Of course you wouldn't print those values but put them into a table.

Filter source files for custom rule

I used a bazel macro to run a python test on a subset of source files. Similar to this:
def report(name, srcs):
source_labels = [file for file in srcs if file.startswith("a")]
if len(source_labels) == 0:
return;
source_filenames = ["$(location %s)" % x for x in source_labels]
native.py_test(
name = name + "_report",
srcs = ["report_tool"],
data = source_labels,
main = "report_tool.py",
args = source_filenames,
)
report("foo", ["foo.hpp", "afoo.hpp"])
This worked fine until one of my source files started using a select and now I get the error:
File "/home/david/foo/report.bzl", line 47, in report
[file for file in srcs if file.startswith("a")]
type 'select' is not iterable
I tried to move the code to a bazel rule, but then I get a different error that py_test can not be used in the analysis phase.
The reason that the select is causing the error is that macros are evaluated during the loading phase, whereas selectss are not evaluated until the analysis phase (see Extension Overview).
Similarly, py_test can't be used in a rule implementation because the rule implementation is evaluated in the analysis phase, whereas the py_test would need to have been loaded in the loading phase.
One way past this is to create a separate Starlark rule that takes a list of labels and just creates a file with each filename from the label. Then the py_test takes that file as data and loads the other files from there. Something like this:
def report(name, srcs):
file_locations_label = "_" + name + "_file_locations"
_generate_file_locations(
name = file_locations_label,
labels = srcs
)
native.py_test(
name = name + "_report",
srcs = ["report_tool.py"],
data = srcs + [file_locations_label],
main = "report_tool.py",
args = ["$(location %s)" % file_locations_label]
)
def _generate_file_locations_impl(ctx):
paths = []
for l in ctx.attr.labels:
f = l.files.to_list()[0]
if f.basename.startswith("a"):
paths.append(f.short_path)
ctx.actions.write(ctx.outputs.file_paths, "\n".join(paths))
return DefaultInfo(runfiles = ctx.runfiles(files = [ctx.outputs.file_paths]))
_generate_file_locations = rule(
implementation = _generate_file_locations_impl,
attrs = { "labels": attr.label_list(allow_files = True) },
outputs = { "file_paths": "%{name}_files" },
)
This has one disadvantage: Because the py_test has to depend on all the sources, the py_test will get rerun even if the only files that have changed are the ignored files. (If this is a significant drawback, then there is at least one way around this, which is to have _generate_file_locations filter the files too, and have the py_test depend on only _generate_file_locations. This could maybe be accomplished through runfiles symlinks)
Update:
Since the test report tool comes from an external repository and can't be easily modified, here's another approach that might work better. Rather than create a rule that creates a params file (a file containing the paths to process) as above, the Starlark rule can itself be a test rule that uses the report tool as the test executable:
def _report_test_impl(ctx):
filtered_srcs = []
for f in ctx.attr.srcs:
f = f.files.to_list()[0]
if f.basename.startswith("a"):
filtered_srcs.append(f)
report_tool = ctx.attr._report_test_tool
ctx.actions.write(
output = ctx.outputs.executable,
content = "{report_tool} {paths}".format(
report_tool = report_tool.files_to_run.executable.short_path,
paths = " ".join([f.short_path for f in filtered_srcs]))
)
runfiles = ctx.runfiles(files = filtered_srcs).merge(
report_tool.default_runfiles)
return DefaultInfo(runfiles = runfiles)
report_test = rule(
implementation = _report_test_impl,
attrs = {
"srcs": attr.label_list(allow_files = True),
"_report_test_tool": attr.label(default="//:report_test_tool"),
},
test = True,
)
This requires that the test report tool be a py_binary somewhere so that the test rule above can depend on it:
py_binary(
name = "report_test_tool",
srcs = ["report_tool.py"],
main = "report_tool.py",
)

Reading File Path to a Variable

I want to use the variable that I passed to a function which contains a file path. However, I don't get it working.
For example, I have a path like "/samba-test/log_gen/log_gen/log_generator" and when I read this path to a variable it doesn't work as expected. Please refer to my explaination in the code. My comments
are tagged with the string "VENK" . Any help would be appreciated.
/* caller */
config_path = "/samba-test/log_gen/log_gen/log_generator"
ReadWrite_Config(config_path)
/*definition*/
def ReadWrite_Timeline(lp_readpath, lp_filterlist):
current_parent_path = lp_readpath
current_search_list = lp_filterlist
print(current_parent_path) >>>>>> VENK - PATH prints fine here as expected <<<<<<<<.
strings_1 = ("2e88422c-4b61-41d7-9cf9-4650edaa4e56", "2017-11-27 16:1")
for index in range(0,3):
print (current_search_list[index])
files=None
filext=[".txt",".log"]
#outputfile = open(wrsReportFileName, "a")
for ext in filext:
print("Current_Parent_Path",current_parent_path ) <<<<<<VENK - Prints as Expected ""
#VENK - The above line prints as ('Current_Parent_Path', '/samba-test/log_gen/log_gen/log_generator') which is expected
#The actual files are inside the 'varlog' where the 'varlog' folder is inside '/samba-test/log_gen/log_gen/log_generator'
#possible problematic line below.
varlogpath = "(current_parent_path/varlog)/*"+ext >>>>>>>>>>> VENK- Unable to find the files if given in this format <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
print("varlogpath",varlogpath) >>>>>>>>>>>> VENK- varlogpath doesn't print as expected <<<<<<<<<<<<<<<<<<<<
#VENK - The above line prints as ('varlogpath', 'current_parent_path/varlog/*.txt') which I feel is problematic.
#VENK - If I give the absolute path as below it works fine
#varlogpath = "/samba-test/log_gen/log_gen/log_generator/varlog/*"+ext
files = glob.glob(varlogpath)
for file in files:
fname_varlog = open(file, 'r')
outputfile.write("\n")
outputfile.write(file)
outputfile.write("\n")
for line in fname_varlog:
#if any(s in line for s in strings):
"""
#s1 searches the mandatory arguments
#s2 searches the optional arguments
"""
if all(s1 in line for s1 in strings_1):
#if all(s1 in line for s1 in strings_1) or all(s2 in line for s2 in strings_2):
#print (file, end="")
outputfile.write(line)
fname_varlog.close()
outputfile.write("\n")
outputfile.write("10.[##### Summary of the Issue #####] -- Enter Data Manually \n")
outputfile.write("\n")
outputfile.close()
#print (ext)
A path join to the variable 'current_parent_path' helped to resolve the problem (like below).
varlogpath = os.path.join(current_parent_path, "*"+ext)

Count images in Folder using ASP.net

I want to count the number of images a folder folder, but it produces this error :
Could not find a part of the path 'c:\Content\slideshow\images\image\'.
All of the images are in a folder in the project. Located a Content/slideshow/images/image
This is my code:
<%
string dir = #"/Content/slideshow/images/image";
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dir);
numFiles = files.Length;
Response.Write("num ber of images :" + numFiles);
%>
"Could not find a part of the path
'c:\Content\slideshow\images\image\'"
Means very simply that the folder does not exist. If you want to user a relative path you can do the following.
Server.MapPath("~/{RelativePathHere})
Edit : In response to your comment. You will need to loop through the file and check for file extension of each (Keeping your own count)
Use HttpContext.Current.Server.MapPath to map the virtual path to physical path and then pass it to Directory.GetFiles method
To call Directory.GetFiles() you need to pass the full path to the images directory.
string dirPath = #"~/Content/slideshow/images/image";
string dirFullPath = Server.MapPath(dirPath);
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
Response.Write("number of images: " + numFiles);
Server.MapPath returns the entire physical file path associated to the dirPath virtual path.
You need to pass this as a relative path using Server.MapPath
Then I would suggest using DirectoryInfo.GetFiles instead of Directory.GetFiles and filter on the image types that you want, so you don't count non-image files. This will yield a FileInfo[].
<%
string dir = Server.MapPath(#"/Content/slideshow/images/image");
FileInfo[] files;
int numFiles;
files = (new System.IO.DirectoryInfo(dir)).GetFiles("filePattern");
numFiles = files.Length;
Response.Write("num ber of images :" + numFiles);
%>
If you have multiple file types that you want to count the best way to do this is just to remove the pattern then filter the results.
var extensions = new String[] {"jpg", "png", "gif"};
files = (new System.IO.DirectInfo(dir)).GetFiles();
foreach(var extension in extensions)
{
numFiles += files.AsEnumerable.Where(f => f.Extension.Equals(extension));
}
int numberOfFiles ;
string path = "C:/PIC";
numberOfFiles = System.IO.Directory.GetFiles(path).Length;
Check Now

Resources