My knowledge about list operations is from scripting languages. So in Java I stopped on something strange in case of finding cookie with particular name.
List<Cookie> cookies = Arrays.asList(request.getCookies());
String auth = cookies.stream()
.filter(c -> c.getName().equals("auth"))
.map(Cookie::getValue);
On the map method IntelliJ is showing me "Cyclic inference".
Java compiler Error:(52, 25) java: incompatible types: no instance(s) of type variable(s) R exist so that java.util.stream.Stream conforms to java.lang.String
Your current code returns a Stream<String>, so you need an extra step to return a string:
Optional<String> auth = cookies.stream()
.filter(c -> c.getName().equals("auth"))
.map(Cookie::getValue)
.findAny();
Note that it returns an Optional<String> because there may be no Cookie that matches "auth". If you want to use a default if "auth" is not found you can use:
String auth = cookies.stream()
.filter(c -> c.getName().equals("auth"))
.map(Cookie::getValue)
.findAny().orElse("");
In essence, what this rather cryptic error message is saying is "the output of the stream sequence doesn't match what you are assigning it to in the end", ex:
String s = list.stream().map(s -> s); // this doesn't result in a String...
.findFirst().get()
So to debug compilation, remove the assignment (temporarily), or, as the other answer says, add something that makes it return a String by collecting (ex: .collect(Collectors.joining(","))) or (getting like .findFirst().get()), or change the assignment, like Stream<String> stream = list.stream().map(...)
Related
In my eclipse plugin I want to support my tool's language which extends C++ with some keywords and concepts. My language class, editor class and source parser class are all inheriting CDT classes for C++. I can parse the keywords and add nodes for them to the AST. But some of my keywords/commands the editor will always mark as "Symbol could not be resolved".
Example:
There is a command "#result" which returns the result of a last computation as an enum value that is defined in some header file in the tool's core.
typedef enum {
OK = 0;
WARNING = 1;
ERROR = 2;
} errCode_t;
So the command #result returns 0, 1 or 2. But inside the editor the command is marked as Symbol '#result' could not be resolved. No I want to tell the Indexer to not try to resolve this very token.
In the Preprocessor class I could change the token type from IToken.tIDENTIFIER to, say, 50000. What I try to achieve by that is something like
if (token.getType() == 50000) {
// don't try to resolve symbol
return null;
} else {
return super.resolveSymbol();
}
Is there a way to do that? I think my first problem is that I don't understand who or what is responsible for the Syntax Error Marking (maybe the Indexer?).
Errors of the form Symbol ... could not be resolved are produced by CDT's Code Analysis component, specifically ProblemBindingChecker, which traverses the AST and reports the error for any IASTName which resolves (via IASTName.resolveBinding()) to a ProblemBinding.
It is only IASTName nodes which resolve to bindings, so if you are getting this error for your #result token, that suggests the parser is building an IASTName node for it. I'm not sure how that's happening if you've changed the token type, I suppose it depends on how you handle the new token type in your extended parser.
Suppose we define a type alias say Message as:
type alias Message a =
{ code : String
, body : a
}
And later define a function readMessage as:
readMessage : Message () -> String
readMessage message =
...
The above example is from Elm tutorial and book says:
This function takes Message with an empty body. This is not the same
as any value, just an empty one.
Can someone please elaborate what exactly happens in above scenario and how compiler handles it.
Unless you really want to see the internal compiler representation of that, I think what's important here is the difference between any value and empty value.
Message a is a parametrized type with 1 parameter. You can read it as a template, e.g. wherever lowercase a appears in the definition of the Message it will be substituted with the concrete type (String, Int, etc).
So this is how function should look like if we want it to take a Message with String body:
readMessage : Message String -> String
readMessage message =
What happens here is that the type of body field is no longer an a but a String (a is substituted with String):
{ code : String
, body : String
}
The value of nothing (aka void or unit) in Elm is encoded as (). That's why a Message with empty body value looks like this:
{ code : String
, body : ()
}
But when we simply don't care about the body value we can just take a Message with any value:
readMessage : Message a -> String
readMessage message =
The lowercase a can be any lowercase string, we can make it more readable like this:
readMessage : Message any -> String
readMessage message =
But then we cannot really read message body, because we don't know the type of it (so we don't know how to read it).
Hope that helps.
The type Message () is an alias for the following record:
{ code : String
, body : ()
}
where the () type denotes a tuple without any items (also known as null tuple). There is only one value of such type and it is also written ().
Now, when we want to omit some field in a record, we cannot just not specify it – that would make the compiler rightly mad, see also The Billion Dollar Mistake. We need to tell the compiler that the value can be omitted.
One way we could do it is to use the Maybe type but if we made a list of messages that would allow us to include the body in some messages and omit it in others. This might not be what we want.
The alternative is to parametrize the Message type as you are doing in the question. This will allow us to have a messages with String bodies when reading the message, and with a different body type when we are not interested in the body.
In this case, we need to consider what the body type should be. While we could use an empty Strings for messages with omitted bodies, they would be easily confused with messages with empty bodies. We could also use Bool but then we would need to decide if we want to use True or False for the omitted value. Finally, we can use the null tuple; since it only has one possible value it is ideal for us.
There is actually one more possibility: we could create a type alias MessageWithoutBody = { code: String }. This is cleaner in some cases (especially when you need to omit more fields) but can be more verbose as you need to duplicate all the fields you want to keep.
So I am trying to do a simple serialization of a lua table, and deserialize it back into a table. But for some reason it just fails.
local a = {}
a[0] = {name="presetA"}
local line = serpent.line(a)
local presets, err = loadstring(line)
if (err) then
log("Error")
log(err)
else
log("Success")
log(serpent.block(presets))
end
After running, log(err) shows
[string "{[0] = {name = "presetA"}}"]:1: unexpected symbol near '{'
loadstring loads a Lua chunk from the given string and runs it.
As your serialized table is not a valid Lua expression the interpreter reports the observed error.
Let's serialze an example:
serpent.line({key = "value"})
returns
"{key = "value"} --[[table: 0D80CF40]]"
A table constructor on it's own is not a valid Lua expression.
Try to run that line and you'll Lua will report:
input:1: unexpected symbol near '{'
The output of serpent.line cannot be used as input to loadstring.
Now see the difference if you use serpent.dump instead
"do local _={name="hallo"};return _;end"
This is a valid, executable Lua chunk that will return the serialized table.
Please note the following section from the serpent documentation:
Note that line and block functions return pretty-printed data
structures and if you want to deserialize them, you need to add return
before running them through loadstring. For example:
loadstring('return '..require('mobdebug').line("foo"))() == "foo".
While you can use loadstring or load functions to load serialized
fragments, Serpent also provides load function that adds safety checks
and reports an error if there is any executable code in the fragment...
Please read manuals.
I read the byte buddy and javassist doc and I would like do not know if is possible to convert a string like:
get foos where name == toto
to
data.getFoos().stream()
.filter( f -> f.name.equals( "toto" ) )
.collect( Collectors.toSet() )
A regex could capture the expression as:
final Pattern query = Pattern.compile("get (\\w+) where (\\w+) ([=!]+) (\\w+)");
final Scanner scanner = new Scanner(System.in);
final Matcher matcher = query.matcher(input);
matcher.group(1) // foos -> Foo and foos -> getFoos()
matcher.group(2) // field to use as filter
matcher.group(3) // symbol == / !=
matcher.group(4) // thing to match
convert get foos to getFoos()
check from Foo class if name field exists
if fields name is not an instance of Number.class translate == to .equals
make the expression
loop and print results
I read some examples without able to found a such thing. So I come here to get your light. thanks
Both Byte Buddy and Javassist generate byte code, not Java code. Javassist does however have functionality to translate String-contained source code to byte code from your inputs. However, the source code level is at Java 4 level such that you cannot use lambdas.
I do however wonder if this is the correct approach for your problem. Rather, I would suggest you to programmatically resolve a stream from the arguments. You could amplify this by creating a custom aPI to transform your arguments into the stream in question.
Two questions.
First,
Below is strong type.
String msg = "Hello world.";
msg = "Hello world again.";
And, below dynamic
var msg = "Hello world.";
msg = "Hello world again.";
Is there any difference between the two 'msg's above?
Second, if I use 'new' keyword to initiate a variable as below,
Map myMap = new Map;
Why to indicate the variable 'myMap' is a Map instance(Map myMap) as 'new' keyword already include the same meaning? So, isn't it okay just,
myMap = new Map;
Because the 'new' keyword already implies the newly initiated variable is both variable and Map type, I can't understand why normally 'Map' keyword is with the variable name, even 'var' also.
Does anyone have any idea about this (seems a little bit redundant) Dart grammar?
In regard to the first question, there will be no difference in what each msg variable contains.
For the Map question, the reason for specifying the type of a variable that is constructed at declaration is to allow some flexibility with subclasses. Take for example the following code:
class SubMap extends Map {
SubMap() : super();
}
Map map = new SubMap();
Here we have a variable map which contains a SubMap object as its value, however we are allowing it to contain values of type Map (or other types which subclass Map) at later times.
The main thing to remember with Dart is that it is optionally typed. When running your code, none of your type annotiations make any difference at all (unless you run in checked mode). What the type annotations are for is to help your IDE and other tools provide autocomplete help, possible warnings, etc. which other fully dynamic languages like Javascript cannot.
String msg = "Hello world.";
msg = "Hello world again.";
msg = 1; // exception in checked mode - int can not be assigned to String.
var msg = "Hello world.";
msg = "Hello world again.";
msg = 1; // ok in checked mode
Checked mode is the developer mode where type annotations are checked and create runtime exceptions when code violates them.
In unchecked (production) mode it makes no difference if you add a type annotation and which one. This is for performance reasons because checked mode is slower.
The declaration Map myMap = new Map() does three things:
it declares a variable named myMap with type-annotation Map,
it creates a new object using the Map constructor, and
it assigns the object to the variable.
The type annotation means that myMap has static type Map. The static type can give you some warnings at compile time, but it doesn't change anything at runtime.
The type annotation also adds a type check in checked mode, where any assignment to the variable is checked for being assignable to Map.
The object you create could be any object using any constructor. I regularly use new HashMap() instead of new Map(), and still assign it to a variable typed as Map.
Then the object is assigned to the variable, and the type check succeeds, if in checked mode.
The variable is independent of the value used to initialize it. If you later assign a string to the myMap variable, it will fail in checked mode.
So, the difference between the two msg variables is that one has a static type and a type check in checked mode.
For the code you show, there is no difference in behavior.
If the next line was var y = msg + 42;, then the typed version would give a warning (msg has static type String, and String.operator+ has type String->String, so the 42 has an invalid argument type), where the untyped version wouldn't warn you (msg has type dynamic so you probably know what you are doing).