Delay output to make it appear as typing? (Java) - string

I hope I can word this properly.
I'm wondering if it is possible to delay the output of letters in a string so it appears as if someone is typing?
I'm currently using JCreator and outputting to the console.
I've used thread.sleep, but this delays the output of the full string.
Any ideas? Let me know if I need to change up the wording.

You need to slice the string and push each character to an array. Then, use for loop to apply your function to each element in your array.
Here's a sample function I made using AS3:
function splitString(str:String):Array{
var arr = [];
for(var i=0;i<str.length;i++){
arr.push(str.substr(i,1));
}
return arr;
}
to apply:
for(var a=0;a<str_split.length;a++){
//trace(str_split[a]);
//apply here your function
}

Related

Change all list items during iteration

Problem
I need to change all list items during a loop. Is it possible?
Code
List<WebElement> elements = driver.findElements(By.xpath('//*[#id="id1"]//tr[td/a]'))
elements.eachWithIndex { element, index ->
...
if(...) {
...
i = index+1
elements = driver.findElements(By.xpath('//*[#id="id1"]//tr[td/a][position()>' + i + ']')) // new list content which must be use by loop
}
}
However, new list is not used by the loop.
Can you help and explain me why?
Thanks
Regards
EDIT 1
I need to retrieve element everytime.
List<WebElement> elements = driver.findElements(By.xpath('//*[#id="dzA26"]//tr[td/a]'))
for(int i = 1; i <= elements.size(); i++) {
WebElement element = driver.findElement(By.xpath('//*[#id="dzA26"]//tr[td/a][' + i + ']'))
...
}
So first of all while iterating over a List, changing or removing elements is not safe to do. It can be possible, but you should avoid it.
That's because you are trying to change the element it is currently iterating at. So the Iterator behind the '.each' closure gets confused and doesn't know where to go on after the current iteration.
If you have to change all elements with the same operation, you could use the List.collect() closure provided by groovy, which will return whatever you like into a new List.
e.g.:
List<WebElement> elements = elements.collect { element ->
return element.doSomething()
}
Edit 1
After your update there is a new Problem, because it seems like you always want to update all Elements int the List.
So why don't you create the List inside the Loop, fill it, and use it, then go to the next iteration.
e.g.:
for(int i = 0;i < threshold; i++) {
List<WebElement> elements = useMethodToRetrieveElementsFori(i);
elements.each {
// Do whatever has to be done with this element.
}
}
Or after looking at it a little longer, it seems obvious to use code reflection at that point. Because you want to dig deeper into the WebElements, you should call a method that calls itself if it needs to go one step further. With your idea, you'd be stuck in an endless loop.
Or we are missing the the whole point of the question.

how to write custom map function in spark?

I have below line which split the words by space and I have map function where I want to pass my custom function to manipulate just for my learning and understanding better
val wordList = dataRdd.flatMap(x=>x.split(" ")).map(x=>(myMap(x)))
def myMap(word:String)
{
if(wordMap.contains(word))
{
var value:Int = wordMap.get(word).get
wordMap+=(word->(value+1))
}else
{
wordMap+=(word->1)
}
}
I have map where I am checking the words and if present I am incrementing by 1 and updating the map
what should be the return type of myMap function, how does the result stored in wordList?
can somebody explain please?
It cannot be done like this (just read Spark Programming Guide about closures).
And the problem you try to solve is just a word count:
dataRdd.flatMap(_.split(" ").map((_, 1L))).reduceByKey(_ + _).collectAsMap

Is good to call function in other function parameter?

I suppose this:
public static string abc()
{
return "abc";
}
Is better to call this function in this way:
string call = abc();
Console.writeline(call);
Than this?
console.writeline(abc());
is there any reason to prefer one to the other?
Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.
For example, this style makes it easy to check the correctness intermediate of an intermediate result:
string call = abc();
assert(!call.empty()); // Just an example.
Console.writeline(call);
Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.
string call = abc();
if (!call.empty())
{
Console.writeline(call);
}
Note also that with this style you will be able to easily inspect the value of call in your debugger.
Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:
int counter;
int Inc() { counter += 1; return counter }
void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
void Bar()
{
Foo(Inc(), Inc());
}
What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.
Actually I don't see a difference if you don't have any error checking.
This would make a difference
string call = abc();
# if call is not empty
{
Console.writeline(call);
}
The above method could avoid empty string being written.

Why does Processing think I'm passing an int into the color() function at the end of this code?

