SPARQL query with filtering - regex

I like to list all drugs that start with some letter to fill autocomplete text box.Here is the code
public string[] GetCompletionList(string prefixText)
{
string rdfDat = AppDomain.CurrentDomain.BaseDirectory + "DrugRDF.rdf";
List<string> list = new List<string>();
TripleStore store = new TripleStore();
Graph rdf = new Graph();
FileLoader.Load(rdf, rdfDat, new RdfXmlParser());
store.Add(rdf);
string tmp = "^" + prefixText;
string sparqlQuery = "PREFIX mojLek: <http://www.example.org/mojLek#>"
+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>"
+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
+ "SELECT ?x"
+ "WHERE {?h mojLek:ime ?x ."
+ "FILTER regex(str(?x),"+tmp+") }";
SparqlQueryParser sparqlParser = new SparqlQueryParser();
SparqlQuery query = sparqlParser.ParseFromString(sparqlQuery);
Object results = store.ExecuteQuery(query);
if (results is SparqlResultSet)
{
SparqlResultSet r = results as SparqlResultSet;
foreach (SparqlResult res in r)
{
list.Add(res["x"].ToString().ToLower());
}
}
return list.ToArray();
}
However if I try it with for example A there are already couples that starts with A I got this error
VDS.RDF.Parsing.RdfParseException: [Line 1 Column 263] The value 'A' is not valid as a QName
at VDS.RDF.Parsing.Tokens.SparqlTokeniser.TryGetQNameOrKeyword()
at VDS.RDF.Parsing.Tokens.SparqlTokeniser.GetNextToken()
at VDS.RDF.Parsing.Tokens.TokenQueue.InitialiseBuffer()
at VDS.RDF.Parsing.SparqlQueryParser.ParseInternal(SparqlQueryParserContext context)
at VDS.RDF.Parsing.SparqlQueryParser.ParseInternal(TextReader input)
at VDS.RDF.Parsing.SparqlQueryParser.ParseFromString(String queryString)
at SuggestWebService.GetCompletionList(String prefixText) in d:\Suggest\App_Code\SuggestWebService.cs:line 57

Put newlines in the query string to make the error messages better.
There are no SPARQL quotes at
regex(str(?x),"+tmp+")
Try:
regex(str(?x),'"+tmp+"')
which puts single quotes into the SPARQL. Be careful of any quotes in tmp.

I have changed my code in this way so it worked for me
string tmp="^"+prefixText;
var query = "PREFIX mojLek: <http://www.example.org/mojLek#>"
+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>"
+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
+ "PREFIX fn: <http://www.w3.org/2005/xpath-functions#>"
+ "SELECT ?x ?h"
+ "WHERE {?h mojLek:ime ?x ."
+ "FILTER regex(?x,\""+tmp+"\")"
+"}";

Related

regex repeated capturing group captures the last iteration but I need all

