Best Python code snippet using lisa_python
dense_features_test.py
Source:dense_features_test.py  
...42  @test_util.run_in_graph_and_eager_modes()43  def test_retrieving_input(self):44    features = {'a': [0.]}45    dense_features = df.DenseFeatures(fc.numeric_column('a'))46    inputs = self.evaluate(dense_features(features))47    self.assertAllClose([[0.]], inputs)48  def test_reuses_variables(self):49    with context.eager_mode():50      sparse_input = sparse_tensor.SparseTensor(51          indices=((0, 0), (1, 0), (2, 0)),52          values=(0, 1, 2),53          dense_shape=(3, 3))54      # Create feature columns (categorical and embedding).55      categorical_column = fc.categorical_column_with_identity(56          key='a', num_buckets=3)57      embedding_dimension = 258      def _embedding_column_initializer(shape, dtype, partition_info=None):59        del shape  # unused60        del dtype  # unused61        del partition_info  # unused62        embedding_values = (63            (1, 0),  # id 064            (0, 1),  # id 165            (1, 1))  # id 266        return embedding_values67      embedding_column = fc.embedding_column(68          categorical_column,69          dimension=embedding_dimension,70          initializer=_embedding_column_initializer)71      dense_features = df.DenseFeatures([embedding_column])72      features = {'a': sparse_input}73      inputs = dense_features(features)74      variables = dense_features.variables75      # Sanity check: test that the inputs are correct.76      self.assertAllEqual([[1, 0], [0, 1], [1, 1]], inputs)77      # Check that only one variable was created.78      self.assertEqual(1, len(variables))79      # Check that invoking dense_features on the same features does not create80      # additional variables81      _ = dense_features(features)82      self.assertEqual(1, len(variables))83      self.assertIs(variables[0], dense_features.variables[0])84  def test_dense_feature_with_partitioner(self):85    with context.eager_mode():86      sparse_input = sparse_tensor.SparseTensor(87          indices=((0, 0), (1, 0), (2, 0), (3, 0)),88          values=(0, 1, 3, 2),89          dense_shape=(4, 4))90      # Create feature columns (categorical and embedding).91      categorical_column = fc.categorical_column_with_identity(92          key='a', num_buckets=4)93      embedding_dimension = 294      def _embedding_column_initializer(shape, dtype, partition_info=None):95        offset = partition_info._var_offset[0]96        del shape  # unused97        del dtype  # unused98        if offset == 0:99          embedding_values = (100              (1, 0),  # id 0101              (0, 1))  # id 1102        else:103          embedding_values = (104              (1, 1),  # id 2105              (2, 2))  # id 3106        return embedding_values107      embedding_column = fc.embedding_column(108          categorical_column,109          dimension=embedding_dimension,110          initializer=_embedding_column_initializer)111      dense_features = df.DenseFeatures(112          [embedding_column],113          partitioner=partitioned_variables.fixed_size_partitioner(2))114      features = {'a': sparse_input}115      inputs = dense_features(features)116      variables = dense_features.variables117      # Sanity check: test that the inputs are correct.118      self.assertAllEqual([[1, 0], [0, 1], [2, 2], [1, 1]], inputs)119      # Check that only one variable was created.120      self.assertEqual(2, len(variables))121      # Check that invoking dense_features on the same features does not create122      # additional variables123      _ = dense_features(features)124      self.assertEqual(2, len(variables))125      self.assertIs(variables[0], dense_features.variables[0])126      self.assertIs(variables[1], dense_features.variables[1])127  def test_feature_column_dense_features_gradient(self):128    with context.eager_mode():129      sparse_input = sparse_tensor.SparseTensor(130          indices=((0, 0), (1, 0), (2, 0)),131          values=(0, 1, 2),132          dense_shape=(3, 3))133      # Create feature columns (categorical and embedding).134      categorical_column = fc.categorical_column_with_identity(135          key='a', num_buckets=3)136      embedding_dimension = 2137      def _embedding_column_initializer(shape, dtype, partition_info=None):138        del shape  # unused139        del dtype  # unused140        del partition_info  # unused141        embedding_values = (142            (1, 0),  # id 0143            (0, 1),  # id 1144            (1, 1))  # id 2145        return embedding_values146      embedding_column = fc.embedding_column(147          categorical_column,148          dimension=embedding_dimension,149          initializer=_embedding_column_initializer)150      dense_features = df.DenseFeatures([embedding_column])151      features = {'a': sparse_input}152      def scale_matrix():153        matrix = dense_features(features)154        return 2 * matrix155      # Sanity check: Verify that scale_matrix returns the correct output.156      self.assertAllEqual([[2, 0], [0, 2], [2, 2]], scale_matrix())157      # Check that the returned gradient is correct.158      grad_function = backprop.implicit_grad(scale_matrix)159      grads_and_vars = grad_function()160      indexed_slice = grads_and_vars[0][0]161      gradient = grads_and_vars[0][0].values162      self.assertAllEqual([0, 1, 2], indexed_slice.indices)163      self.assertAllEqual([[2, 2], [2, 2], [2, 2]], gradient)164  def test_raises_if_empty_feature_columns(self):165    with self.assertRaisesRegexp(ValueError,166                                 'feature_columns must not be empty'):167      df.DenseFeatures(feature_columns=[])(features={})168  def test_should_be_dense_column(self):169    with self.assertRaisesRegexp(ValueError, 'must be a .*DenseColumn'):170      df.DenseFeatures(feature_columns=[171          fc.categorical_column_with_hash_bucket('wire_cast', 4)172      ])(173          features={174              'a': [[0]]175          })176  def test_does_not_support_dict_columns(self):177    with self.assertRaisesRegexp(178        ValueError, 'Expected feature_columns to be iterable, found dict.'):179      df.DenseFeatures(feature_columns={'a': fc.numeric_column('a')})(180          features={181              'a': [[0]]182          })183  def test_bare_column(self):184    with ops.Graph().as_default():185      features = features = {'a': [0.]}186      net = df.DenseFeatures(fc.numeric_column('a'))(features)187      self.evaluate(variables_lib.global_variables_initializer())188      self.evaluate(lookup_ops.tables_initializer())189      self.assertAllClose([[0.]], self.evaluate(net))190  def test_column_generator(self):191    with ops.Graph().as_default():192      features = features = {'a': [0.], 'b': [1.]}193      columns = (fc.numeric_column(key) for key in features)194      net = df.DenseFeatures(columns)(features)195      self.evaluate(variables_lib.global_variables_initializer())196      self.evaluate(lookup_ops.tables_initializer())197      self.assertAllClose([[0., 1.]], self.evaluate(net))198  def test_raises_if_duplicate_name(self):199    with self.assertRaisesRegexp(200        ValueError, 'Duplicate feature column name found for columns'):201      df.DenseFeatures(202          feature_columns=[fc.numeric_column('a'),203                           fc.numeric_column('a')])(204                               features={205                                   'a': [[0]]206                               })207  def test_one_column(self):208    price = fc.numeric_column('price')209    with ops.Graph().as_default():210      features = {'price': [[1.], [5.]]}211      net = df.DenseFeatures([price])(features)212      self.evaluate(variables_lib.global_variables_initializer())213      self.evaluate(lookup_ops.tables_initializer())214      self.assertAllClose([[1.], [5.]], self.evaluate(net))215  def test_multi_dimension(self):216    price = fc.numeric_column('price', shape=2)217    with ops.Graph().as_default():218      features = {'price': [[1., 2.], [5., 6.]]}219      net = df.DenseFeatures([price])(features)220      self.evaluate(variables_lib.global_variables_initializer())221      self.evaluate(lookup_ops.tables_initializer())222      self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))223  def test_compute_output_shape(self):224    price1 = fc.numeric_column('price1', shape=2)225    price2 = fc.numeric_column('price2', shape=4)226    with ops.Graph().as_default():227      features = {228          'price1': [[1., 2.], [5., 6.]],229          'price2': [[3., 4., 5., 6.], [7., 8., 9., 10.]]230      }231      dense_features = df.DenseFeatures([price1, price2])232      self.assertEqual((None, 6), dense_features.compute_output_shape((None,)))233      net = dense_features(features)234      self.evaluate(variables_lib.global_variables_initializer())235      self.evaluate(lookup_ops.tables_initializer())236      self.assertAllClose([[1., 2., 3., 4., 5., 6.], [5., 6., 7., 8., 9., 10.]],237                          self.evaluate(net))238  def test_raises_if_shape_mismatch(self):239    price = fc.numeric_column('price', shape=2)240    with ops.Graph().as_default():241      features = {'price': [[1.], [5.]]}242      with self.assertRaisesRegexp(243          Exception,244          r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):245        df.DenseFeatures([price])(features)246  def test_reshaping(self):247    price = fc.numeric_column('price', shape=[1, 2])248    with ops.Graph().as_default():249      features = {'price': [[[1., 2.]], [[5., 6.]]]}250      net = df.DenseFeatures([price])(features)251      self.evaluate(variables_lib.global_variables_initializer())252      self.evaluate(lookup_ops.tables_initializer())253      self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))254  def test_multi_column(self):255    price1 = fc.numeric_column('price1', shape=2)256    price2 = fc.numeric_column('price2')257    with ops.Graph().as_default():258      features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}259      net = df.DenseFeatures([price1, price2])(features)260      self.evaluate(variables_lib.global_variables_initializer())261      self.evaluate(lookup_ops.tables_initializer())262      self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))263  def test_cols_to_output_tensors(self):264    price1 = fc.numeric_column('price1', shape=2)265    price2 = fc.numeric_column('price2')266    with ops.Graph().as_default():267      cols_dict = {}268      features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}269      dense_features = df.DenseFeatures([price1, price2])270      net = dense_features(features, cols_dict)271      self.evaluate(variables_lib.global_variables_initializer())272      self.evaluate(lookup_ops.tables_initializer())273      self.assertAllClose([[1., 2.], [5., 6.]],274                          self.evaluate(cols_dict[price1]))275      self.assertAllClose([[3.], [4.]], self.evaluate(cols_dict[price2]))276      self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))277  def test_column_order(self):278    price_a = fc.numeric_column('price_a')279    price_b = fc.numeric_column('price_b')280    with ops.Graph().as_default():281      features = {282          'price_a': [[1.]],283          'price_b': [[3.]],284      }...dense_features_v2_test.py
Source:dense_features_v2_test.py  
...41  @test_util.run_in_graph_and_eager_modes()42  def test_retrieving_input(self):43    features = {'a': [0.]}44    dense_features = df.DenseFeatures(fc.numeric_column('a'))45    inputs = self.evaluate(dense_features(features))46    self.assertAllClose([[0.]], inputs)47  def test_reuses_variables(self):48    with context.eager_mode():49      sparse_input = sparse_tensor.SparseTensor(50          indices=((0, 0), (1, 0), (2, 0)),51          values=(0, 1, 2),52          dense_shape=(3, 3))53      # Create feature columns (categorical and embedding).54      categorical_column = fc.categorical_column_with_identity(55          key='a', num_buckets=3)56      embedding_dimension = 257      def _embedding_column_initializer(shape, dtype, partition_info=None):58        del shape  # unused59        del dtype  # unused60        del partition_info  # unused61        embedding_values = (62            (1, 0),  # id 063            (0, 1),  # id 164            (1, 1))  # id 265        return embedding_values66      embedding_column = fc.embedding_column(67          categorical_column,68          dimension=embedding_dimension,69          initializer=_embedding_column_initializer)70      dense_features = df.DenseFeatures([embedding_column])71      features = {'a': sparse_input}72      inputs = dense_features(features)73      variables = dense_features.variables74      # Sanity check: test that the inputs are correct.75      self.assertAllEqual([[1, 0], [0, 1], [1, 1]], inputs)76      # Check that only one variable was created.77      self.assertEqual(1, len(variables))78      # Check that invoking dense_features on the same features does not create79      # additional variables80      _ = dense_features(features)81      self.assertEqual(1, len(variables))82      self.assertIs(variables[0], dense_features.variables[0])83  def test_feature_column_dense_features_gradient(self):84    with context.eager_mode():85      sparse_input = sparse_tensor.SparseTensor(86          indices=((0, 0), (1, 0), (2, 0)),87          values=(0, 1, 2),88          dense_shape=(3, 3))89      # Create feature columns (categorical and embedding).90      categorical_column = fc.categorical_column_with_identity(91          key='a', num_buckets=3)92      embedding_dimension = 293      def _embedding_column_initializer(shape, dtype, partition_info=None):94        del shape  # unused95        del dtype  # unused96        del partition_info  # unused97        embedding_values = (98            (1, 0),  # id 099            (0, 1),  # id 1100            (1, 1))  # id 2101        return embedding_values102      embedding_column = fc.embedding_column(103          categorical_column,104          dimension=embedding_dimension,105          initializer=_embedding_column_initializer)106      dense_features = df.DenseFeatures([embedding_column])107      features = {'a': sparse_input}108      def scale_matrix():109        matrix = dense_features(features)110        return 2 * matrix111      # Sanity check: Verify that scale_matrix returns the correct output.112      self.assertAllEqual([[2, 0], [0, 2], [2, 2]], scale_matrix())113      # Check that the returned gradient is correct.114      grad_function = backprop.implicit_grad(scale_matrix)115      grads_and_vars = grad_function()116      indexed_slice = grads_and_vars[0][0]117      gradient = grads_and_vars[0][0].values118      self.assertAllEqual([0, 1, 2], indexed_slice.indices)119      self.assertAllEqual([[2, 2], [2, 2], [2, 2]], gradient)120  def test_dense_feature_with_training_arg(self):121    price1 = fc.numeric_column('price1', shape=2)122    price2 = fc.numeric_column('price2')123    # Monkey patch the second numeric column to simulate a column that has124    # different behavior by mode.125    def training_aware_get_dense_tensor(transformation_cache,126                                        state_manager,127                                        training=None):128      return transformation_cache.get(price2, state_manager, training=training)129    def training_aware_transform_feature(transformation_cache,130                                         state_manager,131                                         training=None):132      input_tensor = transformation_cache.get(133          price2.key, state_manager, training=training)134      if training:135        return input_tensor * 10.0136      else:137        return input_tensor * 20.0138    price2.get_dense_tensor = training_aware_get_dense_tensor139    price2.transform_feature = training_aware_transform_feature140    with ops.Graph().as_default():141      features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}142      train_mode = df.DenseFeatures([price1, price2])(features, training=True)143      predict_mode = df.DenseFeatures([price1, price2144                                      ])(features, training=False)145      self.evaluate(variables_lib.global_variables_initializer())146      self.evaluate(lookup_ops.tables_initializer())147      self.assertAllClose([[1., 2., 30.], [5., 6., 40.]],148                          self.evaluate(train_mode))149      self.assertAllClose([[1., 2., 60.], [5., 6., 80.]],150                          self.evaluate(predict_mode))151  def test_raises_if_empty_feature_columns(self):152    with self.assertRaisesRegexp(ValueError,153                                 'feature_columns must not be empty'):154      df.DenseFeatures(feature_columns=[])(features={})155  def test_should_be_dense_column(self):156    with self.assertRaisesRegexp(ValueError, 'must be a .*DenseColumn'):157      df.DenseFeatures(feature_columns=[158          fc.categorical_column_with_hash_bucket('wire_cast', 4)159      ])(160          features={161              'a': [[0]]162          })163  def test_does_not_support_dict_columns(self):164    with self.assertRaisesRegexp(165        ValueError, 'Expected feature_columns to be iterable, found dict.'):166      df.DenseFeatures(feature_columns={'a': fc.numeric_column('a')})(167          features={168              'a': [[0]]169          })170  def test_bare_column(self):171    with ops.Graph().as_default():172      features = features = {'a': [0.]}173      net = df.DenseFeatures(fc.numeric_column('a'))(features)174      self.evaluate(variables_lib.global_variables_initializer())175      self.evaluate(lookup_ops.tables_initializer())176      self.assertAllClose([[0.]], self.evaluate(net))177  def test_column_generator(self):178    with ops.Graph().as_default():179      features = features = {'a': [0.], 'b': [1.]}180      columns = (fc.numeric_column(key) for key in features)181      net = df.DenseFeatures(columns)(features)182      self.evaluate(variables_lib.global_variables_initializer())183      self.evaluate(lookup_ops.tables_initializer())184      self.assertAllClose([[0., 1.]], self.evaluate(net))185  def test_raises_if_duplicate_name(self):186    with self.assertRaisesRegexp(187        ValueError, 'Duplicate feature column name found for columns'):188      df.DenseFeatures(189          feature_columns=[fc.numeric_column('a'),190                           fc.numeric_column('a')])(191                               features={192                                   'a': [[0]]193                               })194  def test_one_column(self):195    price = fc.numeric_column('price')196    with ops.Graph().as_default():197      features = {'price': [[1.], [5.]]}198      net = df.DenseFeatures([price])(features)199      self.evaluate(variables_lib.global_variables_initializer())200      self.evaluate(lookup_ops.tables_initializer())201      self.assertAllClose([[1.], [5.]], self.evaluate(net))202  def test_multi_dimension(self):203    price = fc.numeric_column('price', shape=2)204    with ops.Graph().as_default():205      features = {'price': [[1., 2.], [5., 6.]]}206      net = df.DenseFeatures([price])(features)207      self.evaluate(variables_lib.global_variables_initializer())208      self.evaluate(lookup_ops.tables_initializer())209      self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))210  def test_compute_output_shape(self):211    price1 = fc.numeric_column('price1', shape=2)212    price2 = fc.numeric_column('price2', shape=4)213    with ops.Graph().as_default():214      features = {215          'price1': [[1., 2.], [5., 6.]],216          'price2': [[3., 4., 5., 6.], [7., 8., 9., 10.]]217      }218      dense_features = df.DenseFeatures([price1, price2])219      self.assertEqual((None, 6), dense_features.compute_output_shape((None,)))220      net = dense_features(features)221      self.evaluate(variables_lib.global_variables_initializer())222      self.evaluate(lookup_ops.tables_initializer())223      self.assertAllClose([[1., 2., 3., 4., 5., 6.], [5., 6., 7., 8., 9., 10.]],224                          self.evaluate(net))225  def test_raises_if_shape_mismatch(self):226    price = fc.numeric_column('price', shape=2)227    with ops.Graph().as_default():228      features = {'price': [[1.], [5.]]}229      with self.assertRaisesRegexp(230          Exception,231          r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):232        df.DenseFeatures([price])(features)233  def test_reshaping(self):234    price = fc.numeric_column('price', shape=[1, 2])235    with ops.Graph().as_default():236      features = {'price': [[[1., 2.]], [[5., 6.]]]}237      net = df.DenseFeatures([price])(features)238      self.evaluate(variables_lib.global_variables_initializer())239      self.evaluate(lookup_ops.tables_initializer())240      self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))241  def test_multi_column(self):242    price1 = fc.numeric_column('price1', shape=2)243    price2 = fc.numeric_column('price2')244    with ops.Graph().as_default():245      features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}246      net = df.DenseFeatures([price1, price2])(features)247      self.evaluate(variables_lib.global_variables_initializer())248      self.evaluate(lookup_ops.tables_initializer())249      self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))250  def test_cols_to_output_tensors(self):251    price1 = fc.numeric_column('price1', shape=2)252    price2 = fc.numeric_column('price2')253    with ops.Graph().as_default():254      cols_dict = {}255      features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}256      dense_features = df.DenseFeatures([price1, price2])257      net = dense_features(features, cols_dict)258      self.evaluate(variables_lib.global_variables_initializer())259      self.evaluate(lookup_ops.tables_initializer())260      self.assertAllClose([[1., 2.], [5., 6.]],261                          self.evaluate(cols_dict[price1]))262      self.assertAllClose([[3.], [4.]], self.evaluate(cols_dict[price2]))263      self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))264  def test_column_order(self):265    price_a = fc.numeric_column('price_a')266    price_b = fc.numeric_column('price_b')267    with ops.Graph().as_default():268      features = {269          'price_a': [[1.]],270          'price_b': [[3.]],271      }...dungeon.js
Source:dungeon.js  
1/**2 * @class Floor3 * @augments RPG.Cells.BaseCell4 */5RPG.Cells.Corridor = OZ.Singleton().extend(RPG.Cells.BaseCell);6RPG.Cells.Corridor.visual = { desc:"floor section", ch:".", image:"corridor", color:"#ccc" };78/**9 * @class Road10 * @augments RPG.Cells.BaseCell11 */12RPG.Cells.Road = OZ.Singleton().extend(RPG.Cells.BaseCell);13RPG.Cells.Road.visual = { desc:"road", ch:".", image:"road", color:"#963" };1415/**16 * @class Grass17 * @augments RPG.Cells.BaseCell18 */19RPG.Cells.Grass = OZ.Singleton().extend(RPG.Cells.BaseCell);20RPG.Cells.Grass.visual = { desc:"grass", ch:".", image:"grass", color:"#693" };2122/**23 * @class Water24 * @augments RPG.Cells.BaseCell25 */26RPG.Cells.Water = OZ.Singleton().extend(RPG.Cells.BaseCell);27RPG.Cells.Water.visual = { desc:"water", ch:"=", image:"water", color:"#009" };28RPG.Cells.Water.prototype.init = function() {29	this.parent();30	this._water = true;31}3233RPG.Cells.Water.prototype.entering = function(being) {34	var canSee = RPG.Game.pc.canSee(being.getCoords());35	if (canSee) {36		var verb = RPG.Misc.verb("wade", being);37		var s = RPG.Misc.format("Splash Splash! %A %s into the water.", being, verb);38		RPG.UI.buffer.message(s);	39	} else {40		RPG.UI.buffer.message("You hear some splashing.");41	}42}4344/**45 * @class Deep Water46 * @augments RPG.Cells.BaseCell47 */48RPG.Cells.DeepWater = OZ.Singleton().extend(RPG.Cells.Water);49RPG.Cells.DeepWater.visual = { desc:"deep water", ch:"~", image:"deepwater", color:"#009" };50RPG.Cells.DeepWater.prototype._blocks = RPG.BLOCKS_MOVEMENT;515253/**54 * @class Wall55 * @augments RPG.Cells.BaseCell56 */57RPG.Cells.Wall = OZ.Singleton().extend(RPG.Cells.BaseCell);58RPG.Cells.Wall.visual = { desc:"solid wall", ch:"#", image:"wall", color:"#666" };59RPG.Cells.Wall.prototype._blocks = RPG.BLOCKS_LIGHT;6061/**62 * @class Fake wall63 * @augments RPG.Cells.Wall64 */65RPG.Cells.Wall.Fake = OZ.Singleton().extend(RPG.Cells.Wall);66RPG.Cells.Wall.Fake.prototype.init = function() {67	this.parent();68	this._fake = true;69}7071/**72 * @class Tree73 * @augments RPG.Features.BaseFeature74 */75RPG.Features.Tree = OZ.Class().extend(RPG.Features.BaseFeature);76RPG.Features.Tree.visual = { desc:"tree", ch:"T", image:"tree", color:"#093" }77RPG.Features.Tree.prototype._blocks = RPG.BLOCKS_ITEMS;7879/**80 * @class Altar feature81 * @augments RPG.Features.BaseFeature82 */83RPG.Features.Altar = OZ.Class().extend(RPG.Features.BaseFeature);84RPG.Features.Altar.visual = { desc:"altar", image:"altar", ch:"\u00B1", color:"#fff"};8586/**87 * @class Bench feature88 * @augments RPG.Features.BaseFeature89 */90RPG.Features.Bench = OZ.Class().extend(RPG.Features.BaseFeature);91RPG.Features.Bench.visual = { desc:"bench", image:"bench", ch:"|", color:"#963"};92RPG.Features.Bench.prototype._blocks = RPG.BLOCKS_MOVEMENT;9394/**95 * @class Signpost feature96 * @augments RPG.Features.BaseFeature97 */98RPG.Features.Signpost = OZ.Class().extend(RPG.Features.BaseFeature);99RPG.Features.Signpost.visual = { image:"signpost", ch:"\u2142", color:"#666"};100RPG.Features.Signpost.prototype.init = function(label) {101	this.parent();102	this._label = label;103}104RPG.Features.Signpost.prototype.describe = function() {105	return "signpost labeled '" + this._label + "'";106}107108/**109 * @class Generic trap110 * @augments RPG.Features.BaseFeature111 */112RPG.Features.Trap = OZ.Class().extend(RPG.Features.BaseFeature);113RPG.Features.Trap.factory.frequency = 0;114RPG.Features.Trap.visual = { ch:"^" }115RPG.Features.Trap.prototype.init = function() {116	this.parent();117	this._damage = null;118}119120RPG.Features.Trap.prototype.entering = function(being) {121	this.parent(being);122	being.trapEncounter(this);123}124125RPG.Features.Trap.prototype.setOff = function(being) {126}127128RPG.Features.Trap.prototype.getDamage = function() {129	return this._damage;130}131132/**133 * @class Teleport trap134 * @augments RPG.Features.Trap135 */136RPG.Features.Trap.Teleport = OZ.Class().extend(RPG.Features.Trap);137RPG.Features.Trap.Teleport.visual = { desc:"teleport trap", image:"trap-teleport", color:"#3c3" }138139RPG.Features.Trap.Teleport.prototype.setOff = function(being) {140	var c = this._map.getFreeCoords();141	being.teleport(c);142}143144/**145 * @class Pit trap146 * @augments RPG.Features.Trap147 */148RPG.Features.Trap.Pit = OZ.Class().extend(RPG.Features.Trap);149RPG.Features.Trap.Pit.visual = { desc:"pit trap", image:"trap-pit", color:"#963" }150151RPG.Features.Trap.Pit.prototype.init = function() {152	this.parent();153	this._damage = new RPG.RandomValue(3, 1);154}155156RPG.Features.Trap.Pit.prototype.setOff = function(being) {157	var canSee = RPG.Game.pc.canSee(this._coords);158159	if (canSee) {160		var verb = RPG.Misc.verb("fall", being);161		var s = RPG.Misc.format("%A %s into a pit!", being, verb);162		RPG.UI.buffer.message(s);163	}164165	var dmg = RPG.Rules.getTrapDamage(being, this);166	being.adjustStat(RPG.STAT_HP, -dmg);167	168	if (!being.isAlive() && canSee && being != RPG.Game.pc) {169		var s = RPG.Misc.format("%The suddenly collapses!", being);170		RPG.UI.buffer.message(s);171	}172173}174175/**176 * @class Flash trap177 * @augments RPG.Features.Trap178 */179RPG.Features.Trap.Flash = OZ.Class().extend(RPG.Features.Trap);180RPG.Features.Trap.Flash.visual = { desc:"flash trap", image:"trap-flash", color:"#ff0" }181182RPG.Features.Trap.Flash.prototype.setOff = function(being) {183	var canSee = RPG.Game.pc.canSee(this._coords);184185	var blindness = new RPG.Effects.Blindness(5);186	being.addEffect(blindness);187188	if (canSee) {189		var s = RPG.Misc.format("%A %is blinded by a light flash!", being);190		RPG.UI.buffer.message(s);191	}192}193194/**195 * @class Abstract destroyable feature196 * @augments RPG.Features.BaseFeature197 * @augments RPG.Features.IDamageReceiver198 */199RPG.Features.Destroyable = OZ.Class().extend(RPG.Features.BaseFeature)200			 	     .implement(RPG.Misc.IDamageReceiver);201202RPG.Features.Destroyable.factory.frequency = 0;203RPG.Features.Destroyable.prototype.damage = function(amount) {204	this._hp -= amount;205	if (!this.isAlive()) { this._destroy(); }206}207RPG.Features.Destroyable.prototype.isAlive = function() {208	return this._hp > 0;209}210211/**212 * This being just destroyed this feature213 * @param {RPG.Beings.BaseBeing} being214 */215RPG.Features.Destroyable.prototype._destroy = function() {216	this._map.setFeature(null, this._coords); 217}218219/**220 * @class Tombstone feature221 * @augments RPG.Features.Destroyable222 */223RPG.Features.Tombstone = OZ.Class().extend(RPG.Features.Destroyable);224RPG.Features.Tombstone.visual = { desc:"tombstone", image:"tombstone", ch:"\u2020", color:"#666"};225RPG.Features.Tombstone.prototype._blocks = RPG.BLOCKS_MOVEMENT;226RPG.Features.Tombstone.prototype.init = function() {227	this.parent();228	this._hp = 4;229}230RPG.Features.Tombstone.prototype._destroy = function() {231	this.parent();232	var undead = RPG.Factories.undead.getInstance(this._map.getDanger());233	RPG.Game.getEngine().addActor(undead);234	this._map.setBeing(undead, this._coords);235}236237/**238 * @class Door239 * @augments RPG.Features.Destroyable240 */241RPG.Features.Door = OZ.Class().extend(RPG.Features.Destroyable);242RPG.Features.Door.visual = { color:"#963" }243RPG.Features.Door.prototype.init = function() {244	this.parent();245	this._hp = 4;246	this._closed = null;247	this._locked = null;248	this.open();249}250251RPG.Features.Door.prototype.getVisualProperty = function(name) {252	var result = this.parent(name);253	if (this._closed) {254		var data = {255			ch: "+",256			desc: "closed door",257			image: "door-closed"258		};259	} else {260		var data = {261			ch: "/",262			desc: "open door",263			image: "door-open"264		};265	}266	return data[name] || this.parent(name);267}268269RPG.Features.Door.prototype.lock = function() {270	this.close();271	this._locked = true;272	return this;273}274275RPG.Features.Door.prototype.close = function() {276	this._closed = true;277	this._locked = false;278	this._blocks = RPG.BLOCKS_LIGHT;279	if (this._map && this._map.isActive() && RPG.Game.pc.canSee(this._coords)) { 280		RPG.Game.pc.coordsChanged(this._coords);281		RPG.Game.pc.updateVisibility(); 282	}283	return this;284}285286RPG.Features.Door.prototype.open = function() {287	this._closed = false;288	this._locked = false;289	this._blocks = RPG.BLOCKS_NOTHING;290	if (this._map && this._map.isActive() && RPG.Game.pc.canSee(this._coords)) { 291		RPG.Game.pc.coordsChanged(this._coords);292		RPG.Game.pc.updateVisibility(); 293	}294	return this;295}296297RPG.Features.Door.prototype.unlock = function() {298	this._locked = false;299	return this;300}301302RPG.Features.Door.prototype.isClosed = function() {303	return this._closed;304}305306RPG.Features.Door.prototype.isLocked = function() {307	return this._locked;308}309RPG.Features.Door.prototype._destroy = function() {310	this.parent();311	if (RPG.Game.pc.canSee(this._coords)) { RPG.Game.pc.updateVisibility(); }312}313314/**315 * @class Stained glass window, random shiny color. When destroyed, damages stuff around.316 * @augments RPG.Features.Destroyable317 * @augments RPG.Features.IActor318 * @augments RPG.Features.IDamageDealer319 */320RPG.Features.StainedGlassWindow = OZ.Class().extend(RPG.Features.Destroyable)321					    .implement(RPG.IActor)322					    .implement(RPG.Misc.IDamageDealer);323324RPG.Features.StainedGlassWindow.visual = { desc:"stained glass window", image:"stained-glass-window", ch:"=" };325RPG.Features.StainedGlassWindow.prototype._blocks = RPG.BLOCKS_MOVEMENT;326RPG.Features.StainedGlassWindow.prototype._hit = new RPG.RandomValue(8, 5);327RPG.Features.StainedGlassWindow.prototype._damage = new RPG.RandomValue(2, 1);328RPG.Features.StainedGlassWindow.prototype.init = function() { 329	this.parent();330	this._hp = 3;331	this._color = ["red","green","blue","yellow","magenta","cyan"].random(); 332}333RPG.Features.StainedGlassWindow.prototype.getColor = function() { 334	return this._color;335}336RPG.Features.StainedGlassWindow.prototype._destroy = function() {337	this.parent();338	RPG.Game.getEngine().addActor(this);339}340/**341 * @see RPG.IActor#getSpeed342 */343RPG.Features.StainedGlassWindow.prototype.getSpeed = function() {344	return 1/0;345}346/**347 * @see RPG.IActor#yourTurn348 * Damage surrounding beings349 */350RPG.Features.StainedGlassWindow.prototype.yourTurn = function() {351	var coords = this._map.getCoordsInCircle(this._coords, 1);352	for (var i=0;i<coords.length;i++) {353		var b = this._map.getBeing(coords[i]);354		if (!b) { continue; }355		var combat = new RPG.Combat(this, b).execute();356		357		if (!combat.wasHit()) {358			var verb = RPG.Misc.verb("evade", b);359			var s = RPG.Misc.format("%The %s the falling glass.", b, verb);360			RPG.UI.buffer.message(s);361			continue;362		}363		364		var verb = (combat.wasKill() ? "killed" : "wounded");365		var s = RPG.Misc.format("%The %is %s by the falling glass!", b, b, verb);366		RPG.UI.buffer.message(s);367	}368369	RPG.Game.getEngine().removeActor(this);370	return RPG.ACTION_TIME;371}372373374/**375 * @class Basic level connector376 * @augments RPG.Features.BaseFeature377 */378RPG.Features.Connector = OZ.Class().extend(RPG.Features.BaseFeature);379380RPG.Features.Connector.prototype.init = function() {381	this.parent();382	this._target = null;383}384385RPG.Features.Connector.prototype.enter = function(being) {386	var target = this.getTarget();387388	if (target) { /* move being to other map */389		var map = target.getMap();390		var coords = target.getCoords();391		map.setBeing(being, coords);392		return RPG.ACTION_TIME;393	} else {394		return RPG.ACTION_NO_TIME;395	}396}397398/**399 * @param {RPG.Features.Connector} target400 */401RPG.Features.Connector.prototype.setTarget = function(target) {402	this._target = target;403	return this;404}405406/**407 * @returns {RPG.Features.Connector || null}408 */409RPG.Features.Connector.prototype.getTarget = function() {410	if (!this._target) { RPG.Game.getStory().staircaseCallback(this); }/* ask story to generate some */411	return this._target;412}413414/**415 * @class Connector in "down" direction416 * @augments RPG.Features.Connector417 */418RPG.Features.Connector.Entry = OZ.Class().extend(RPG.Features.Connector);419RPG.Features.Connector.Entry.visual = { ch:">" };420421/**422 * @class Connector in "up" direction423 * @augments RPG.Features.Connector424 */425RPG.Features.Connector.Exit = OZ.Class().extend(RPG.Features.Connector);426RPG.Features.Connector.Exit.visual = { ch:"<" };427428/**429 * @class Staircase down430 * @augments RPG.Features.Connector.Entry431 */432RPG.Features.StaircaseDown = OZ.Class().extend(RPG.Features.Connector.Entry);433RPG.Features.StaircaseDown.visual = { desc:"staircase leading down", image:"staircase-down", color:"#ccc" }434435/**436 * @class Staircase up437 * @augments RPG.Features.Connector.Exit438 */439RPG.Features.StaircaseUp = OZ.Class().extend(RPG.Features.Connector.Exit);440RPG.Features.StaircaseUp.visual = { desc:"staircase leading up", image:"staircase-up", color:"#ccc" }441442/**443 * @class Road in "up" direction444 * @augments RPG.Features.Connector445 */446RPG.Features.RoadExit = OZ.Class().extend(RPG.Features.Connector.Exit);447RPG.Features.RoadExit.visual = { desc:"road leading away", image:"road-away", color:"#963" };448449/**450 * @class Road in "down" direction451 * @augments RPG.Features.Connector452 */453RPG.Features.RoadEntry = OZ.Class().extend(RPG.Features.Connector.Entry);454RPG.Features.RoadEntry.visual = { desc:"road leading further", image:"road-further", color:"#963" };455456/**457 * @class Set of cells with tutorial messages458 * @augments RPG.Areas.BaseArea459 */460RPG.Areas.Tutorial = OZ.Class().extend(RPG.Areas.BaseArea);461RPG.Areas.Tutorial.prototype._messages = {};462RPG.Areas.Tutorial.prototype.init = function() {463	this.parent();464	this._visited = {};465}466RPG.Areas.Tutorial.prototype.getCoords = function() {467	var all = [];468	for (var p in this._messages) { 469		if (p in this._visited) { continue; }470		all.push(RPG.Coords.fromString(p)); 471	}472	return all;473}474475RPG.Areas.Tutorial.prototype.entering = function(being) {476	this.parent(being);477	if (being != RPG.Game.pc) { return; }478	var id = being.getCoords().toString();479	480	if (id in this._visited) { return; } /* already seen */481	482	/* showing tutorial for the first time? */483	var first = true;484	for (var p in this._visited) { first = false; }485	486	if (first) {487		var text = this._messages[id];488		text += "<br/><br/>";489		text += "Do you want to continue seeing these tutorial tips?";490		491		var yes = function() { /* want to see */492			this._visited[id] = 1;493		}494		495		var no = function() { /* do not want to see, mark all as visited */496			for (var id in this._messages) { this._visited[id] = 1; }497		}498		499		RPG.UI.confirm(text, "Tutorial", yes.bind(this), no.bind(this));500		501	} else {502		this._visited[id] = 1;503		RPG.UI.alert(this._messages[id], "Tutorial");504	}505}506507/**508 * @class Shop area509 * @augments RPG.Areas.Room510 */511RPG.Areas.Shop = OZ.Class().extend(RPG.Areas.Room);512RPG.Areas.Shop.prototype.init = function(corner1, corner2) {513	this.parent(corner1, corner2);514	this._modifiers[RPG.FEAT_MAX_MANA] = -1e6; /* in shops, there is no mana .) */515	this._door = null;516	this._welcome = "You entered a shop.";517}518519RPG.Areas.Shop.prototype.setMap = function(map) {520	this.parent(map);521522	var c = new RPG.Coords(0, 0);523	for (var i=this._corner1.x-1; i<=this._corner2.x+1; i++) {524		for (var j=this._corner1.y-1; j<=this._corner2.y+1; j++) {525			if (i >= this._corner1.x && i <= this._corner2.x && j >= this._corner1.y && j <= this._corner2.y) { continue; }526			c.x = i;527			c.y = j;528			if (this._map.blocks(RPG.BLOCKS_MOVEMENT, c)) { continue; }529			530			if (this._door) { throw new Error("Shop cannot have >1 doors"); }531			this._door = c.clone();532		}533	}534	535	if (!this._door) { throw new Error("Shop without doors"); }536}537538RPG.Areas.Shop.prototype.getDoor = function() {539	return this._door;540}541542RPG.Areas.Shop.prototype.setShopkeeper = function(being) {543	this._map.setBeing(being, this._door);544	var ai = new RPG.AI.Shopkeeper(being, this);545	being.setAI(ai);546}
...highlight-test.js
Source:highlight-test.js  
1/*2* Copyright 2017, GeoSolutions Sas.3* All rights reserved.4*5* This source code is licensed under the BSD-style license found in the6* LICENSE file in the root directory of this source tree.7*/8import expect from 'expect';9import {10    selectedFeatures,11    filteredspatialObject,12    filteredspatialObjectCoord,13    filteredGeometry,14    filteredSpatialObjectId,15    filteredSpatialObjectCrs,16    filteredspatialObjectType,17    filteredFeatures,18    highlighedFeatures19} from '../highlight';20const idFt1 = "idFt1";21const idFt2 = "idFt2";22const modeEdit = "edit";23let feature1 = {24    type: "Feature",25    geometry: {26        type: "Point",27        coordinates: [1, 2]28    },29    id: idFt1,30    properties: {31        someProp: "someValue"32    }33};34let feature2 = {35    type: "Feature",36    geometry: {37        type: "Point",38        coordinates: [1, 2]39    },40    id: idFt2,41    properties: {42        someProp: "someValue"43    }44};45let feature3 = [{46    type: "Feature",47    geometry: {48        type: 'Polygon',49        coordinates: [ [ 0.000008983152841195214, 0.000017966305681987637 ] ]50    },51    style: {52        fillColor: '#FFFFFF',53        fillOpacity: '0.2',54        color: '#ffcc33'55    },56    id: 'spatial_object'57}];58const initialState = {59    featuregrid: {60        mode: modeEdit,61        select: [feature1, feature2],62        changes: [feature2],63        showFilteredObject: true,64        open: true65    },66    highlight: {67        featuresPath: "featuregrid.select"68    },69    query: {70        filterObj: {71            spatialField: {72                geometry: {73                    type: 'Polygon',74                    coordinates: [[ 1, 2]],75                    projection: 'EPSG:3857',76                    id: 'spatial_object'77                }78            }79        }80    }81};82describe('Test highlight selectors', () => {83    it('test if there are some selected features', () => {84        const features = selectedFeatures(initialState);85        expect(features).toExist();86        expect(features.length).toBe(2);87    });88    it('test if there are not some selected features', () => {89        initialState.featuregrid.select = [];90        const features = selectedFeatures(initialState);91        expect(features).toExist();92        expect(features.length).toBe(0);93    });94    it('test filteredspatialObject', () => {95        const spatialObject = initialState.query.filterObj.spatialField;96        const features = filteredspatialObject(initialState);97        expect(features).toExist();98        expect(features).toBe(spatialObject);99    });100    it('test filteredspatialObject with empty state', () => {101        expect(filteredspatialObject({})).toBe(undefined);102    });103    it('test filteredGeometry', () => {104        const geometry = initialState.query.filterObj.spatialField.geometry;105        const features = filteredGeometry(initialState);106        expect(features).toExist();107        expect(features).toBe(geometry);108    });109    it('test filteredspatialObjectCoord', () => {110        const coordinates = initialState.query.filterObj.spatialField.geometry.coordinates;111        const features = filteredspatialObjectCoord(initialState);112        expect(features).toExist();113        expect(features).toBe(coordinates);114    });115    it('test filteredSpatialObjectId', () => {116        const geometryId = initialState.query.filterObj.spatialField.geometry.id;117        const features = filteredSpatialObjectId(initialState);118        expect(features).toExist();119        expect(features).toBe(geometryId);120    });121    it('test filteredSpatialObjectCrs', () => {122        const geometryCrs = initialState.query.filterObj.spatialField.geometry.projection;123        const features = filteredSpatialObjectCrs(initialState);124        expect(features).toExist();125        expect(features).toBe(geometryCrs);126    });127    it('test filteredspatialObjectType', () => {128        const geometryType = initialState.query.filterObj.spatialField.geometry.type;129        const features = filteredspatialObjectType(initialState);130        expect(features).toExist();131        expect(features).toBe(geometryType);132    });133    it('test filteredFeatures', () => {134        const features = filteredFeatures(initialState);135        expect(features).toExist();136        expect(features).toEqual(feature3);137    });138    it('test highlighedFeatures', () => {139        const features = highlighedFeatures(initialState);140        const featuresSelected = initialState.featuregrid.select;141        const combinedFeatures = [...featuresSelected, ...feature3];142        expect(features).toExist();143        expect(features).toEqual(combinedFeatures);144    });...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
