RavenDb Suggestions - return multiple-contexts words - autocomplete

I'm trying to get context based suggestions result from RavenDb, the purpose is ui dropdown with auto suggestion from large amount of data on server, each keystroke (in 400ms) is sent to retrieve suggestions.
The suggestion i need is with multiple words by context.
let's say i'm looking for 'Harry Potter', i have documents with just 'Harry' and some docs with only 'Potter', and documents with both.
But if i type 'harre poter' i would get one word suggestions.
i tried searching with multiple words (demonstrated here - suggest.Term = "(word1 word2)";), but the result is list of one words. i want to type 'harre poter' and get suggestion of 'Harry Potter'
i even tried querying multiple times with each word, but the result are not context based, in other word - there is no connection between them.
var words = text.Split(new String[] {" "}, StringSplitOptions.RemoveEmptyEntries).ToList();
var sugegstions = new List<SuggestionQuery>();
foreach (var word in words)
{
var suggest = new SuggestionQuery();
suggest.Field = "Body";
suggest.Term = word;
suggest.Popularity = true;
suggest.MaxSuggestions = 5;
suggest.Distance = StringDistanceTypes.Levenshtein;
sugegstions.Add(suggest);
}
var results = new List<SuggestionQueryResult>();
foreach (var suggest in sugegstions)
{
SuggestionQueryResult result =
s.Query<Book, Books_ByBody>().Suggest(suggest);
results.Add(result);
}
i looked in this SO question, and tried it too, but the results are the docs not suggestions.
my index is : `
public class Books_ByBody : AbstractIndexCreationTask
{
public Books_ByBody()
{
Map = books from book in books
select new
{
book.Body,
};
Indexes.Add(x => x.Body, FieldIndexing.Analyzed);
Suggestion(x => x.Body);
}
}
`

Related

Find the most used word in the text in flutter

