I want to write a custom filter which works as similar to Path Hierarchy Tokenizer - solr

please find attached code I can't post image of analysis as my reputation is less than 10. the thing is I am getting empty space until last token and there after all those tokes which are added. the problem here is in analysis I query is not matching with the index content I am not getting whats going wrong
public final boolean incrementToken() throws IOException
{
if(Flag_Tokens_are_read)
{
String buffer="";
if((loop++)!=tokenCount-1)
{
for(int k=loop;k<tokenCount;)
{
buffer = buffer+tokensArray.get(k).toString();
k++;
if(k<tokenCount)
buffer=buffer+" ";
else
{
if(Flag_First_Time_total_length)
{ startOffset=0;
endOffset=buffer.length();
Flag_First_Time_total_length=false;
}
else
{
int length = buffer.length()-1;
startOffset=endOffset-length;
//endOffset=17;
}
char[] newBuffer = buffer.toCharArray();
termAtt.setEmpty();
this.termAtt.copyBuffer(newBuffer, 0, newBuffer.length);
offsetAtt.setOffset(startOffset, endOffset);
posIncAttr.setPositionIncrement(0);
return true;
}
}
}
return false;
}
if (input.incrementToken())
{
String token = termAtt.toString();
tokensArray.add(token);
//this.termAtt.copyBuffer(newBuffer, 0, newBuffer.length);
return incrementToken();
}
else
{ if(Flag_First_Time)
{
tokenCount=tokensArray.size();
Flag_Tokens_are_read=true;
loop=-1;
Flag_First_Time = false;
return incrementToken();
}
else
{
return false;
}
}
this is my code for incrementtoken(). its working but I don't know why it is not working for query searching

Related

System.IndexOutOfRangeException in c# window form

I have been trying too parse 2 parameter using for loop but it only loop once and locates one parameter. This is my code.
By providing rectangle 70,80 command in the form, I am trying to draw shapes but while passing through check variable for loop works only once. It does not increments but returns value only after first execution then goes to check number of parameter then rejects with error Array out of bounds.
public String[] ParameterSplit;
public IDictionary<string, int> VariableDictionary = new Dictionary<string, int>();
public IDictionary<string, int> MethodVariableDictionary = new Dictionary<string, int>();
public Boolean AlreadyInArray = false;
public Boolean Value1IsVariable = false;
public Boolean Value2IsVariable = false;
public int value = 0;
public int value1 = 0;
public int value2 = 0;
public CommandParser()
{
}
//This method is used for the validation of commands and parameters which passes thorough
//singleline command and multiline command method
public string[] CommandParsers(string input, int lineCount)
{
string[] text = { };
string[] inputcommand = input.Split(',', ' ');
if (inputcommand[0].ToUpper() == "MOVETO")
{
if(inputcommand.Length < 4)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
}
else
{
if (inputcommand[0].ToUpper() == "DRAWTO")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show($"ERROR: Provide correct parameter for moveto in line no {lineCount}");
string[] strings = { "moveto,100,100" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "RECTANGLE")
{
ParameterSplit = inputcommand[1].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
CheckForVariable();
if (ParameterSplit.Length == 2)
{
}
else
{
Convert.ToInt32(ParameterSplit[0]);
Convert.ToInt32(ParameterSplit[1]);
text = ParameterSplit;
}
}
else if (inputcommand[0].ToUpper() == "CIRCLE")
{
if (inputcommand.Length == 2)
{
Convert.ToInt32(inputcommand[1]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for circle in line no " + lineCount );
string[] strings = { "circle,20" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "TRIANGLE")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for triangle in line no "+ lineCount);
string[] strings = { "triangle,20,60" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "PEN")
{
Pen = true;
string[] validateinput = { "pen", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "red":
color = Color.Red;
break;
case "blue":
color = Color.Blue;
break;
case "yellow":
color = Color.Yellow;
break;
case "green":
color = Color.Green;
break;
case "violet":
color = Color.Violet;
break;
}
}
else if (inputcommand[0].ToUpper() == "FILL")
{
string[] validateinput = { "fill", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "on":
fill = true;
break;
case "off":
fill = false;
break;
}
}
else if (inputcommand.Length > 2)
{
text = inputcommand;
//checks if the middle element is a "="
if(inputcommand[1].ToUpper() == "=")
{
//check if the variable is already stored or not
//StoreVarialable();
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[0]))
{
AlreadyInArray = true;
}
}
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if(variable.Key.Equals(inputcommand[2]))
{
value1 = variable.Value;
Value1IsVariable = true;
}
}
if(inputcommand.Length.Equals(5))
{
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[4]))
{
value2 = variable.Value;
Value2IsVariable = true;
}
}
if (AlreadyInArray)
{
VariableDictionary.Remove(inputcommand[0]);
}
}
try
{
if (Value1IsVariable.Equals(false))
{
value1 = Convert.ToInt32(inputcommand[2]);
}
if (Value2IsVariable.Equals(false))
{
if (inputcommand.Length.Equals(5))
{
value2 = Convert.ToInt32(inputcommand[4]);
}
}
if (inputcommand.Length > 3)
{
if (inputcommand[3].Equals("+"))
{
value = value1 + value2;
}
else if (inputcommand[3].Equals("-"))
{
value = value1 - value2;
}
else
{
//InvalidOperator();
}
}
else
{
try
{
value = int.Parse(inputcommand[2]);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
}
}
//Adds the variable with the inputted value if it is an integer
// VariableDictionary.Add(inputcommand[0], value);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
//return;
}
}
else
{
}
}
else
{
string[] validateinput = { "error" };
text = validateinput;
}
//end of condition
}
return text;
}
public void CheckForVariable()
{
//Loops through all the parameters
for (int i = 0; i<ParameterSplit.Length ; i++)
{
int index = i;
try
{
//Checks if the parameter is an int
int test = int.Parse(ParameterSplit[index]);
}
catch
{
Boolean foundVariable = false;
foreach (KeyValuePair<string, int> variable in MethodVariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[index]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[index] = variable.Value.ToString();
//ErrorList = ErrorList + variable.Key + ParameterSplit[i] + Environment.NewLine; ;
foundVariable = true;
}
}
if (foundVariable == false)
{
//if it is not then loop through the VariableDictionary to check if the parameter is a variable name
foreach (KeyValuePair<string, int> variable in VariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[i]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[i] = variable.Value.ToString();
}
}
}
}
}
}
//This method is used to get the color from pen by returning its values
internal Color getColor()
{
return color;
}
}
I tried this where I have to check 2 parameter using for loop inside CheckForVariable method

