I have URL's like this:
/path1/path2/path3/path4/path5/96_6.txt
/path1/path2/path3/path4/path5/96_7.txt?blah=1
So far I am doing the following to obtain the file on the end of my URL:
local request_uri = "/path1/path2/path3/path4/path5/96_645.txt?lol=1"
local name = request_uri:match( "([^/]+)$" )
local filename = string.gsub(name, "?.*", "")
print(name)
print(filename)
What outputs:
96_645.txt?lol=1
96_645.txt
What I want to do is to remove path2 and path3 from my URL. The issue is they are dynamic folder paths and can contain characters.
What is the best solution for this?
Try this one:
function fix_url(p)
p, _ = string.gsub(p, '^/([^/]+)/[^/]+/[^/]+/(.*)', '/%1/%2')
return p
end
Here are some tests:
p = fix_url('/path1/path2/path3/path4/path5/96_6.txt')
assert(p == '/path1/path4/path5/96_6.txt')
p = fix_url('/path1/path2/path3/path4/path5/96_7.txt?blah=1')
assert(p == '/path1/path4/path5/96_7.txt?blah=1')
p = fix_url('/path1/foo.txt')
assert(p == '/path1/foo.txt')
Related
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.
How to resolved error or possible ways to resolved it?
Guys, i've developed plugin using Lua language which can be integrate or run from Adobe's LightRoom Classic. Currently i need to upload or send a file to server but i can not. Everytime i called the POST API which is multipart/form-data error popup "?:0: attempt to perform arithmetic on field 'fileSize' (a nil value)". Not even API is being called this error pops up before API call. after debug I can assure the possible issue is in creating mimeChunks with file type.
I have developed the code like below, can any one help me out with suggestions so that i can able to resolved issue?
local filePath = assert("C:\Users\Ankit\Desktop\Hangman.PNG")
local fileName = LrPathUtils.leafName(filePath)
local mimeChunks = {}
mimeChunks[#mimeChunks + 1] = {
name = 'api_sig',
value = "test value"
}
mimeChunks[#mimeChunks + 1] = {
name = "file",
filePath = filePath,
fileName = fileName,
contentType = "application/octet-stream"
}
local postUrl = "API endpoint"
local result, hdrs = LrHttp.postMultipart(postUrl, mimeChunks)
if result then
LrDialogs.message("Form Values", result)
else
LrDialogs.message("Form Values", "API issue")
end
Eventually image or file path itself cause the issue, there are no such indications or articles related to this functionality, but yes "add-on backslash" will work out for sure. Kindly review the below code for more detailed bifurcation which pass dynamic selected file or image path.
local function uploadFile(filePath)
local fileName = LrPathUtils.leafName( filePath )
local mimeChunks = {}
mimeChunks[ #mimeChunks + 1 ] = { name = 'api_sig', value = "test value"}
mimeChunks[#mimeChunks + 1] = {
name = "file",
filePath = filePath,
fileName = fileName,
contentType = "image/jpeg" --multipart/form-data --application/octet-stream
}
import "LrTasks".startAsyncTask(
function()
local postUrl = "http://cms.local.com/api/v1/upload"
local result, hdrs = LrHttp.postMultipart(postUrl, mimeChunks)
if result then
LrDialogs.message("Image uploaded.", result)
else
LrDialogs.message("Error", "API issue")
end
end
)
end
Above uploadFile method will automatically call the API and post form-data collection. Below code is for call uploadFile function which select all the images from catalog.
for p, photo in ipairs(LrApplication.activeCatalog()) do
uploadFile(assert(photo:getRawMetadata('path')));
end
Above code will help you out the selection of categlog with Adobe's LightRoom Plugin.
I want to replace % signs with a $. I tried doing an escape character () but that didn't work. I am using lua 5.1 and I get a malformed pattern error. (ends in '%') This is bugging me because I don't know how to fix it.
io.write("Search: ") search = io.read()
local query = search:gsub("%", "%25") -- Where I put the % sign.
query = query:gsub("+", "%2B")
query = query:gsub(" ","+")
query = query:gsub("/", "%2F")
query = query:gsub("#", "%23")
query = query:gsub("$", "%24")
query = query:gsub("#", "%40")
query = query:gsub("?", "%3F")
query = query:gsub("{", "%7B")
query = query:gsub("}","%7D")
query = query:gsub("[","%5B")
query = query:gsub("]","%5D")
query = query:gsub(">", "%3E")
query = query:gsub("<", "%3C")
local url = "https://www.google.com/#q=" .. query
print(url)
Output reads:
malformed pattern (ends with '%')
You need to escape % and write %%.
The idiomatic what to do this in Lua is to give a table to gsub:
local reserved="%+/#$#?{}[]><"
local escape={}
for c in reserved:gmatch(".") do
escape[c]=string.format("%%%02X",c:byte())
end
escape[" "]="+"
query = search:gsub(".", escape)
How do you get the last index of a character in a string in Lua?
"/some/path/to/some/file.txt"
How do I get the index of the last / in the above string?
index = string.find(your_string, "/[^/]*$")
(Basically, find the position where the pattern "a forward slash, then zero or more things that aren't a forward slash, then the end of the string" occurs.)
This method is a bit more faster (it searches from the end of the string):
index = your_string:match'^.*()/'
Loops?!? Why would you need a loop for that? There's a 'reverse' native string function mind you, just apply it then get the first instance :) Follows a sample, to get the extension from a complete path:
function fileExtension(path)
local lastdotpos = (path:reverse()):find("%.")
return (path:sub(1 - lastdotpos))
end
You can do it in a single line of course, I split it in two for legibility's sake.
Here is a complete solution.
local function basename(path)
return path:sub(path:find("/[^/]*$") + 1)
end
local s = "/aa/bb/cc/dd/ee.txt"
local sep = "/"
local lastIndex = nil
local p = string.find(s, sep, 1)
lastIndex = p
while p do
p = string.find(s, sep, p + 1)
if p then
lastIndex = p
end
end
print(lastIndex)
You could continue find next value, until find nil,record last position
There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it.
In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts.
http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123
should parse into:
netloc = 'www.somesite.com'
baseURL = 'base'
path = '/first/second/third/fourth/'
file = 'foo.html?abc=123'
The code below produces the correct result, but is there are better way to do this in Python?
url = "http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123"
file= url.rpartition('/')[2]
netloc = urlparse(url)[1]
pathParts = path.split('/')
baseURL = pathParts[1]
partCount = len(pathParts) - 1
path = "/"
for i in range(2, partCount):
path += pathParts[i] + "/"
print 'baseURL= ' + baseURL
print 'path= ' + path
print 'file= ' + file
print 'netloc= ' + netloc
Since your requirements on what parts you want are different from what urlparse gives you, that's as good as it's going to get. You could, however, replace this:
partCount = len(pathParts) - 1
path = "/"
for i in range(2, partCount):
path += pathParts[i] + "/"
With this:
path = '/'.join(pathParts[2:-1])
I'd be inclined to start out with urlparse. Also, you can use rsplit, and the maxsplit parameter of split and rsplit to simplify things a bit:
_, netloc, path, _, q, _ = urlparse(url)
_, base, path = path.split('/', 2) # 1st component will always be empty
path, file = path.rsplit('/', 1)
if q: file += '?' + q