I'm calculating how many different words there are. How can I find the most used word in the text. How can I add this to the code.
int kacFarkliKelime(String metin) {
String yeniMetin = metin.replaceAll(RegExp(r'[^\w\s]+'), "");
List<String> liste = yeniMetin.split(
" ",
);
List farklilar = [];
liste.forEach((element) {
String sorgulanan = element.toLowerCase();
if (!farklilar.contains(sorgulanan)) {
farklilar.add(sorgulanan);
}
});
if(farklilar[0])
return farklilar.length;
}
I'd build a Map<String, int> that'd count each word as it is seen, then get a list of keys sorted by descending value order. (There's a few handy "sort by" functions in package:collection to help with that.) The code for that would look like:
var words = (use a regex to extract words);
var count = <String,int>{};
for (final w in words) {
count[w] = 1 + (count[w] ?? 0);
}
var ordered = count.keys.toList();
ordered.sort((a, b) => count[b].compareTo(count[a]));
Now the first element of ordered is the word with the most appearances in the text.

Concatenate multiple PDF/A with different conformance levels

Is it possible to concatenate a number of pdf/a (with possibly different conformance levels: some pdf/a-1b, some pdf/a-3b ecc) into a single pdfa ?
I was thinking that using the latest level (3-a or 3b) would be ok but I get errors when validating with VeraPDF:
Here is my code (where :
public static byte[] CreateConformantCopy(List<byte[]> sourcePdfs)
{
var version = PdfVersion.PDF_1_7;
var type = PdfAType.PDF_A_3B;
WriterProperties wp = new WriterProperties();
wp.UseSmartMode();
wp.SetPdfVersion(version.ToPdfVersion());
PdfOutputIntent oi = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", Assembly.GetExecutingAssembly().GetManifestResourceStream("xxx.Resources.sRGB_CS_profile.icm"));
using (var mergedPdf = new MemoryStream())
{
var writer = new PdfWriter(mergedPdf, wp);
using (PdfADocument newDoc = new PdfADocument(writer, type.ToPdfAConformanceLevel(), oi, new DocumentProperties() { }))
{
Document document = new Document(newDoc, PageSize.A4.Rotate());
newDoc.SetTagged();
newDoc.GetCatalog().SetLang(new PdfString(Thread.CurrentThread.CurrentUICulture.Name));
newDoc.GetCatalog().SetViewerPreferences(
new PdfViewerPreferences()
.SetDisplayDocTitle(true)
.SetCenterWindow(true)
);
PdfMerger merger = new PdfMerger(newDoc);
for (int k = 0; k < sourcePdfs.Count; k++)
{
using (var inDoc = PdfHelper.GetDocument(sourcePdfs[k]))
{
var numberOfPages = inDoc.GetNumberOfPages();
merger.Merge(inDoc, 1, numberOfPages);
}
}
newDoc.Close();
}
return mergedPdf.ToArray();
}
}
PDF/A-1 and PDF/A-2 have several differences in the requirements. So, merging them together might not be possible. Looking on your validation errors, I think this is exactly the case. For example, the very first one is about XMP metadata. The PDF/A-2 is more strict here, and you get this error because your first file (which is probably a valid PDF/A-1) does not actually satisfy the PDF/A-2 rules.
What is possible however is to attach a PDF/A-1 document to PDF/A-2 one. This does not even require the use of PDF/A-3, which allows arbitrary attachments. The PDF/A-2 standard does allow attaching valid PDF/A-1 (as well as PDF/A-2 documents).

get value for specific question/item in a Google Form using Google App Script in an on submit event

I have figured out how to run a Google App Script project/function on a form submit using the information at https://developers.google.com/apps-script/guides/triggers/events#form-submit_4.
Once I have e I can call e.response to get a FormResponse object and then call getItemResponses() to get an array of all of the responses.
Without iterating through the array and checking each one, is there a way to find the ItemResponse for a specific question?
I see getResponseForItem(item) but it looks like I have to somehow create an Item first?
Can I some how use e.source to get the Form object and then find the Item by question, without iterating through all of them, so I could get the Item object I can use with getResponseForItem(item)?
This is the code I use to pull the current set of answers into a object, so the most current response for the question Your Name becomes form.yourName which I found to be the easiest way to find responses by question:
function objectifyForm() {
//Makes the form info into an object
var myform = FormApp.getActiveForm();
var formResponses = myform.getResponses()
var currentResponse = formResponses[formResponses.length-1];
var responseArray = currentResponse.getItemResponses()
var form = {};
form.user = currentResponse.getRespondentEmail(); //requires collect email addresses to be turned on or is undefined.
form.timestamp = currentResponse.getTimestamp();
form.formName = myform.getTitle();
for (var i = 0; i < responseArray.length; i++){
var response = responseArray[i].getResponse();
var item = responseArray[i].getItem().getTitle();
var item = camelize(item);
form[item] = response;
}
return form;
}
function camelize(str) {
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()#\+\?><\[\]\+]/g, '')
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
//Use with installable trigger
function onSubmittedForm() {
var form = objectifyForm();
Logger.log(form);
//Put Code here
}
A couple of important things.
If you change the question on the form, you will need to update your
code
Non required questions may or may not have answers, so check if answer exists before you use it
I only use installable triggers, so I know it works with those. Not sure about with simple triggers
You can see the form object by opening the logs, which is useful for finding the object names

Relational Queries In parse.com (Unity)

I found example in parse.com. I have 2 objects : Post and Comment, in the Comment objects have a collumn: "parent" pointer to Post obj and I want to join them:
var query = ParseObject.GetQuery ("Comment");
// Include the post data with each comment
query = query.Include("parent");
query.FindAsync().ContinueWith(t => {
IEnumerable<ParseObject> comments = t.Result;
// Comments now contains the last ten comments, and the "post" field
// contains an object that has already been fetched. For example:
foreach (var comment in comments)
{
// This does not require a network access.
string o= comment.Get<string>("content");
Debug.Log(o);
try {
string post = comment.Get<ParseObject>("parent").Get<string>("title");
Debug.Log(post);
} catch (Exception ex) {
Debug.Log(ex);
}
}
});
It worked!
And then, I have 2 objects: User and Gamescore, in the Gamescore objects have a collumn: "playerName" pointer to Post obj I want join them too:
var query = ParseObject.GetQuery ("GameScore");
query.Include ("playerName");
query.FindAsync ().ContinueWith (t =>{
IEnumerable<ParseObject> result = t.Result;
foreach (var item in result) {
Debug.Log("List score: ");
int score = item.Get<int>("score");
Debug.Log(score);
try {
var obj = item.Get<ParseUser>("playerName");
string name = obj.Get<string>("profile");
//string name = item.Get<ParseUser>("playerName").Get<string>("profile");
Debug.Log(name);
} catch (Exception ex) {
Debug.Log(ex);
}
}
});
but It isn't working, Please help me!
Why didn't you do the following like you did your first example:
query = query.Include ("playerName");
you just have -
query.Include ("playerName");
One solution would be to ensure that your ParseUser object is properly fetched. ie:
var obj = item.Get<ParseUser>("playerName");
Task t = obj.FetchIfNeededAsync();
while (!t.IsCompleted) yield return null;
Then you can do this without worrying:
string name = obj.Get<string>("profile");
But that will be another potential request to Parse, which is unfortunate. It seems that query.Include ("playerName") isn't properly working in the Unity version of Parse?
I believe you're supposed to use multi-level includes for this, like .Include("parent.playerName") in your first query.

Equivalent function to "find in all diagrams" in Enterprise Architect

I am searching for a API function corresponding to the "find in all diagrams"-function (Strg + U) in Enterprise Architect.
The class element provides the attribute diagrams which should return a collection of diagrams but it returns in my case always an empty list. Is it the wrong way?
EDIT:
I would be happy about a function that returns a collection of diagrams which include the element.
THE SOLUTION:
public List<EA.Diagram> getAllDiagramsOfElement(EA.Element element){
String xmlQueryResult = repository.SQLQuery(
"select dobj1.Diagram_ID " +
"from t_diagramobjects dobj1 " +
"where dobj1.Object_ID = " + element.ElementID+";");
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlQueryResult);
XmlNodeList xnList = xml.SelectNodes("/EADATA/Dataset_0/Data/Row");
List<EA.Diagram> result = new List<EA.Diagram>();
foreach (XmlNode xn in xnList){
result.Add(repository.GetDiagramByID(Convert.ToInt32(xn["Diagram_ID"].InnerText)));
}
return result;
}
With kind regards
MK
You might have to use a query,
Try this
select * from t_diagramobjects dobj1, t_diagramobjects dobj2 where dobj1.object_id=dobj2.object_id and dobj1.diagram_id!=dobj2.diagram_id;
In case you would like to stay with the API, you have to walk the packages in the model tree recursively, adding diagrams to a collection (ok, Dictionary object in VBScript).
Then you find all Diagramobjects from Diagrams. DiagramObjects then relate to Elements (remember, Element may be represented in more Diagrams).
Another approach could be to use Repository.SQLQuery method, which should return XML-formatted resultset (I didn't test that yet). But you'd need MSXML present on the machine to parse it (and keep up with the versions).
Generally, if you want to scan whole model and you don't need parent-child relationships, SQL should be better fit. And vice versa.
I have this same function in my Enterprise Architect Add-in Framework, implemented in the class ElementWrapper:
//returns a list of diagrams that somehow use this element.
public override HashSet<T> getUsingDiagrams<T>()
{
string sqlGetDiagrams = #"select distinct d.Diagram_ID from t_DiagramObjects d
where d.Object_ID = " + this.wrappedElement.ElementID;
List<UML.Diagrams.Diagram> allDiagrams = this.model.getDiagramsByQuery(sqlGetDiagrams).Cast<UML.Diagrams.Diagram>().ToList(); ; ;
HashSet<T> returnedDiagrams = new HashSet<T>();
foreach (UML.Diagrams.Diagram diagram in allDiagrams)
{
if (diagram is T)
{
T typedDiagram = (T)diagram;
if (!returnedDiagrams.Contains(typedDiagram))
{
returnedDiagrams.Add(typedDiagram);
}
}
}
return returnedDiagrams;
}
The function getDiagramsByQuery in the Model class looks like this
//returns a list of diagrams according to the given query.
//the given query should return a list of diagram id's
public List<Diagram> getDiagramsByQuery(string sqlGetDiagrams)
{
// get the nodes with the name "Diagram_ID"
XmlDocument xmlDiagramIDs = this.SQLQuery(sqlGetDiagrams);
XmlNodeList diagramIDNodes =
xmlDiagramIDs.SelectNodes(formatXPath("//Diagram_ID"));
List<Diagram> diagrams = new List<Diagram>();
foreach (XmlNode diagramIDNode in diagramIDNodes)
{
int diagramID;
if (int.TryParse(diagramIDNode.InnerText, out diagramID))
{
Diagram diagram = this.getDiagramByID(diagramID);
diagrams.Add(diagram);
}
}
return diagrams;
}