RSSService item with the same key multiple times

I have a RSSService with an item like the one show below
<item>
<title>Accessori per la cura della persona</title>
<link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
<comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
<pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
<dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
<category><![CDATA[News]]></category>
<category><![CDATA[Offerte]]></category>
<category><![CDATA[Callifugo]]></category>
<category><![CDATA[Raspa piedi]]></category>
<category><![CDATA[Spazzola ceramica]]></category>
<category><![CDATA[Spazzola piatta]]></category>
<category><![CDATA[Spazzola tonda]]></category>
<category><![CDATA[Spazzole capelli]]></category>
<guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
<description>.....
To read all the content I use this:
List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
Button b = new Button((String)m.get("title"));
if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}
When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:
String[] mc = (String[]) m.get("category");
Thank's in advance for any help.
Davide.
This looks like a missing feature in RSSService that expects to find only one category entry and so it parses it into a hash map which effectively allows only one such entry.
I would suggest implementing your own RSS reading and go to the XML directly to get the full power of the protocol. You can use the existing class as a reference on how to do the RSS/ATOM parsing.
This is my idea
protected void textElement(String text) {
if(lastTag != null && current != null) {
// make "ATOM" seem like RSS
if("summary".equals(lastTag)) {
current.put("details", text);
} else {
if("content".equals(lastTag)) {
current.put("description", text);
} else {
if(current.get(lastTag) != null){
try {
List list = (List) current.get(lastTag);
list.add(text);
current.put(lastTag, list);
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
List list = new ArrayList();
list.add((String)current.get(lastTag));
list.add(text);
current.put(lastTag, list);
}
} else {
current.put(lastTag, text);
}
}
}
}
}
Used in my Form like this:
for (Map m : records) {
Button b = new Button((String)m.get("title"));
try{
String category = (String)m.get("category");
if(category.equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
b.setIcon(iconNews);
List list = (List) m.get("category");
for(int i=0; i < list.size(); i++){
if(((String)list.get(i)).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
}
}
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}

store data in array from another class method

i have one method in class call Class1 like
' public void getEventFromUser() {
int event;
Scanner input = new Scanner(System.in);
date.getDateFromUser();
// od.inputday();
// od.inputyear();
time.getTimeFromUser();
System.out.println("Enter description :");
description = input.nextLine();
}'
and i want to execute this method and store in array in another class
like
public void addEvent() {
if (numEvent == maxEvent) {
System.out.println("error…no more room to add events");
} else {
schedule[numEvent]=getEventFromUser();
int count = 0;
while (count < numEvent - 1) {
if (schedule[numEvent].isEqual(schedule[count])) {
isFound = true;
break;
}
count++;
if (isFound == true) {
System.out.println("Event already exists-notadding");
schedule[numEvent] = null;
} else {
schedule[numEvent].setDate();
schedule[numEvent].setTime();
schedule[numEvent].setDescription();
numEvent++;
//schedule[numEvent]=schedule[numEvent].getEventFromUser();
}
}
}
} '
so,how can i do this?
pls give me some solution
getEventFromUser() doesn't return a value, which is why schedule[numEvent]=schedule[numEvent].getEventFromUser() is giving you trouble.
Without knowing a bit more about what you're trying to do, it's hard to say if you should have getEventFromUser() return a value or have getEventFromUser() directly store a value in a field in the class. (I'm guessing the setDate, setTime and setDescription methods do this.)

How can I detect the last character of GSM modem response

I am using a GSM modem "SIM900"
I have tested it with hyper terminal and main command is ok.
Then I burnt the code to send the AT command to dial a number on the Microcontroller to the GSM modem using UART and it works fine.
But I'm having a problem with the response.
The GSM replies with stream of characters but it doesn't end with Null '\0' !
How can I get the whole response in array to parse it later? And, how can I detect the end of response?
AT\r\n response is ==> OK
AT+CMGR=1 response is ==> +CMGR: "REC UNREAD" ,"+2347060580383","10/10/27,18:54:32+04"
Thanks in advance.
You can use \r\nOK for the ending, because phones use \n only for NewLine. But there's a more reliable way (I did that once) to make sure you don't get the wrong ending, for example when the incoming text message had the exact \r\nOK in it. In order to do that, I suggest that you change the Character Set to UCS2, so you will get the message text and sender number in UnicodeArray (It's like it is been escaped.)
Here's the class I used for my purpose (The extra check modules (AT\r command) are used to prevent getting stuck in error, in case there's an unexpected error or something like that! And the module I had sometimes went unresponsive, so with this I could make it again responsive! Doesn't seem logical, but saved me! Works perfectly for me now!):
public class SMSController
{
public event EventHandler StatusChanged;
protected virtual void OnStatusChanged()
{
if (StatusChanged != null)
{
StatusChanged(this, EventArgs.Empty);
}
}
SerialPort serial;
public SMSController(SerialPort serialPort)
{
this.serial = serialPort;
}
string readLine(int timeout = -1)
{
int oldTo = serial.ReadTimeout;
serial.ReadTimeout = timeout;
string str = serial.ReadTo("\n").Replace("\n", "").Replace("\r", "");
serial.ReadTimeout = oldTo;
return str;
}
void writeLine(string str)
{
serial.Write(str + "\r\n");
}
bool waitForString(string str, int timeout = -1)
{
if (readLine(timeout).Contains(str))
{
return true;
}
return false;
}
bool waitForOK(int timeout = -1, bool repeat = true)
{
if (repeat)
{
readUntilFind("OK", timeout);
return true;
}
else
return waitForString("OK", timeout);
}
void readUntilFind(string str, int timeout = -1)
{
while (!waitForString(str, timeout)) ;
}
void writeCommand(string command)
{
serial.DiscardInBuffer();
writeLine(command);
}
bool applyCommand(string command, int timeout = -1)
{
writeCommand(command);
return waitForOK(timeout);
}
private string lastStatus = "Ready";
public string LastStatus
{
get { return lastStatus; }
private set
{
lastStatus = value;
OnStatusChanged();
}
}
public void InitModule()
{
try
{
LastStatus = "Checking SIM900...";
applyCommand("ATE0", 2000); //Disable echo
applyCommand("AT", 5000); //Check module
LastStatus = "Initializing SIM900...";
applyCommand("AT+CMGF=1", 1000); //Set SMS format to text mode
LastStatus = "Operation successful!";
}
catch (TimeoutException)
{
LastStatus = "Operation timed-out";
}
catch (Exception ex)
{
LastStatus = ex.Message;
}
}
public static string ConvertToUnicodeArray(string str)
{
byte[] byt = Encoding.Unicode.GetBytes(str);
string res = "";
for (int i = 0; i < byt.Length; i+=2)
{
res += byt[i + 1].ToString("X2");
res += byt[i].ToString("X2");
}
return res;
}
public void SendMessage(string destinationNumber, string text, bool isUnicode = false)
{
try
{
LastStatus = "Initiating to send...";
applyCommand("AT+CSMP=17,167,2,25", 1000);
if (isUnicode)
{
if (!applyCommand("AT+CSCS=\"UCS2\"", 5000))
throw new Exception("Operation failed!");
writeCommand("AT+CMGS=\"" + ConvertToUnicodeArray(destinationNumber) + "\"");
}
else
{
if (!applyCommand("AT+CSCS=\"GSM\"", 5000))
throw new Exception("Operation failed!");
writeCommand("AT+CMGS=\"" + destinationNumber + "\"");
}
waitForString("> ", 5000);
LastStatus = "Sending...";
serial.DiscardInBuffer();
serial.Write(isUnicode ? ConvertToUnicodeArray(text) : text);
serial.Write(new byte[] { 0x1A }, 0, 1);
if (waitForOK(30000))
{
LastStatus = "Message sent!";
}
else
LastStatus = "Sending failed!";
}
catch (TimeoutException)
{
LastStatus = "Operation timed-out";
}
catch (Exception ex)
{
LastStatus = ex.Message;
}
}
private string readTo(string str, int timeout)
{
int to = serial.ReadTimeout;
serial.ReadTimeout = timeout;
string strread = serial.ReadTo(str);
serial.ReadTimeout = to;
return strread;
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static string ConvertUnicodeToText(string bytes)
{
byte[] bt = StringToByteArray(bytes);
for (int i = 0; i < bt.Length; i+=2)
{
byte swap = bt[i];
bt[i] = bt[i + 1];
bt[i + 1] = swap;
}
return Encoding.Unicode.GetString(bt);
}
public SMS[] GetUnreadMessages()
{
List<SMS> lst = new List<SMS>();
try
{
LastStatus = "Initializing...";
applyCommand("AT+CSMP=17,167,2,25", 1000);
applyCommand("AT+CSCS=\"UCS2\"", 2000);
LastStatus = "Fetching text messages...";
writeCommand("AT+CMGL=\"REC UNREAD\"");
string texts = readTo("OK\r\n", 10000);
string[] packets = texts.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < packets.Length; i++)
{
if (!packets[i].Contains("+CMGL"))
continue;
string num = packets[i].Split(new string[] { "," },
StringSplitOptions.RemoveEmptyEntries)[2].Replace("\"", "");
string txt = packets[i].Split(new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries)[1].Replace("\"", "");
lst.Add(new SMS(ConvertUnicodeToText(num), ConvertUnicodeToText(txt)));
}
applyCommand("AT+CMGDA=\"DEL READ\"", 10000);
LastStatus = "Operation successful!";
}
catch (TimeoutException)
{
LastStatus = "Operation timed-out";
}
catch (Exception ex)
{
LastStatus = ex.Message;
}
return lst.ToArray();
}
}
Test for a new-line, which typical is \n or \r\n.
A NUL (0 or '\0') is only used in C to terminate a character array, a "string".

core-plot Mixing CPTScatterPlotInterpolationCurved and CPTScatterPlotInterpolationLinear

I need to be able to draw sequential line segments that have the same Y Coordinate with CPTScatterPlotInterpolationLinear and ones that do not with CPTScatterPlotInterpolationCurved.
As CPTScatterPlotInterpolationCurved draws all lines curved. I am currently doing this by adding multiple plots.
public List<CorrectedGraphPoints> GetCorrectDataPoints(List<PointF> dataSource)
{
int lastIndex = 0;
bool shouldLoop = true;
CPTScatterPlotInterpolation interpolation = CPTScatterPlotInterpolation.Curved;
List<CorrectedGraphPoints> OuterList = new List<CorrectedGraphPoints> ();
if (dataSource [0].Y == dataSource [1].Y)
interpolation = CPTScatterPlotInterpolation.Linear;
while (lastIndex+1 != dataSource.Count) {
OuterList.Add (new CorrectedGraphPoints (interpolation));
while (shouldLoop)
{
OuterList[OuterList.Count -1].Add(dataSource[lastIndex]);
if ((lastIndex + 1) < dataSource.Count) {
if (interpolation == CPTScatterPlotInterpolation.Linear) {
if (dataSource [lastIndex].Y != dataSource [lastIndex + 1].Y) {
interpolation = CPTScatterPlotInterpolation.Curved;
shouldLoop = false;
break;
}
}
if (interpolation == CPTScatterPlotInterpolation.Curved) {
if (dataSource [lastIndex].Y == dataSource [lastIndex + 1].Y) {
interpolation = CPTScatterPlotInterpolation.Linear;
shouldLoop = false;
break;
}
}
}
else {
shouldLoop = false;
break;
}
if (shouldLoop)
lastIndex++;
}
shouldLoop = true;
}
return OuterList;
}
public class CorrectedGraphPoints
{
private List<PointF> points;
public List<PointF> Points { get { return points; } }
private CPTScatterPlotInterpolation interpolation;
public CPTScatterPlotInterpolation Interpolation { get { return interpolation; } }
public CorrectedGraphPoints(CPTScatterPlotInterpolation interpolation)
{
this.interpolation = interpolation;
points = new List<PointF> ();
}
public void Add(PointF point)
{
points.Add (point);
}
}
However creating multiple plots that use fill slows the app down tremendously. I was wondering if I could limit how much I do this? I haven't been able to find a way to change the interpolation for a section?? IS this an just an issue with core plot or is it something wrong with my logic or code?
Another possible solution would be to add additional points to your data to draw the curved sections. This would allow you to use only one plot. The number of additional points needed will depend on several factors including the size of the plot and the line style used to draw the line.

Resources