How to resolve dangling ${ when using StringSubstitutor? - apache-commons-text

Test Case
// Build map
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped ${ over the ${target}.%";
// Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap);
// Replace
String resolvedString = sub.replace(templateString);
assertThat( resolvedString, is( "The quick brown fox jumped ${ over the lazy dog.%" ) );
The Failure
${target} variable is not being replaced:
java.lang.AssertionError:
Expected: is "The quick brown fox jumped ${ over the lazy dog.%"
but: was "The quick brown fox jumped ${ over the ${target}.%"

https://commons.apache.org/proper/commons-text/apidocs/org/apache/commons/text/StringSubstitutor.html#setEscapeChar-char-
Appears there is support for some recursive processing of variables but would need to otherwise use an escape char to indicate the first ${ isn't the beginning of a variable evaluation I think.

Related

What causing this error Immer only supports setting array indices and the 'length' property

I am new to redux. I am now going to select movies to be pinned to another page. I can passed the id selected to the reducer. Then i will change the one of the variable so that it can be display on the other page. Once I checked the checkbox, I encounter this problem
My reducer
showSelectedPinnedMovie: function(state,action){
alert(action.payload);
if(action.payload) {
state.count++
state.movieId.push(action.payload)
};
if(state.count >= 6){
alert("You cannot pinned more than 5")
}
for(let c=0; c < state.value.length; c++ ){
state.value.selecttobepinned = false;
}
for(let i=0; i< state.value.length; i++ ){
for(let c=0; c< state.selectedPinnedId.length; c++){
if(state.value[i].id !== state.selectedPinnedId[c]){
return Object.assign({},state.value[i],{ "selecttobepinned" : true});
}
}
return state.value;
}
for(let i=0; i< state.value.length; i++ ){
for(let c=0; c< state.selectedPinnedId.length; c++){
if(state.value[i].id === state.selectedPinnedId[c]){
return Object.assign({},state.value[i],{ "selecttobepinned" : true});
}
}
return state.value;
}
state.count =0;
state.selectedPinnedId = [];
},
My initial data
initialState: {
value: [
{ "id": 1,"movie name" : "Ticket to Paradise","display":true,"description":"Academy Award® winners George Clooney and Julia Roberts reunite on the big screen as exes who find themselves on a shared mission to stop their lovestruck daughter from making the same mistake they once made","genre" :"Comedy", "lead actor": ["George Clooney", "Julia Roberts"],"rating":5,"displayOneMovie":false,"selecttobepinned":false,"language":"english"},
{ "id": 2, "movie name": "Black Panter","display":true,"description":"Queen Ramonda (Angela Bassett), Shuri (Letitia Wright), M’Baku (Winston Duke), Okoye (Danai Gurira) and the Dora Milaje (including Florence Kasumba), fight to protect their nation from intervening world powers in the wake of King T’Challa’s death.","genre":"Action","lead actor":["Angela Bassett","Letitia Wright"],"rating":6,"displayOneMovie":false,"selecttobepinned":false,"language":"english"},
{ "id":3, "movie name": "Smile","display":true,"description":"After witnessing a bizarre, traumatic incident involving a patient, Dr. Rose Cotter (Sosie Bacon) starts experiencing frightening occurrences that she can't explain.","genre":"Drama","lead actor":["Sosie Bacon","Jessie T. Usher"],"rating":6,"displayOneMovie":false,"selecttobepinned":false,"language":"english"},
{"id":4,"movie name":"Come Back Home","display":true,"description":"In the cold winter, a group of Shenzhen tourist families take a trip to the northeast Changbai Mountain. It was originally intended to be a happy and harmonious holiday, but due to the negligence of his father, an 8-year-old boy is unfortunately lost.","genre":"Mistery","lead actor":["Donnie Yen", "Han Xue"],"rating":6,"displayOneMovie":false,"selecttobepinned":false,"language":"mandarian"},
{"id":5,"movie name":"Ajoomma","display":true,"description":"Auntie (Hong Huifang), is a middle-aged Singaporean woman who has dedicated the best years of her life to caring for her family. Now widowed with her grown up son, Sam (Shane Pow) about to fly the roost, Auntie is left to contend with a whole new identity beyond her roles of daughter, wife, and mother.","genre":"Drama","lead actor":["Hong Huifang", "Jung Dong-Hwan"],"rating":4,"displayOneMovie":false,"selecttobepinned":false,"language":"mandarian"},
{"id":6,"movie name":"The King Of Musang King","display":true,"description":"Mao Shan (Jack Neo) is an ambitious durian farmer who wishes to expand his sales overseas, against pressures from the “Three Heavenly Kings” of the business. He helps Mei Lian (Yeo Yann Yann), his neighbour and sole supporter, to improve her durian farm harvests, and develops feelings for her in the process.","genre":"Comedy","lead actor":["Mark Lee","Henry Thia"],"rating":4,"displayOneMovie":false,"selecttobepinned":false,"language":"mandarian"}
],
movieId: [],
count: 0,// No records initially
},
I don't know whether I am updateing the state correctly. Can anyone solve this problem for me?

scala console error when testing sample IO using zio

Hi I've below ZIO ConsoleIO test.
import zio._
import zio.Console
import zio.test.Assertion.equalTo
import zio.test._
object ConsoleIOSpec extends ZIOSpecDefault {
val greet: ZIO[Any, Nothing, Unit] = for {
name <- Console.readLine.orDie
_ <- Console.printLine(s"Hello, $name").orDie
} yield ()
def spec = suite("ExampleSpec")(
test("greet says hello to the user") {
for {
_ <- TestConsole.feedLines("Jack")
_ <- greet
value <- TestConsole.output
} yield assert(value) (equalTo(Vector("Hello, Jack")))
}
)
}
The code is on this github here. When I run the test I get the below error -
ExampleSpec / greet says hello to the user
✗ Vector1("Hello, Jack
") was not equal to Vector1("Hello, Jack")
value did not satisfy equalTo(Vector("Hello, Jack"))
value = Vector1("Hello, Jack
")
at /Users/rnatarajan/Documents/Coding/others/zionomicon/c2-testing/src/test/scala/ConsoleIOSpec.scala:18
Output Produced by Test
| Jack
| Hello, Jack
I've attached the error screenshot -
This is code from zionomicon book section 3.3 Test Implementations Of Standard ZIO Services.
How to fix this issue?
Method "Console.printLine" prints the string in parameter, and a carriage return at the end of it, as you can see with the double quotes in a new line.
To fix the problem, you can replace "Console.printLine" with "Console.print", or take into account the return carriage at the end of the output.

Unable to get NSEnumerator to display next item in my array

I am new to Objective-C and I have researched this online for weeks now. Almost every example is the same on every site and does not fully make it clear to me how to integrate it into my code for an Xcode 4 App.
The example seen everywhere is:
NSEnumerator* theEnum = [some_array objectEnumerator];
id obj; or id some_object = NULL;
while(obj = [theEnum nextObject]) {
//do something...
I think if I better understood what id some_object = NULL;/ id obj; represents I could figure it out on my own.
In my code I have three arrays. I want to be able to display one object in each array in a UILabel field every time the user clicks the Next button until all of them have been displayed.
NSArray1 = 1,2,3
NSArray2 = John, Jill, Josh
NSArray3 = boy, girl, boy
When the next button is pushed you would see 1, John and boy. The next time you would see 2, Jill and girl and finally 3, Josh and boy.
Below is basic example, not my actually code.
number = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
name = [[NSArray alloc] initWithObjects:#"John",#"Jill",#"Josh", nil];
gender = [[NSArray alloc] initWithObjects:#"boy",#"girl",#"boy", nil];
NSEnumerator *enum = [number objectEnumerator];
id obj; (??What is this?? And how to connect to the statement below??)
while ((obj = [enumNumber nextObject])) {
self.numberItem.text = ??
self.nameItem.text = ??
self.genderItem.text = ??
Thanks
id obj is just the variable containing the current variable you're looking at. In this code, since your NSArrays all contain string, you could use NSString *obj instead.
An enumerator can only enumerate one collection at a time. If you want to loop through all three of them together, use a traditional for loop:
for(unsigned int i = 0; i < number.count; i++) {
self.numberItem.text = [number objectAtIndex:i];
self.nameItem.text = [name objectAtIndex:i];
self.genderItem.text = [gender objectAtIndex:i];
}

regexp not working...arghhhh

I'm using Flex 4. I'm driving myself crazy. Why won't the following work?
// in my Application tag:
creationComplete="replaceMe(event)"
// in my script block:
public function replaceMe(event:Event):void{
var str:String = "She sells seashells by the seashore.";
var pattern:RegExp = /sh/gi;
str.replace(pattern, "sch");
test.text = str;
}
my text area (id="test") says "She sells seashells by the seashore."...
it should say "sche sells seaschells by the seaschore."
Because Strings are immutable objects. So, str.replace() just returns new string, without modifying str. Try
str = str.replace(pattern, "sch")
Assign the new string value back to the old string like so:
str = str.replace(pattern, "sch");
Edit: Dzmitry answered first. =P

Function to convert "camel case" type text to text with spaces in between? ie: HelloWorld --> Hello World

Anyone know of a nice efficient function that could convert, for example:
HelloWorld --> Hello World
helloWorld --> Hello World
Hello_World --> Hello World
hello_World --> Hello World
It would be nice to be able to handle all these situations.
Preferably in in VB.Net, or C#.
I don´t know if this is the most efficient way. But this method works fine:
EDIT 1: I have include Char.IsUpper suggestion in the comments
EDIT 2: included another suggestion in the comments: ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. foreach (char character in input)
EDIT 3: I've used StringBuilder, like #Dan commented.
public string CamelCaseToTextWithSpaces(string input)
{
StringBuilder output = new StringBuilder();
input = input.Replace("_", "");
foreach (char character in input)
{
if (char.IsUpper(character))
{
output.Append(' ');
}
if (output.Length == 0)
{
// The first letter must be always UpperCase
output.Append(Char.ToUpper(character));
}
else
{
output.Append(character);
}
}
return output.ToString().Trim();
}
There are some other possibilities you might want to cater for - for instance, you probably don't want to add spaces to abbreviations/acronyms.
I'd recommend using:
Private CamelCaseConverter As Regex = New Regex("(?<char1>[0-9a-z])(?<char2>[A-Z])", RegexOptions.Compiled + RegexOptions.CultureInvariant)
Public Function CamelCaseToWords(CamelCaseString As String) As String
Return CamelCaseConverter.Replace(CamelCaseString, "${char1} ${char2}")
End Function
'Gives:
'CamelCase => Camel Case
'PIN => PIN
What it doesn't do is uppercase the first letter of the first word, but you can look at the other examples for ways of doing that, or maybe someone can come up with a clever RegEx way of doing it.
Sounded fun so I coded it the most important part is the regex take a look at this site for more documentation.
private static string BreakUpCamelCase(string s)
{
MatchCollection MC = Regex.Matches(s, #"[0-9a-z][A-Z]");
int LastMatch = 0;
System.Text.StringBuilder SB = new StringBuilder();
foreach (Match M in MC)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch, M.Index + 1 - LastMatch));
LastMatch = M.Index + 1;
}
if (LastMatch < s.Length)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch));
}
return SB.ToString();
}

Resources