I am new to ExtJS. I came across following piece of code:
Ext.String.format('{1}',value+"#abc.com",value);
Now this will create a mailto link. But my query is that how Ext.String.format works and what else can I use it for?
Ext.String.format:
Allows you to define a tokenized string and pass an arbitrary number
of arguments to replace the tokens. Each token must be unique, and
must increment in the format {0}, {1}, etc.
You can look at the source of the function and see it uses the formatRe regex (/\{(\d+)\}/g):
format: function(format) {
var args = Ext.Array.toArray(arguments, 1);
return format.replace(formatRe, function(m, i) {
return args[i];
});
}
Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each token must be unique, and must increment in the format {0}, {1}, etc.
The following Ext.String.format is modified to accept formatters functions (Ext.util.Format)
e.g.
alert(Ext.String.format("{0} {1:usMoney} {2:date('Y-m-d')}", 10, 20, new Date()));
Here is modified code
Code:
Ext.String._formatRe = /{(\d+)(?:\:([\w.])(?:((.?)?))?)?}/g;
Ext.String._argRe = /(['"])(.?)\1\s(?:,|$)/g
Ext.String.format = function(format) {
var args = Ext.Array.toArray(arguments, 1),
fm = Ext.util.Format;
return format.replace(Ext.String._formatRe, function(m, idx, fn, fmArgs) {
var replaceValue = args[parseInt(idx, 10)],
values,
match;
if (fn) {
values = [replaceValue];
while (match = Ext.String._argRe.exec(fmArgs)) {
values.push(match[2]);
}
return fm[fn].apply(fm, values);
}
return replaceValue;
});
};
Related
this is the problem
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
myCode
class Solution {
fun isPalindrome(s:String):Boolean {
var s1 = s.toLowerCase()
var myStringBuilder = StringBuilder()
var n = s1.length-1
var n1=myStringBuilder.length
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
for( i in 0 .. (n1/2)-1){
if(myStringBuilder[i] != myStringBuilder[n1-i-1]){
return false
}
}
return true
}
}
the first case passed
but this is not passed as per the result Input: s = "race a car result true expected is false
You're initialising n1 too early:
// create an -empty- StringBuilder
var myStringBuilder = StringBuilder()
...
// since it's empty, n1 == 0
var n1=myStringBuilder.length
You're setting it to the length of the StringBuilder contents before you've actually put anything in it. This is a simple value you're setting, it's not a reference to the length getter that will give the current value when you access it. You set it once and that's its value forever.
So your last loop, the one that checks if it's a palindrome or not, never actually runs:
// since n1 is 0, this is for (i in 0..0)
for( i in 0 .. (n1/2)-1){
You can fix it by initialising n1 when you've finished adding your content to the StringBuilder, so you can get its final length:
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
// StringBuilder is complete, grab its final length
var n1 = myStringBuilder.length
// now you can use it
for (i in 0..(n1/2)-1) {
Just fyi, there's also an until operator that works like .. except it doesn't include the last value of the range. So you can write
for (i in 0 until (n1/2))
if you want!
You can use this simple solution.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
for (i in 0..str.length/2 ){
if (str[i]!=str[str.length-i-1])
return false
}
return true
}
Edit:
By the #cactustictacs comment, you can do this in much more simple way.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
return str == str.reversed()
}
I'm using Lucene.NET 4.8-beta00005.
I have a "name" field in my documents defined as follows:
doc.Add(CreateField(NameField, entry.Name.ToLower()));
writer.AddDocument(doc);
Where CreateField is implemented as follows
private static Field CreateField(string fieldName, string fieldValue)
{
return new Field(fieldName, fieldValue, new FieldType() {IsIndexed = true, IsStored = true, IsTokenized = true, StoreTermVectors = true, StoreTermVectorPositions = true, StoreTermVectorOffsets = true, StoreTermVectorPayloads = true});
}
The "name" field is assigned a StandardAnalyzer.
Then in my CustomScoreProvider I'm retriving the terms from the term vector as follows:
private List<string> GetDocumentTerms(int doc, string fieldName)
{
var indexReader = m_context.Reader;
var termVector = indexReader.GetTermVector(doc, fieldName);
var termsEnum = termVector.GetIterator(null);
BytesRef termBytesRef;
termBytesRef = termsEnum.Next();
var documentTerms = new List<string>();
while (termBytesRef != null)
{
//removing trailing \0 (padded to 16 bytes)
var termText = Encoding.Default.GetString(termBytesRef.Bytes).Replace("\0", "");
documentTerms.Add(termText);
termBytesRef = termsEnum.Next();
}
return documentTerms;
}
Now I have a document where the value of the "name" field is "dan gertler diamonds ltd."
So the terms from the term vector I'm expecting are:
dan gertler diamonds ltd
But my GetDocumentTerms gives me the following terms:
dan diamonds gertlers ltdtlers
I'm using as StandardAnalyzer with the field so I'm not expecting it to do much transformation to the orignal words in the field (and I did check with this particular name and StandardAnalyzer).
What am I doing wrong here and how to fix it?
Edit: I'm extracing the terms manually with each field's Analyzer and stroing the them in a separate String field as a workaroud for now.
If you want to get the terms in correct order, you must also use the positional information. Test this code:
Terms terms = indexReader.GetTermVector(doc, fieldName);
if (terms != null)
{
var termIterator = terms.GetIterator(null);
BytesRef bytestring;
var documentTerms = new List<Tuple<int, string>>();
while ((bytestring = termIterator.Next()) != null)
{
var docsAndPositions = termIterator.DocsAndPositions(null, null, DocsAndPositionsFlags.OFFSETS);
docsAndPositions.NextDoc();
int position;
for(int left = docsAndPositions.Freq; left > 0; left--)
{
position = docsAndPositions.NextPosition();
documentTerms.Add(new Tuple<int, string>(position, bytestring.Utf8ToString()));
}
}
documentTerms.Sort((word1, word2) => word1.Item1.CompareTo(word2.Item1));
foreach (var word in documentTerms)
{
Console.WriteLine("{0} {1} {2}", fieldName, word.Item1, word.Item2);
}
}
This code also handles the situation where you have the same term (word) in more than one place.
How to substring method in React native? I tried all methods which are given below but none of the method worked.
substring, slice, substr
The substring method is applied to a string object.
The substring() method extracts the characters from a string, between two specified indices, and returns the new substring.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
If "start" is greater than "end", this method will swap the two arguments, meaning str.substring(1, 4) == str.substring(4, 1).
If either "start" or "end" is less than 0, it is treated as if it were 0.
Note: The substring() method does not change the original string.
The way to use it is this:
var str = "Hello world!";
var res = str.substring(1, 4);
// res value is "ell"
https://www.w3schools.com/jsref/jsref_substring.asp
You can use it :
var str = "Hello world!";
var res = str.substring(0, 4); // output is Hello
if you get from JSON
{item.name.substring(0, 4)}
from text
this is text.substring(0, 5) // output is: this i
Method 1: With Variables
var str = "Demo String";
var res = str.substring(2, 5); //starts from 0
Method 2: With States Directly
<Text>{this.state.str.substring(0, 7)}</Text>
try
(obj.str).substring(1, 4);
Another alternative, you can make simple function. and then print in your jsx.
var number = "62857123456"
const slice = {
phone: (input: string = '') => {
let output = '';
// you can use substring, slice, substr
output = input.slice(2,14);
return output;
},
};
Finally, print on your jsx by calling the function that was created.
{slice.phone(number)}
I have faced the same situation For this the solution is place all js code in a function and call it externally
class AboutMe extends Component {
displayAboutMe(){
var data = this.props.getAboutMeQuery;
if(data.loading){
return(<div>Loading Books</div>)
}else{
var aboutMe = JSON.stringify(this.props.getAboutMeQuery.aboutme);
console.log(aboutMe);
var res = aboutMe.substring(12,453);
console.log(res);
}
}
render(){
this.displayAboutMe()
return (
<div id="profile-section"></div>
)}}
I have been trying to fill up a word template(.docx) file which has placeholders which needs to be replaced.
I was able to rewrite the template but the text does not come with line breaks
I understand that carriage return or new line (\r\n) does not work in .docx files. I used the VariableReplace method to convert but I was unable to place br or factory.createBr() while using the variable replace.
Any suggestions would be really helpful. Below is the piece of code what i tried
Map<String,String> variableReplaceMap = new HashMap<>();
Map<String, String> textContent = readTextContentAfterDBExtractionToFillUpTemplate();
ObjectFactory factory = Context.getWmlObjectFactory();
P para = factory.createP();
R rspc = factory.createR();
String power= textContent.get("Power & Energy");
String[] powerWithNewLine = skills.split("\\\\n");
for (String eachLineOfPower : powerWithNewLine) {
Text eachLineOfPowerTxt = factory.createText();
eachLineOfPowerTxt .setValue( eachLineOfPower );
rspc.getContent().add( eachLineOfPowerTxt );
Br br = factory.createBr();
rspc.getContent().add(br);
para.getParagraphContent().add(rspc);
documentPart.addObject(para);
}
String str = "";
for (Object eachLineOfPgrph : para.getParagraphContent()) {
str = str + eachLineOfPgrph;
}
variableReplaceMap.put("POWER", str);
return variableReplaceMap;
The link from Jason is dead.
Here is the current link: https://github.com/plutext/docx4j/blob/master/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/VariableReplace.java
In case it gets changed in the future, simply use the following function and apply it to your string, that contains linebreaks:
/**
* Hack to convert a new line character into w:br.
* If you need this sort of thing, consider using
* OpenDoPE content control data binding instead.
*
* #param r
* #return
*/
private static String newlineToBreakHack(String r) {
StringTokenizer st = new StringTokenizer(r, "\n\r\f"); // tokenize on the newline character, the carriage-return character, and the form-feed character
StringBuilder sb = new StringBuilder();
boolean firsttoken = true;
while (st.hasMoreTokens()) {
String line = (String) st.nextToken();
if (firsttoken) {
firsttoken = false;
} else {
sb.append("</w:t><w:br/><w:t>");
}
sb.append(line);
}
return sb.toString();
}
See newlineToBreakHack method at https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/VariableReplace.java#L122
I'm looking to find the last line of a text file using a rather standard while-loop idiom I find often used in Java.
I have a less compact version working. But the one I would like to use does not appear to be valid syntax in Kotlin. My preferred method includes an assignment and a Boolean test on that assignment in the same line.
Admittedly this is a small matter, but I'm looking to better implement my Kotlin code.
fun readLastLine(file:File):String {
val bufferedReader = file.bufferedReader()
var lastLine=""
//valid
var current = bufferedReader.readLine()
while(current != null) {
lastLine=current
current = bufferedReader.readLine()
}
//return lastLine
//not valid...
//while((current=bufferedReader.readLine())!=null){
// lastLine=current
//}
//responding to comment below,
//preferred/terse answer using file.readLines
//this reads all the lines into a list, then returns the last
return file.readLines().last()
}
In Kotlin, an assignment is not an expression whose value is equal to the assigned value.
You can combine two statements using run function in Kotlin. This function returns the value of the the last expression.
var current = ""
while (run {
current = bufferedReader.readLine()
current != null
}) { // or while (run { current = bufferedReader.readLine(); current != null }) {
lastLine = current
}
However, you can further reduce the code using File.forEachLine() in Kotlin.
fun readLastLine(file: File): String {
var lastLine = ""
file.forEachLine { line ->
lastLine = line
}
return lastLine
}
Or shorter,
fun readLastLine(file: File): String {
var lastLine = ""
file.forEachLine { lastLine = it }
return lastLine
}
This uses BufferedReader and closes automatically internally: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/for-each-line.html