Example code:
var reStr = `"(?:\\"|[^"])*"`
var reStrSum = regexp.MustCompile(`(?m)(` + reStr + `)\s*\+\s*(` + reStr + `)\s*\+\s*(` + reStr + `)`)
var str = `"This\nis\ta\\string" +
"Another\"string" +
"Third string"
`
for i, match := range reStrSum.FindAllStringSubmatch(str, -1) {
fmt.Println(match, "found at index", i)
for i, str := range match {
fmt.Println(i, str)
}
}
Output:
["This\nis\ta\\string" +
"Another\"string" +
"Third string" "This\nis\ta\\string" "Another\"string" "Third string"] found at index 0
0 "This\nis\ta\\string" +
"Another\"string" +
"Third string"
1 "This\nis\ta\\string"
2 "Another\"string"
3 "Third string"
E.g. it matches the "sum of strings" and it captures all three strings correctly.
My problem is that I do not want to match the sum of exactly three strings. I want to match all "sum of strings" where the sum can consist of one or more string literals. I have tried to express this with {0,}
var reStr = `"(?:\\"|[^"])*"`
var reStrSum = regexp.MustCompile(`(?m)(` + reStr + `)` + `(?:\s*\+\s*(` + reStr + `)){0,}`)
var str = `
test1("This\nis\ta\\string" +
"Another\"string" +
"Third string summed");
test2("Second string " + "sum");
`
for i, match := range reStrSum.FindAllStringSubmatch(str, -1) {
fmt.Println(match, "found at index", i)
for i, str := range match {
fmt.Println(i, str)
}
}
`)){0,}`)
then I get this result:
["This\nis\ta\\string" +
"Another\"string" +
"Third string summed" "This\nis\ta\\string" "Third string summed"] found at index 0
0 "This\nis\ta\\string" +
"Another\"string" +
"Third string summed"
1 "This\nis\ta\\string"
2 "Third string summed"
["Second string " + "sum" "Second string " "sum"] found at index 1
0 "Second string " + "sum"
1 "Second string "
2 "sum"
Group 0 of the first match contains all three strings (the regexp matches correctly), but there are only two capturing groups in the expression, and the second group only contains the last iteration of the repetition. E.g. "Another\"string" is lost in the process, it cannot be accessed.
Would it be possible to get all iterations of (all repetitions) inside group 2 somehow?
I would also accept any workaround that uses nested loops. But please be aware that I cannot simply replace the {0,} repetition with an outer FindAllStringSubmatch call, because the FindAllStringSubmatch call is already used for iterating over "sums of strings". In other words, I must find the first string sum and also the "Second string sum".
I just found a workaround that will work. I can do two passes. In the first pass, I just match all string literals, and replace them with unique placeholders in the original text. Then the transformed text won't contain any strings, and it becomes much easier to do further processing on it in a second pass.
Something like this:
type javaString struct {
value string
lineno int
}
// First we find all string literals
var placeholder = "JSTR"
var reJavaStringLiteral = regexp.MustCompile(`(?m)("(?:\\"|[^"])*")`)
javaStringLiterals := make([]javaString, 0)
for pos, strMatch := range reJavaStringLiteral.FindAllStringSubmatch(strContent, -1) {
pos = strings.Index(strContent, strMatch[0])
head := strContent[0:pos]
lineno := strings.Count(head, "\n") + 1
javaStringLiterals = append(javaStringLiterals, javaString{value: strMatch[1], lineno: lineno})
}
// Next, we replace all string literals with placeholders.
for i, jstr := range javaStringLiterals {
strContent = strings.Replace(strContent, jstr.value, fmt.Sprintf("%v(%v)", placeholder, i), 1)
}
// Now the transformed text does not contain any string literals.
After the first pass, the original text becomes:
test1(JSTR(1) +
JSTR(2) +
JSTR(3));
test2(JSTR(3) + JSTR(4));
After this step, I can easily look for "JSTR(\d+) + JSTR(\d+) + JSTR(\d+)..." expressions. Now they are easy to find, because the text does not contain any strings (that could otherwise contain practically anything and interfere with regular expressions). These "sum of string" matches can then be re-matched with another FindAllStringSubmatch (in an inner loop) and then I'll get all information that I needed.
This is not a real solution, because it requires writting a lot of code, it is specific to my concrete use case, and does not really answer the original question: allow access to all iterations inside a repeated capturing group.
But the general idea of the workaround might be benefical for somebody who is facing a similar problem.

Cannot convert values ​into mysql

