I am trying to take an ArrayList of strings and separate it so that i can extract a title from each line.
Here is the contents of the ArrayList:
Tom Sawyer;Twain, Mark;1972;8.50;f;
Leaves of Grass;Whitman, Walt;1975;29.99;p;
Romeo and Juliet;Shakespeare, William;1980;4.99;d;
Great Gatsby;Fitzgerald, F. Scott;1979;5.99;f;
Scarlet Letter;Hawthorne, Nathaniel;1981;4.78;f;
Whisper of the River;Sams, Ferrol;1984;21.95;f;
Moby Dick;Melville, Herman;1962;13.98;f;
Last of the Mohicans;Cooper, James Fenimore;1968;8.75;f;
Odyssey;Homer;1950;9.99;f;
Christmas Carol;Dickens, Charles;1966;12.50;f;
Les Miserables;Hugo, Victor;1988;19.98;f;
Heart of Darkness;Conrad, Joseph;1970;14.45;f;
Animal Farm;Orwell, George;1978;10.00;f;
Canterbury Tales;Chaucer, Geoffrey;1965;20.00;d;
Old Man and the Sea;Hemingway, Ernest;1966;9.95;f;
I need to make a method or something that gets the first part of the line up until the ";".
Here is the code I was using for something similar except this is reading a data file:
while (datascanner.hasNext())
File datafile = new File (data name)
Scanner datascanner = new Scanner(datafile)
String data = datascanner.nextLine()
StringToeknizer dataParser = new StringTokenizer(data, ";")
String title = dataParser.nextToken()
I need something similar to this but instead it searches the arraylist and not the file. I will then extract the other contents on each line:
String author = dataParser.nextToken()
int CopyR = dataParser.nextToken()
and so on...
Just iterate through the list and apply your logic
for(String line : myArrayList)
{
StringTokenizer st = new StringTokenizer(line, ";");
String author = st.nextToken();
//etc.
}
Related
I prepared this small example to show you my problem (vb.net and Newtonsoft)
I would prefer that the solution be done with Newtonsoft.
Public Class Message
Property Emoji As String
End Class
Public Sub GetJson()
Dim msgObject As New Message With {.Emoji = "\uD83D\uDE00"}
'Option 1
Dim JsonSerializerSettings As New JsonSerializerSettings
JsonSerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
Dim msgJson_1 As String = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject, JsonSerializerSettings)
'Option 2
Dim msgJson_2 As String = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject, Newtonsoft.Json.Formatting.None)
'Option 3
Dim stringWriter As New StringWriter()
Using writer As New JsonTextWriter(stringWriter)
writer.Formatting = Formatting.None
Dim serializer As New JsonSerializer()
serializer.Serialize(writer, msgObject)
End Using
Dim msgJson_3 As String = stringWriter.ToString()
End Sub
with none of the three options works, it always results in
{
"Emoji": "\\uD83D\\uDE00"
}
The result I need is
{
"Emoji": "\uD83D\uDE00"
}
How do I set Newtonsoft to not take into account the backslash character, as an escaped character?
Another unorthodox way could be:
jsonString = jsonString.replace("\\","\")
I do not really like
Thanks!!!!
\ is an escape char in JSON hence if you try and serialise a \ it gets escaped as \\ then when you deserialise \\ you get \
My guess is you have been given an example asking you to send "Emoji": "\uD83D\uDE00"
In json (and C#) \u#### specifies a unicode character (usually for something not found on a keyboard) as you are using VB.NET instead you should use $"{ChrW(&HD83D)}{ChrW(&HDE00)}"
"jsonString = jsonString.replace("//","/") " will never work, this is more safe way
json = json.Replace("\\\\u","\\u");
or since you don't like old, good classical solutions
json = Regex.Replace(json, #"\\u", #"u");
//or
json = json.Replace(#"\\u", #"\u");
even this will work in your case ( but I will not recommend for another cases since it is not safe)
json = Regex.Unescape(json);
I am using Lucene.net and am trying to implement a SynonymFilter to provide expanded terms when items within my database of products can be named differently, or spelled differently - e.g. "spanner" > "wrench", or "lawnmower" > "lawn mower".
As a test I setup a SynonymMap as follows :
String base1 = "lawnmower";
String syn1 = "lawn mower";
String base2 = "spanner";
String syn2 = "wrench";
SynonymMap.Builder sb = new SynonymMap.Builder(true);
sb.Add(new CharsRef(base1), new CharsRef(syn1), true);
sb.Add(new CharsRef(base2), new CharsRef(syn2), true);
SynonymMap smap = sb.Build();
Searching for "spanner" or "wrench" brings back all terms with either word in. Searching for "lawn mower" or "lawnmower" only brings back terms that match exactly the input search criteria.
Is there something else that needs to done for multiple word phrases within the Synonyms?
Also how do I expand to say 3 or more terms for for example "lawnmower", "lawn mower", "mower", "grass cutter"?
Thanks
There is an example of multi-word synonyms in the unit tests. You have to split the words yourself and insert a SynonymMap.WORD_SEPARATOR (null character) between them. To make this easier, there is a Join method on SynonymMap.Builder.
String base1 = "lawnmower";
String syn1 = "lawn mower";
SynonymMap.Builder sb = new SynonymMap.Builder(true);
CharsRef syn1Chars = sb.Join(Regex.Split(syn1, " +"), new CharsRef());
sb.Add(new CharsRef(base1), syn1Chars, true);
SynonymMap smap = sb.Build();
Here is an extension method to make quick work of this.
public static class SynonymMapBuilderExtensions
{
private static Regex Space = new Regex(" +", RegexOptions.Compiled);
public static void AddPhrase(this SynonymMap.Builder builder, string input,
string output, bool keepOrig)
{
CharsRef outputRef = builder.Join(Space.Split(output), new CharsRef());
builder.Add(new CharsRef(input), outputRef, keepOrig);
}
}
You can then use this extension method whether the synonym has spaces or not, and you don't have to bother with creating the CharsRef objects if you don't need them anywhere else in your code.
String base1 = "lawnmower";
String syn1 = "lawn mower";
String base2 = "spanner";
String syn2 = "wrench";
SynonymMap.Builder sb = new SynonymMap.Builder(true);
sb.AddPhrase(base1, syn1, true);
sb.AddPhrase(base2, syn2, true);
SynonymMap smap = sb.Build();
I am trying to Import a Csv File into SQL SERVER using SSIS
Here's an example how data looks like
Student_Name,Student_DOB,Student_ID,Student_Notes,Student_Gender,Student_Mother_Name
Joseph Jade,2005-01-01,1,Good listener,Male,Amy
Amy Jade,2006-01-01,1,Good in science,Female,Amy
....
Csv Columns are not containing text qualifiers (quotations)
I Created a simple package using SSIS to import it into SQL but sometime the data in SQL looked like below
Student_Name Student_DOB Student_ID Student_Notes Student_Gender Student_Mother_Name
Ali Jade 2004-01-01 1 Good listener Bad in science Male,Lisa
The Reason was that somtimes [Student_Notes] column contains Comma (,) that is used as column delimiter so the Row are not imported Correctly
Any suggestions
A word of warning: I'm not a regular C# coder.
But anyway this code does the following:
It opens a file called C:\Input.TXT
It searches each line. If the line has more than 5 commas, it takes all the extra commas out of the third last field (notes)
It writes the result to C:\Output.TXT - that's the one you need to actually import
There are many improvements that could be made:
Get file paths from connection managers
Error handling
An experienced C# programmer could probably do this in hlaf the code
Keep in mind your package will need write access to the appropriate folder
public void Main()
{
// Search the file and remove extra commas from the third last field
// Extended from code at
// http://stackoverflow.com/questions/1915632/open-a-file-and-replace-strings-in-c-sharp
// Nick McDermaid
string sInputLine;
string sOutputLine;
string sDelimiter = ",";
String[] sData;
int iIndex;
// open the file for read
using (System.IO.FileStream inputStream = File.OpenRead("C:\\Input.txt"))
{
using (StreamReader inputReader = new StreamReader(inputStream))
{
// open the output file
using (StreamWriter outputWriter = File.AppendText("C:\\Output.txt"))
{
// Read each line
while (null != (sInputLine = inputReader.ReadLine()))
{
// Grab each field out
sData = sInputLine.Split(sDelimiter[0]);
if (sData.Length <= 6)
{
// 6 or less fields - just echo it out
sOutputLine = sInputLine;
}
else
{
// line has more than 6 pieces
// We assume all of the extra commas are in the notes field
// Put the first three fields together
sOutputLine =
sData[0] + sDelimiter +
sData[1] + sDelimiter +
sData[2] + sDelimiter;
// Put the middle notes fields together, excluding the delimiter
for (iIndex=3; iIndex <= sData.Length - 3; iIndex++)
{
sOutputLine = sOutputLine + sData[iIndex] + " ";
}
// Tack on the last two fields
sOutputLine = sOutputLine +
sDelimiter + sData[sData.Length - 2] +
sDelimiter + sData[sData.Length - 1];
}
// We've evaulted the correct line now write it out
outputWriter.WriteLine(sOutputLine);
}
}
}
}
Dts.TaskResult = (int)Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success;
}
In The Flat File Connection Manager. Make the File as only one column (DT_STR 8000)
Just add a script Component in the dataflowtask and Add Output Columns (Same as Example Shown)
in The script component split each row using the following Code:
\\Student_Name,Student_DOB,Student_ID,Student_Notes,Student_Gender,Student_Mother_Name
Dim strCells() as string = Row.Column0.Split(CChar(","))
Row.StudentName = strCells(0)
Row.StudentDOB = strCells(1)
Row.StudentID = strCells(2)
Row.StudentMother = strCells(strCells.Length - 1)
Row.StudentGender = strCells(strCells.Length - 2)
Dim strNotes as String = String.Empty
For int I = 3 To strCells.Length - 3
strNotes &= strCells(I)
Next
Row.StudentNotes = strNotes
it worked fine for me
If import CSV file is not a routine
Import CSV file in Excel
Search error rows with Excel rows filter and rewrite them
Save Excel file in TXT Tab delimited
Import TXT file with SSIS
Else make a script that search comma in the Student Notes column range
I have a docx file which contains a footnote. I have a placeholder in the footnote text that needs to be replaced. While extracting the nodes and modifying the textvalue that placeholder went unpassed. For some reason I think it is not picking up the text provided in the footnote.
Can u please guide me as to how u get to replace a placeholder in the footnote.
Approach 1
faster if you haven't yet caused unmarshalling to occur:
FootnotesPart fp = wordMLPackage.getMainDocumentPart().getFootnotesPart();
fp.variableReplace(mappings);
Approach 2
FootnotesPart fp = wordMLPackage.getMainDocumentPart().getFootnotesPart();
// unmarshallFromTemplate requires string input
String xml = XmlUtils.marshaltoString(fp.getJaxbElement(), true);
// Do it...
Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
// Inject result into docx
fp.setJaxbElement((CTFootnotes) obj);
Since #JasonPlutext's answer did not work for my case I am posting what worked for me
FootnotesPart fp = template.getMainDocumentPart().getFootnotesPart();
List<Object> texts = fp.getJAXBNodesViaXPath("//w:t", true);
for(Object obj : texts) {
Text text = (Text) ((JAXBElement) obj).getValue();
String textValue = text.getValue();
// do variable replacement
text.setValue(textValue);
}
But still I face the issue when exporting this as pdf using Docx4J.toPDF(..);
The output does not pick up the footnote reference.
I have to pass my Json data in a particular format.
My app is coded in vb.
The following is my code :
Dim jsonObject As New Json.JsonObject
jsonObject.Item("count") = New Json.JsonNumber("0")
jsonObject.Item("data") = New Json.JsonArray("")
**jsonObject.Item("success") = New Json.JsonString("True")**
The Problem lies in the line :
jsonObject.Item("success") = New Json.JsonString("True") .
The error message being shown is " Type 'Jayrock.Json.JsonString' has no constructors."
Just to add i have imported the associated libraries .
What should I do to tackle this problem ??
Try simply like this:
Dim jsonObject As New Json.JsonObject
jsonObject.Item("count") = 0
jsonObject.Item("data") = New Json.JsonArray()
jsonObject.Item("success") = "True"
In other words, you can use primitive types like string and integer as values.