Parse url query parameters in C glib? - c

Is it possible to get URL fragment parameters in C under glib ?
I've got a url like file://localhost/home/me/notepad.txt#line=100,2
What's the best way to get the parameters specified at the end of the url ?

There’s no single GLib function which will do what you want. If you can use libsoup (also part of the GNOME stack), then you can do it using SoupURI:
g_autoptr(SoupURI) uri = soup_uri_new (uri_string);
const gchar *fragment = soup_uri_get_fragment (uri);
That will set fragment to line=100,2. You’ll have to do further parsing of whatever your fragment format is, by hand. g_strsplit() would be useful for that.

You may also take a look on the function parse_sftp_uri from gnome-terminal terminal-nautilus.c file.
It can be easily adapted for general URIs.

Unsure if you mean to parse notepad.txt#line=100,2 or #line=100,2, nevertheless my answer should work in both cases.
You can use the strrchr() (man strrchr) function to get the last occurence of a character within a string.
Something like:
char *file;
file = strrchr(url, '/') + 1;

Related

How to read a text file from resources without javaClass

I need to read a text file with readLines() and I've already found this question, but the code in the answers always uses some variation of javaClass; it seems to work only inside a class, while I'm using just a simple Kotlin file with no declared classes. Writing it like this is correct syntax-wise but it looks really ugly and it always returns null, so it must be wrong:
val lines = object {}.javaClass.getResource("file.txt")?.toURI()?.toPath()?.readLines()
Of course I could just specify the raw path like this, but I wonder if there's a better way:
val lines = File("src/main/resources/file.txt").readLines()
Thanks to this answer for providing the correct way to read the file. Currently, reading files from resources without using javaClass or similar constructs doesn't seem to be possible.
// use this if you're inside a class
val lines = this::class.java.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()
// use this otherwise
val lines = object {}.javaClass.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()
According to other similar questions I've found, the second way might also work within a lambda but I haven't tested it. Notice the need for the ?. operator and the lines?.let {} syntax needed from this point onward, because getResourceAsStream() returns null if no resource is found with the given name.
Kotlin doesn't have its own means of getting a resource, so you have to use Java's method Class.getResource. You should not assume that the resource is a file (i.e. don't use toPath) as it could well be an entry in a jar, and not a file on the file system. To read a resource, it is easier to get the resource as an InputStream and then read lines from it:
val lines = this::class.java.getResourceAsStream("file.txt").bufferedReader().readLines()
I'm not sure if my response attempts to answer your exact question, but perhaps you could do something like this:
I'm guessing in the final use case, the file names would be dynamic - Not statically declared. In which case, if you have access to or know the path to the folder, you could do something like this:
// Create an extension function on the String class to retrieve a list of
// files available within a folder. Though I have not added a check here
// to validate this, a condition can be added to assert if the extension
// called is executed on a folder or not
fun String.getFilesInFolder(): Array<out File>? = with(File(this)) { return listFiles() }
// Call the extension function on the String folder path wherever required
fun retrieveFiles(): Array<out File>? = [PATH TO FOLDER].getFilesInFolder()
Once you have a reference to the List<out File> object, you could do something like this:
// Create an extension function to read
fun File.retrieveContent() = readLines()
// You can can further expand this use case to conditionally return
// readLines() or entire file data using a buffered reader or convert file
// content to a Data class through GSON/whatever.
// You can use Generic Constraints
// Refer this article for possibilities
// https://kotlinlang.org/docs/generics.html#generic-constraints
// Then simply call this extension function after retrieving files in the folder.
listOfFiles?.forEach { singleFile -> println(singleFile.retrieveContent()) }
In order to have the same url that work for both Jar or in local, the url (or path) needs to be a relative path from the repository root.
..meaning, the location of your file or folder from your src folder.
could be "/main/resources/your-folder/" or "/client/notes/somefile.md"
The url must be a relative path from the repository root.
it must be "src/main/resources/your-folder/" or "src/client/notes/somefile.md"
Now you get the drill, and luckily for Intellij Idea users, you can get the correct path with a right-click on the folder or file -> copy Path/Reference.. -> Path From Repository Root (this is it)
Last, paste it and do your thing.

fetch a discord link from a long text

૮₍ • ᴥ • ₎ა・Raiden ▬▭⋱𓂅
ᘏ⑅ᘏ╭╯Welcome╰╮𓂃ᘏᗢ
・・・・・・・・・・・・・・・・・・・・・
https://discord.gg/rsCC8y7WC4
・・・・・・・・・・・・・・・・・・・・・
Join!
・・・・・・・・・・・・・・・・・・・・・
How can I pull the "discord.gg/rsCC8y7WC4" link from a text like this
console.log(invitelink) ==> discord.gg/rsCC8y7WC4
Use String.match() for this. String.match accepts a regex argument which looks like this:
let str = 'hey there this is just a random string';
let res = str.match(/random/);
//res is now ['random']
Now for your problem, you are probably looking for this:
if(msg.content.match(/discord\.gg\/.+/) || msg.content.match(/discordapp\.com\/invite\/.+/)) return msg.channel.send('Hey! You put an invite in your message!');
Now that regex may look a bit messy/complicated but the \s are to escape the character and make sure regex knows that it’s not the special character it uses, and is actually just a character part of the search. To clarify why the above example should work, here’s a little explanation:
match() returns either an array (if it gets a match) or null (if it gets no match). You are searching for the strings 'discord.gg/' followed by any characters and also checking for the string 'discordapp.com/invite/' also followed by any characters.
If this doesn’t work, please tell me.

Returning the filename of the current sketch

I am trying to write a GUI that will display the name of the sketch it was generated from using a simple text() command. However, I am running into trouble getting any of the general JS solutions to work for me. Many solutions I have found use the filename reserved word but that does not seem to be reserved in Processing 3.5.4. I have also tried parsing the strings using a similar method to what can be found here. I am very new to processing and this is only my 2nd attempt at using Processing.
Any advice would be greatly appreciated
You can get the path (as a string) to the sketch with sketchPath().
From there you could either parse the string (pull off everything after the last slash) to get the sketch name, or you can use sketchFile() to get a reference to the file itself and get the name from there:
String path = sketchPath();
File file = sketchFile(path);
String sketchName = file.getName();
println(sketchName);
You could combine this all into one line like so:
String sketchName = sketchFile(sketchPath()).getName();

Reactjs convert input string to upper case

I'm creating an app in Reactjs using react-strap. I would like to convert an input field to upper case.
From googling, it looks like simply appending "toUpperCase()" to the field would work, but this doesn't appear as an option in Visual Studio code.
I had a similar issue with doing a replace all, but finally got that to work using "const" field:
// replace ":" with "-"
const phrase = item.macs;
const replaced = phrase.replace(/:/g, '-')
item.macs = replaced;
However, converting to a const field doesn't work for making the "toUpperCase()" available.
What should I do to turn this into a string so I can call the "toUpperCase()" function?
Edit: change references from "toUpper" to "toUpperCase". The problem is this is not available as a function.
For example of I do
'myString'.toUpperCase();
it works. But it I can't get it to bring that up in Visual Studio Code, and it's ignored if I code it anyway.
I believe you are looking after toUpperCase.
To make a string uppercase in javascript you can call .toUpperCase() method on it. For example
const foo = 'foo'
const fooUpper = foo.toUpperCase()
console.log(fooUpper) // expected result 'FOO'
I got around this problem by forcing the input item to be regarded as a string by prepending it with a '', like so:
item.macs = '' + item.macs;
item.macs = item.macs.replace(/:/g, '-');
item.macs = item.macs.toUpperCase();
After that, all the string functions were available.

One line code examples in various languages for MD5

I'm looking for one line code examples in various languages for getting a valid MD5 result (as a string, not a bytehash or what have you). For instance:
PHP:
$token = md5($var1 . $var2);
I found VB especially troublesome to do in one line.
C#:
string hash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "md5");
VB is virtually the same.
Here it is not using the System.Web namespace:
string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));
Or in readable form:
string hash =
Convert.ToBase64String
(new System.Security.Cryptography.MD5CryptoServiceProvider()
.ComputeHash
(System.Text.Encoding.UTF8.GetBytes
(input)
)
);
There is a kind of universality in how this is to be accomplished. Typically, one defines a routine called md5_in_one_line (or Md5InOneLine) once, and uses it all over the place, just as one would use a library routine.
So for example, once one defines Md5InOneLine in C#, it's an easy one-liner to get the right results.
Python
token = __import__('md5').new(var1 + var2).hexdigest()
or, if md5 is alrady imported:
token = md5.new(var1 + var2).hexdigest()
Thanks to Greg Hewgill
Aren't you really just asking "what languages have std. library support for MD5?" As Justice said, in any language that supports it, it'll just be a function call storing the result in a string variable. Even without built-in support, you could write that function in any language!
Just in case you need VBScript:
download the MD5 class from webdevbros and then with one line:
hash = (new MD5).hash("some value")
Does it really matter if you can do MD5 in one line. If it's that much trouble that you can't do it in VB in 1 line, then write your own function. Then, when you need to do MD5 in VB in one line, just call that function.
If doing it all in 1 line of code is all that important, here is 1 line of VB. that doesn't use the System.Web Namespace.
Dim MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider() : Dim HashBytes() As Byte : Dim MD5Str As String = "" : HashBytes = MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes("MyString")) : For i As Integer = 0 To HashBytes.Length - 1 : MD5Str &= HashBytes(i).ToString("x").PadLeft(2, "0") : Next
This will hash "MyString" and store the MD5 sum in MD5Str.
Coldfusion has a bunch of hashing algorithms, MD5 is the default.
cfset var md5hashresult = hash("string to hash")

Resources