I want to enter the value of a variable into a MySql database, but it is giving me this error:
I use code like this:
ADOQuery1->SQL->Clear();
ADOQuery1->SQL->Add("insert into data_nasabah(nama_nasabah,tanggal,debit/kredit,saldo,no_rekening)values('"+ns[0].nama+"','"+Date()+"','"+ns[0].dk[0]+"','"+ns[0].saldo[0]+"','"+rekening[n]+"')");
ADOQuery1->ExecSQL();
Column names that have special characters in them need to be quoted with `, or " in ANSI_QUOTES mode. See 9.2 Schema Object Names in MySQL's documentation.
Try this:
ADOQuery1->SQL->Text = "insert into data_nasabah (nama_nasabah, tanggal, `debit/kredit`, saldo, no_rekening) values ('" + ns[0].nama + "','" + Date() + "','" + ns[0].dk[0] + "','" + ns[0].saldo[0] + "','" + rekening[n] + "')";
However, don't format SQL statement parameters manually like you are! This is subject to SQL Injection attacks. You can use Sysutils::QuotedStr() (or Sysutils::AnsiQuotedStr()) to avoid this, eg:
ADOQuery1->SQL->Text = "insert into data_nasabah (nama_nasabah, tanggal, `debit/kredit`, saldo, no_rekening) values (" + QuotedStr(ns[0].nama) + "," + QuotedStr(Date()) + "," + QuotedStr(ns[0].dk[0]) + "," + QuotedStr(ns[0].saldo[0]) + "," + QuotedStr(rekening[n]) + ")";
But, you really should be using a parameterized query instead, let the database engine handle the quoting for you, eg:
// make sure to set ADOQuery1->ParamCheck=true beforehand!
ADOQuery1->SQL->Text = "insert into data_nasabah (nama_nasabah, tanggal, `debit/kredit`, saldo, no_rekening) values (:PNamaNasabah, :PTanggal, :PDebitKredit, :PSaldo, :PNoRekening)";
ADOQuery1->Parameters->ParamByName("PNamaNasabah")->Value = ns[0].nama;
ADOQuery1->Parameters->ParamByName("PTanggal")->Value = Date();
ADOQuery1->Parameters->ParamByName("PDebitKredit")->Value = ns[0].dk[0];
ADOQuery1->Parameters->ParamByName("PSaldo")->Value = ns[0].saldo[0];
ADOQuery1->Parameters->ParamByName("PNoRekening")->Value = rekening[n];
ADOQuery1->ExecSQL();

Regex for extracting the exception names

I want to extract the exception name from the below sentences using regex pattern,
Error: MYTERA RuntimeException: No task output
Error: android.java.lang.NullPointerException.checked
I need the terms RuntimeException and NullPointerException with a single Regex pattern.
This expression might help you to do so:
([A-Za-z]+Exception)
Graph
This graph shows how the expression would work and you can visualize your expressions in this link:
Performance
This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = 'Error: android.java.lang.NullPointerException.checked';
var regex = /(.*)\.([A-Za-z]+Exception)(.*)/g;
var match = string.replace(regex, "$2");
}
end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match πŸ’šπŸ’šπŸ’š ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

c# Regex- Remove string which developed only combination of special charter

I am looking for regular expression by which I can ignore strings which is only combination of All special charters.
Example
List<string> liststr = new List<string>() { "a b", "c%d", " ", "% % % %" ,"''","&","''","'"}; etc...
I need result of this one
{ "a b", "c%d"}
You can use this, too, to match string without any Unicode letter:
var liststr = new List<string>() { "a b", "c%d", " ", "% % % %", "''", "&", "''", "'" };
var rx2 = #"^\P{L}+$";
var res2 = liststr.Where(p => !Regex.IsMatch(p, rx2)).ToList();
Output:
I also suggest creating the regex object as a private static readonly field, with Compiled option, so that performance is not impacted.
private static readonly Regex rx2 = new Regex(#"^\P{L}+", RegexOptions.Compiled);
... (and inside the caller)
var res2 = liststr.Where(p => !rx2.IsMatch(p)).ToList();
Use this one :
.*[A-Za-z0-9].*
It matches at least one alphanumeric character. Doing this, it will take any string that is not only symbols/special chars. It does the output you want, see here : demo
You can use a very simple regex like
Regex regex = new Regex(#"^[% &']+$");
Where
[% &'] Is the list of special characters that you wish to include
Example
List<string> liststr = new List<string>() { "a b", "c%d", " ", "% % % %" ,"''","&","''","'"};
List<string> final = new List<string>();
Regex regex = new Regex(#"^[% &']+$");
foreach ( string str in liststr)
{
if (! regex.IsMatch(str))
final.Add(str);
}
Will give an output as
final = {"a b", "c%d"}

django make log that works for all models

I am trying to make my own log that makes a string of changed data between object (my old object and my new object) However i keep getting back empty string,
My code:
def log_fields(old_obj, new_obj):
fields = new_obj.__class__._meta.fields
changed_fields = ""
old_data = ""
new_data = ""
# get all changed data
for field in fields:
old_field_data = old_obj.__getattribute__(field.name)
new_field_data = new_obj.__getattribute__(field.name)
if old_field_data != new_field_data:
count =+ 1
# convert changed data to strings
# number + space + data + 5 spaces for next string
changed_fields.join(str(count)).join(" ").join(str(field)).join(" ")
old_data.join(str(count)).join(" ").join(str(old_field_data)).join(" ")
new_data.join(str(count)).join(" ").join(str(new_field_data)).join(" ")
print changed_fields
print old_data
print new_data
I got a feeling something with the string .join combination something is going wrong, cause trying this manually in shell seems to work up to the comparison. Not sure tho hos i should change the string
changed_fields = changed_fields + str(count) + "." + str(field.name) + " "
old_data = old_data + str(count) + "." + str(old_field_data) + " "
new_data = new_data + str(count) + "." + str(new_field_data) + " "
Seems to do the job, so for now, ill keep it at this