I have an old X10 example in class which I'm trying to compile.
import x10.array.Array;
import x10.io.Console;
...
public static def main(args: Array[String](1)) {
val regionTest = 1..12;
val testArray = new Array[Int](1..12, (Point)=>0);
for ([i] in testArray) {
testArray(i) = i;
Console.OUT.println("testArray("+i+") = " + testArray(i));
}
}
Unfortunately it seems to be outdated. I could figure out by myself that you have to write public static def main(args:Rail[String]) now. The definition of val regionTest = 1..12 seems to be ok. The syntax for the array must be wrong, all following lines maybe too. I tried to fix this with this guide, but did not succeed.
My setup is working, the initial class in a new X10 Eclipse IDE project runs.
Could somebody help me port this to version 2.5.x?
There were a number of non-backward-compatible changes in X10 version 2.4, which require code changes - see the guide to "porting to X10 2.4".
Your example would be updated as follows:
import x10.regionarray.Array;
import x10.regionarray.Region;
import x10.io.Console;
....
public static def main(args:Rail[String]) {
val regionTest = Region.makeRectangular(1..12);
val testArray = new Array[Int](regionTest, (Point)=>0n);
for ([i] in testArray) {
testArray(i) = i as Int;
Console.OUT.println("testArray("+i+") = " + testArray(i));
}
}
This demonstrates a number of important changes:
(Lines 1--2) The general-purpose array classes have moved from the x10.array package to x10.regionarray. These classes are no longer imported by default.
(Lines 6--7) There is no implicit type conversion from LongRange (1..12) to Region. A Region object must be explicitly constructed and passed to the x10.regionarray.Array constructor.
(Line 7) The default integral type is now Long instead of Int. An Int literal must be suffixed with the character 'n' as in '(Point)=>0n'.
(Lines 8--9) The index type for array classes has changed from Int to Long (to support very large data structures). Therefore the exploded Point iterator for ([i] in testArray) now yields i:Long instead of i:Int - which means the cast i as Int is now required when assigning to an Int array element on line 9.
Related
How should I know without using another condition to compare the map.size() with limitValue, that the limit was exceeding when my stream iterated?
Here,
for limitValue = 3, it should return false.
for limitValue = 4, it should return true.
I can not use an outside int field as it must be final to be used inside lambda.
import java.util.*;
import java.util.stream.*;
public class Test {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "foo");
map.put(2, "bar");
map.put(3, "baz");
int limitValue = 3;
String result = map.entrySet()
.stream()
.limit(limitValue)
.map(entry -> entry.getKey() + " - " + entry.getValue())
.collect(Collectors.joining(", "));
System.out.println(result);
}
}
I can not use an outside int field as it must be final to be used
inside lambda.
Yes, this is because, within a lambda expression, you can only reference local variables whose value doesn’t change (in java).
This is a good thing in a way as mutating a variable(s) inside a lambda is not thread safe when executing in parallel.
So, the system is helping you prevent such scenarios at compile time by allowing only final or effectively final variables to be used in lambdas.
Note, this restriction only holds for local variables.
Anyhow, my advice is not to mutate variables that are not solely contained within a given function itself as it introduces a side-effect and side-effects in behavioral parameters to stream operations are, in general, discouraged.
Keep things simple and proceed with the below approach.
boolean exceeded = limitValue > map.size();
The comments on the stemStatic method of the Morphology class state that it will:
return a new WordTag which has the lemma as the value of word().
The default is to lowercase non-proper-nouns, unless options have
been set.
(https://github.com/evandrix/stanford-corenlp/blob/master/src/edu/stanford/nlp/process/Morphology.java)
How/where can I set those options, to disable the lowercase conversion?
I've looked through the source but can't see how I can set options that will affect this static method. Frustratingly, the related static lemmatise method -- lemmaStatic -- includes a boolean parameter to do exactly this...
I'm using v3.3.1 via Maven...
thanks!
Ok after looking at this for a bit, it seems the right track might be to not use the static method, but instead build a Morphology instance with:
public Morphology(Reader in, int flags) {
The int flags will set the lexer.options.
Here are the lexer options (from Morpha.java) :
/** If this option is set, print the word affix after a + character */
private final static int print_affixes = 0;
/** If this option is set, lowercase all tokens */
private final static int change_case = 1;
/** Return the tags on the input words if present?? */
private final static int tag_output= 2;
The int flags is the bit string for the 3 options, so 7 = 111 , meaning all options will be set to true , 0 = 000 , all options false, 5 = 101 would set print_affixes and tag_output, etc...
Then you can use apply in Morphology.java
public Object apply(Object in) {
Object in should be a WordTag built with the original word and tag.
Please let me know if you need any further assistance!
We could also change Morphology.java to have the kind of method you want! The above is if you don't want to play around with customizing Stanford CoreNLP.
In Ruby I often like to handle null values from collections with the following function:
def nilstuff(a,stuff="")
if(a.nil?)
return stuff
else
return a
end
end
In Scala there is an annoyance that empty values in collections throw exceptions, not nil:
val myMap = Map[String, String]()
myMap += ("Apple" -> "Plant")
myMap += ("Walrus" -> "Animal")
println(myMap("Elephant"))
//Exception in thread "main" java.lang.ExceptionInInitializerError
// at MyProgram.main(MyProgram.scala)
//Caused by: java.util.NoSuchElementException: key not found: Elephant
Is there a way to make a similar function in Scala that handles exceptions and returns the "stuff" instead?
println(missing_stuff(myMap("Elephant"),"Unknown"))
You can add a default value to your Map:
scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map
scala> val myMap = Map[String, String]().withDefaultValue("Unknown")
myMap: scala.collection.mutable.Map[String,String] = Map()
scala> myMap("foo")
res0: String = Unknown
Another option is the getOrElse method of Map.
Or apply a pattern match to the result of get:
myMap.get("foo") match {
case Some(value) => useAsDesired(value)
case None => useAsDesired("Unknown")
}
The last might be the most general solution to what your title calls "Clean exception handling."
There are several ways built in.
(1) Don't get the value, get an option.
myMap.get("Elephant")
Now that you have an Option, you can do all sorts of things with it (including get either its contents or a default value if there is none):
myMap.get("Elephant").getOrElse("")
(2) Get the value, or a default value if it's not there
myMap.getOrElse("Elephant", "")
(3) Create the map with a default value (warning--this will not survive filtering, mapping, or any other handy collections operations). Immutably you'd add this after you were done building the map:
val defaultMap = myMap.withDefault(_ => "")
defaultMap("Elephant")
With a mutable map, you might add it at the beginning:
val myMap = new collection.mutable.HashMap[String,String].withDefaultValue("")
(4) Add the item that you're missing when you find it not there (mutable maps only):
myMap.getOrElseUpdate("Elephant", "Dumbo")
Probably not what you want in this particular case, but often useful.
I've been using JoSQL for quite a few months now and today I came across a problem I am not sure how to solve. I probably could solve it by binding variables/placeholders, but I'd like to include the fields in the query.
SELECT * FROM ...MyObject WHERE getType != com.mypackage.myclass.TYPE_A
This is the query that I have. TYPE_A is a public static final int attribute in "myclass" class. Accessing methods (such as getType) is easy, because getType is expected to be a method from MyObject - just that I do not write round brackets after it (this is how JoSQL works as far as I know).
Does anyone happen to have an idea how to access a public static final field?
JoSQL uses gentlyweb-utils; it seems to be some sort of Accessor/Getter/Setter framework. I'd love to access that attribute without having to bind variables, but I haven't been able to do so.
Thanks for your help in advance! I really appreciate it.
I think I have figured something out. First: it seems not possible to access the static variables for whatever reason. I've used the following approach to solve my issue:
create a method, which picks up a given JoSQL-statement
mark the constants, which you want to replace, by say "{?FULL_PACKAGE_AND$CONSTANT}"
use reflections to determine the column as well as the column (and value) from the field
iteratively replace the statement until no "{?"-values are available
Example:
JoSQL-statement looks like this:
(isWeapon = TRUE AND getItem.getType2 = {?com.l2jserver.gameserver.model.items.L2Item$TYPE2_WEAPON})
Method using the query-object:
final Query query = DataLayer.createJoSqlQuery(joSql);
Method (pre)processing the JoSQL-statement:
final Query query = new Query();
int variableColumn = 0;
while (joSql.indexOf("{?") > -1) {
variableColumn++;
final int startIndex = joSql.indexOf("{?");
final int endIndex = joSql.indexOf("}", startIndex);
final String value = joSql.substring(startIndex + 2, endIndex);
try {
final Object variableValue = Class.forName(value.split("\\$")[0]).getField(value.split("\\$")[1]).get(null);
query.setVariable(variableColumn, variableValue);
joSql = joSql.replace("{?" + value + "}", "?");
}
catch (...) {
e.printStackTrace();
}
}
query.parse(joSql);
return query;
The JoSQL-statement preprocessing method bascially iterates through a given JoSQL-statement and sees whether it contains the string "{?". If it does, it does some copy and paste (note the dollar-symbol right in front of the constant name).
Finally it creates the objects and sets them using something similar to prepared statements "setObject"-method. In the end it just replaces the values within the JoSQL-statement with question marks ("?") and sets a corresponding object in the newly created Query-object, which is later used to retrieve information.
I'm working on a definitions file for the Google maps API for TypeScript.
And I need to define an enum like type eg. google.maps.Animation which contains two properties: BOUNCE and DROP.
How should this be done in TypeScript?
TypeScript 0.9+ has a specification for enums:
enum AnimationType {
BOUNCE,
DROP,
}
The final comma is optional.
As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:
enum TShirtSize {
Small,
Medium,
Large
}
var mySize = TShirtSize.Large;
By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.
Listing 6.2 Enumerations with explicit members
enum TShirtSize {
Small = 3,
Medium = 5,
Large = 8
}
var mySize = TShirtSize.Large;
Both of these examples lifted directly out of TypeScript for JavaScript Programmers.
Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:
Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.
enum TShirtSize {
Small: 3,
Medium: 5,
Large: 8
}
var mySize = TShirtSize.Large;
This is now part of the language. See TypeScriptLang.org > Basic Types > enum for the documentation on this. An excerpt from the documentation on how to use these enums:
enum Color {Red, Green, Blue};
var c: Color = Color.Green;
Or with manual backing numbers:
enum Color {Red = 1, Green = 2, Blue = 4};
var c: Color = Color.Green;
You can also go back to the enum name by using for example Color[2].
Here's an example of how this all goes together:
module myModule {
export enum Color {Red, Green, Blue};
export class MyClass {
myColor: Color;
constructor() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
}
}
var foo = new myModule.MyClass();
This will log:
undefined
2
Blue
Because, at the time of writing this, the Typescript Playground will generate this code:
var myModule;
(function (myModule) {
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(myModule.Color || (myModule.Color = {}));
var Color = myModule.Color;
;
var MyClass = (function () {
function MyClass() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
return MyClass;
})();
myModule.MyClass = MyClass;
})(myModule || (myModule = {}));
var foo = new myModule.MyClass();
Just another note that you can a id/string enum with the following:
class EnumyObjects{
public static BOUNCE={str:"Bounce",id:1};
public static DROP={str:"Drop",id:2};
public static FALL={str:"Fall",id:3};
}
Update:
As noted by #iX3, Typescript 2.4 has support for enum strings.
See:Create an enum with string values in Typescript
Original answer:
For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;
Solution 1:
copied from: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
There is a simple solution: Just cast the string literal to any before assigning:
export enum Language {
English = <any>"English",
German = <any>"German",
French = <any>"French",
Italian = <any>"Italian"
}
solution 2:
copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html
You can use a string literal as a type. For example:
let foo: 'Hello';
Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:
let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"
They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:
type CardinalDirection =
"North"
| "East"
| "South"
| "West";
function move(distance: number, direction: CardinalDirection) {
// ...
}
move(1,"North"); // Okay
move(1,"Nurth"); // Error!
Enums in typescript:
Enums are put into the typescript language to define a set of named constants. Using enums can make our life easier. The reason for this is that these constants are often easier to read than the value which the enum represents.
Creating a enum:
enum Direction {
Up = 1,
Down,
Left,
Right,
}
This example from the typescript docs explains very nicely how enums work. Notice that our first enum value (Up) is initialized with 1. All the following members of the number enum are then auto incremented from this value (i.e. Down = 2, Left = 3, Right = 4). If we didn't initialize the first value with 1 the enum would start at 0 and then auto increment (i.e. Down = 1, Left = 2, Right = 3).
Using an enum:
We can access the values of the enum in the following manner:
Direction.Up; // first the enum name, then the dot operator followed by the enum value
Direction.Down;
Notice that this way we are much more descriptive in the way we write our code. Enums basically prevent us from using magic numbers (numbers which represent some entity because the programmer has given a meaning to them in a certain context). Magic numbers are bad because of the following reasons:
We need to think harder, we first need to translate the number to an entity before we can reason about our code.
If we review our code after a long while, or other programmers review our code, they don't necessarily know what is meant with these numbers.
Works for me to type enums like this (which also allows you to loop through it as an object):
enum: { [x: string]: string }
Map example:
export const yourFunction = (
enum: { [x: string]: string },
) => {
const iHaveBeenMapped = Object.keys(enum).map((key) => {
const enumValue = enum[key];
});
}