Preface: I'm working with Processing and I've never used Java.
I have this Processing function, designed to find and return the most common color among the pixels of the current image that I'm working on. the last line complains that "The method color(int) in the type PApplet is not applicable for the arguments (String)." What's up?
color getModeColor() {
HashMap colors = new HashMap();
loadPixels();
for (int i=0; i < pixels.length; i++) {
if (colors.containsKey(hex(pixels[i]))) {
colors.put(hex(pixels[i]), (Integer)colors.get(hex(pixels[i])) + 1);
} else {
colors.put(hex(pixels[i]),1);
}
}
String highColor;
int highColorCount = 0;
Iterator i = colors.entrySet().iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
if ((Integer)me.getValue() > highColorCount) {
highColorCount = (Integer)me.getValue();
highColor = (String)me.getKey();
}
}
return color((highColor);
}
The Processing docs that I'm looking at are pretty sparse on the HashMap so I'm not really sure what's going on inside it, but I've been augmenting what's available there with Java docs they point to. But I'm not really grokking what's happening with the types. It looks like the key in the HashMap needs to be a string and the value needs to be an integer, but they come out as objects that I have to cast before using. So I'm not sure whether that's causing this glitch.
Or maybe there's just a problem with color() but the docs say that it'll take a hex value which is what I was trying to use as the key in the HashMap (where I'd rather just use the color itself).
Now that I've talked through this, I'm thinking that the color() function sees the hex value as an int but the hex() function converts a color to a string. And I don't seem to be able to convert that string to an int. I guess I could parse the substrings and reconstruct the color, but there must be some more elegant way to do this that I'm missing. Should I just create a key-value-pair class that'll hold a color and a count and use an arraylist of those?
Thanks in advance for any help or suggestions you can provide!
I'll dig deeper into this, but an initial thought is to employ Java generics so that the compiler will complain about type issues (and you won't get runtime errors):
HashMap<String,Integer> colors = new HashMap<String,Integer>();
So the compiler will know that keys are Strings and elements are Integers. Thus, no casting will be necessary.
I didn't figure it out, but I did work around it. I'm just making my own string from the color components like:
colors.put(red(pixels[i]) + "," + green(pixels[i]) + "," + blue(pixels[i]),1)
and then letting the function drop a color out like this:
String[] colorConstituents = split(highColor, ",");
return color(int(colorConstituents[0]), int(colorConstituents[1]), int(colorConstituents[2]));
This doesn't really seem like the best way to handle it -- if I'm messing with this long-term I guess I'll change it to use an arraylist of objects that hold the color and count, but this works for now.

Best way to build object from delimited string (hopefully not looped case)

this question feels like it would have been asked already, but I've not found anything so here goes...
I have constructor which is handed a string which is delimited. From that string I need to populate an object's instance variables. I can easily split the string by the delimited to give me an array of strings. I know I can simply iterate through the array and set my instance variables using ifs or a switch/case statement based on the current array index - however that just feels a bit nasty. Pseudo code:
String[] tokens = <from generic string tokenizer>;
for (int i = 0;i < tokens.length;i++) {
switch(i) {
case(0): instanceVariableA = tokens[i];
case(1): instanceVarliableB = tokens[i];
...
}
}
Does anyone have any ideas of how I do this better/nicer?
For what it's worth, I'm working in Java, but I guess this is language independant.
Uhm... "nasty" is in the way the constructor handles the parameters. If you can't change that then your code snippet is as good as it may be.
You could get rid of the for loop, though...
instanceVariableA = tokens[0];
instanceVariableB = tokens[1];
and then introduce constants (for readibilty):
instanceVariableA = tokens[VARIABLE_A_INDEX];
instanceVariableB = tokens[VARIABLE_B_INDEX];
NOTE: if you could change the string parameter syntax you could introduce a simple parser and, with a little bit of reflection, handle this thing in a slightly more elegant way:
String inputString = "instanceVariableA=some_stuff|instanceVariableB=some other stuff";
String[] tokens = inputString.split("|");
for (String token : tokens)
{
String[] elements = token.split("=");
String propertyName = tokens[0];
String propertyValue = tokens[1];
invokeSetter(this, propertyName, propertyValue); // TODO write method
}
Could you not use a "for-each" loop to eliminate much of the clutter?
I really think the way you are doing it is fine, and Manrico makes a good suggestion about using constants as well.
Another method would be to create a HashMap with integer keys and string values where the key is the index and the value is the name of the property. You could then use a simple loop and some reflection to set the properties. The reflection part might make this a bit slow, but in another language (say, PHP for example) this would be much cleaner.
just an untested idea,
keep the original token...
String[] tokens = <from generic string tokenizer>;
then create
int instanceVariableA = 0;
int instanceVariableB = 1;
if you need to use it, then just
tokens[instanceVariableA];
hence no more loops, no more VARIABLE_A_INDEX...
maybe JSON might help?
Python-specific solution:
Let's say params = ["instanceVariableA", "instanceVariableB"]. Then:
self.__dict__.update(dict(zip(params, tokens)))
should work; that's roughly equivalent to
for k,v in zip(params, tokens):
setAttr(self, k, v)
depending on the presence/absence of accessors.
In a non-dynamic language, you could accomplish the same effect building a mapping from strings to references/accessors of some kind.
(Also beware that zip stops when either list runs out.)

Resources