问:
Vertically position material icon besides paragraph text
I have a p element, besides which I am placing a material icon via font method.

Both are inline-block to display side by side, but I am having trouble moving the icon vertically without breaking neighboring layout.

I have tried wrapping the icon in a div, span, and playing with making its container positioned relatively/absolutely but cannot seem to make it behave.

Simplified example for my project:

html

```<code><div class="card-heading">
  <p>
    my title
  </p>
  <div class="icon-holder">
    <i class="material-icons">camera</i>
  </div>
</div>
</code>```

scss

```<code>.card-heading {
  p {
    display: inline-block;
  }

  .icon-holder {
    display: inline-block;

    i {
      padding-top: 6px;
    }
  }
}
</code>```

Example codepen illustrating issue https://codepen.io/joshuaohana/pen/dRqgye

In this example, I am trying to move the icon down by 6px, but instead of moves both the p and the icon

答:
You can add display: flex to .card-heading. Need to remove the padding-top: 6px from .icon-holder.

Codepen here.

Read more about CSS Flexible Box here

.card-heading {
  display: -webkit-flex;
  display: -moz-flex;
  display: flex;

  -webkit-align-items: center;
  -moz-align-items: center;
  align-items: center;
}

.card-heading p, .card-heading .icon-holder {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

<div class="card-heading">
  <p>
    my title
  </p>
  <div class="icon-holder">
    <i class="material-icons">camera</i>
  </div>
</div></code>```

Body:
I have a p element, besides which I am placing a material icon via font method.

Both are inline-block to display side by side, but I am having trouble moving the icon vertically without breaking neighboring layout.

I have tried wrapping the icon in a div, span, and playing with making its container positioned relatively/absolutely but cannot seem to make it behave.

Simplified example for my project:

html

    my title

    camera

scss

.card-heading {
  p {
    display: inline-block;
  }

  .icon-holder {
    display: inline-block;

    i {
      padding-top: 6px;
    }
  }
}

Example codepen illustrating issue https://codepen.io/joshuaohana/pen/dRqgye

In this example, I am trying to move the icon down by 6px, but instead of moves both the p and the icon

Body:
You can add display: flex to .card-heading. Need to remove the padding-top: 6px from .icon-holder.

Codepen here.

Read more about CSS Flexible Box here

.card-heading {
  display: -webkit-flex;
  display: -moz-flex;
  display: flex;

  -webkit-align-items: center;
  -moz-align-items: center;
  align-items: center;
}

.card-heading p, .card-heading .icon-holder {
  display: inline-block;
}

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

<div class="card-heading">
  <p>
    my title
  </p>
  <div class="icon-holder">
    <i class="material-icons">camera</i>
  </div>
</div>


来源: stackexchange

问:
tensor forest estimator value error at fitting the training part
Code :
    from sklearn import cross_validation as cv
    import numpy as np
    from tensorflow.contrib.learn.python.learn.estimators import estimator
    from tensorflow.contrib.tensor_forest.python import tensor_forest

```<code>X = np.array([[  74.,  166.,  331.,  161.,  159.,  181.,  180.],
   [ 437.,  427.,  371.,  361.,  393.,  465.,  464.],
   [ 546.,  564.,  588.,  595.,  536.,  537.,  520.],
   [  89.,   89.,   87.,   87.,  108.,  113.,  111.],
   [  75.,   90.,   74.,   89.,  130.,  140.,  135.]])
Y = np.array([[ 51.,  43.,  29.,  43.,  43.,  41.,  42.],
   [ 22.,  23.,  26.,  27.,  25.,  19.,  19.],
   [  7.,   7.,   5.,   5.,   9.,   8.,  10.],
   [ 55.,  54.,  55.,  53.,  51.,  51.,  51.],
   [ 58.,  57.,  57.,  58.,  55.,  55.,  55.]])
train_X, test_X, train_Y, test_Y = cv.train_test_split(X, Y,
test_size=0.50, random_state=42)

def build_estimator() :
 params = tensor_forest.ForestHParams(num_classes=7, num_features=7,
 num_trees=30, max_nodes=100)
 graph_builder_class = tensor_forest.RandomForestGraphs

 graph_builder_class = tensor_forest.TrainingLossForest
 return estimator.SKCompat(random_forest.TensorForestEstimator(
   params, graph_builder_class=graph_builder_class,
   model_dir=None))
est = build_estimator()
train_X = train_X.astype(dtype = np.float32)
train_Y = train_Y.astype(dtype = np.float32)
est = est.fit(x=train_X, y=train_Y, batch_size = 100)
</code>```

My both input and output shape is [Number_of_samples,7]. It perfectly runs with scikitlearn random forest classifier. However for tf learn, I get the following error when fitting the estimator :

INFO:tensorflow:Constructing forest with params =
  INFO:tensorflow:{'valid_leaf_threshold': 1, 'split_after_samples':
  250, 'num_output_columns': 8, 'feature_bagging_fraction': 1.0,
  'split_initializations_per_input': 1, 'bagged_features': None,
  'min_split_samples': 5, 'max_nodes': 100, 'num_features': 7,
  'num_trees': 30, 'num_splits_to_consider': 7, 'base_random_seed': 0,
  'num_outputs': 1, 'dominate_fraction': 0.99, 'max_fertile_nodes': 50,
  'bagged_num_features': 7, 'dominate_method': 'bootstrap',
  'bagging_fraction': 1.0, 'regression': False, 'num_classes': 7}

ValueErrorTraceback (most recent call last)
   in ()
  ----> 1 est = est.fit(x=train_X, y=train_Y, batch_size = 100)

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in fit(self, x, y, batch_size, steps, max_steps, monitors)    1351

  steps=steps,    1352                         max_steps=max_steps,
  -> 1353                         monitors=all_monitors)    1354     return self    1355

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/client/random_forest.pyc
  in fit(self, x, y, input_fn, steps, batch_size, monitors, max_steps)
      262     elif input is not None:
      263       self._estimator.fit(input_fn=input_fn, steps=steps, monitors=monitors,
  --> 264                           max_steps=max_steps)
      265     else:
      266       raise ValueError('fit: Must provide either both x and y or input_fn.')

/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.pyc
  in new_func(*args, **kwargs)
      278             _call_location(), decorator_utils.get_qualified_name(func),
      279             func.module, arg_name, date, instructions)
  --> 280       return func(*args, **kwargs)
      281     new_func.doc = _add_deprecated_arg_notice_to_docstring(
      282         func.doc, date, instructions)

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in fit(self, x, y, input_fn, steps, batch_size, monitors, max_steps)
      424       hooks.append(basic_session_run_hooks.StopAtStepHook(steps, max_steps))
      425
  --> 426     loss = self._train_model(input_fn=input_fn, hooks=hooks)
      427     logging.info('Loss for final step: %s.', loss)
      428     return self

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _train_model(self, input_fn, hooks)
      932       features, labels = input_fn()
      933       self._check_inputs(features, labels)
  --> 934       model_fn_ops = self._call_legacy_get_train_ops(features, labels)
      935       ops.add_to_collection(ops.GraphKeys.LOSSES, model_fn_ops.loss)
      936       all_hooks.extend([

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _call_legacy_get_train_ops(self, features, labels)    1001     1002
  def _call_legacy_get_train_ops(self, features, labels):
  -> 1003     train_ops = self._get_train_ops(features, labels)    1004     if isinstance(train_ops, model_fn_lib.ModelFnOps):  # Default
  signature    1005       return train_ops

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _get_train_ops(self, features, labels)    1160       ModelFnOps
  object.    1161     """
  -> 1162     return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)    1163     1164   def
  _get_eval_ops(self, features, labels, metrics):

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _call_model_fn(self, features, labels, mode)    1131     if
  'model_dir' in model_fn_args:    1132       kwargs['model_dir'] =
  self.model_dir
  -> 1133     model_fn_results = self._model_fn(features, labels, **kwargs)    1134     1135     if isinstance(model_fn_results, model_fn_lib.ModelFnOps):

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/client/random_forest.pyc
  in _model_fn(features, labels)
      128     if labels is not None:
      129       training_loss = graph_builder.training_loss(
  --> 130           features, labels, name=LOSS_NAME)
      131       training_graph = control_flow_ops.group(
      132           graph_builder.training_graph(

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in training_loss(self, features, labels, name)
      559
      560   def training_loss(self, features, labels, name='training_loss'):
  --> 561     return array_ops.identity(self._get_loss(features, labels), name=name)
      562
      563

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in _get_loss(self, features, labels)
      548     self._loss = control_flow_ops.cond(
      549         self.average_size() > 0, _average_loss,
  --> 550         lambda: constant_op.constant(sys.maxsize, dtype=dtypes.float32))
      551
      552     return self._loss

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.pyc
  in cond(pred, fn1, fn2, name)    1757     context_t =
  CondContext(pred, pivot_1, branch=1)    1758     context_t.Enter()
  -> 1759     orig_res, res_t = context_t.BuildCondBranch(fn1)    1760     context_t.ExitResult(res_t)    1761     context_t.Exit()

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.pyc
  in BuildCondBranch(self, fn)    1658   def BuildCondBranch(self, fn):
  1659     """Add the subgraph defined by fn() to the graph."""
  -> 1660     r = fn()    1661     original_r = r    1662     result = []

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in _average_loss()
      544       probs = self.inference_graph(features)
      545       return math_ops.reduce_sum(self.loss_fn(
  --> 546           probs, labels)) / math_ops.to_float(array_ops.shape(labels)[0])
      547
      548     self._loss = control_flow_ops.cond(

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in _loss(probs, targets)
      508   def _loss(probs, targets):
      509     if targets.get_shape().ndims > 1:
  --> 510       targets = array_ops.squeeze(targets, squeeze_dims=[1])
      511     one_hot_labels = array_ops.one_hot(
      512         math_ops.to_int32(targets),

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.pyc
  in squeeze(input, axis, name, squeeze_dims)    2270   if
  np.isscalar(axis):    2271     axis = [axis]
  -> 2272   return gen_array_ops._squeeze(input, axis, name)    2273     2274

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.pyc
  in _squeeze(input, squeeze_dims, name)    3496   """    3497   result
  = _op_def_lib.apply_op("Squeeze", input=input,
  -> 3498                                 squeeze_dims=squeeze_dims, name=name)    3499   return result    3500

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.pyc
  in apply_op(self, op_type_name, name, **keywords)
      761         op = g.create_op(op_type_name, inputs, output_types, name=scope,
      762                          input_types=input_types, attrs=attr_protos,
  --> 763                          op_def=op_def)
      764         if output_structure:
      765           outputs = op.outputs

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc
  in create_op(self, op_type, inputs, dtypes, input_types, name, attrs,
  op_def, compute_shapes, compute_device)    2395

  original_op=self._default_original_op, op_def=op_def)    2396     if
  compute_shapes:
  -> 2397       set_shapes_for_outputs(ret)    2398     self._add_op(ret)    2399

  self._record_op_seen_by_control_dependencies(ret)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc
  in set_shapes_for_outputs(op)    1755       shape_func =
  _call_cpp_shape_fn_and_require_op    1756
  -> 1757   shapes = shape_func(op)    1758   if shapes is None:    1759     raise RuntimeError(

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc
  in call_with_requiring(op)    1705     1706   def
  call_with_requiring(op):
  -> 1707     return call_cpp_shape_fn(op, require_shape_fn=True)    1708     1709   _call_cpp_shape_fn_and_require_op =
  call_with_requiring

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.pyc
  in call_cpp_shape_fn(op, input_tensors_needed,
  input_tensors_as_shapes_needed, debug_python_shape_fn,
  require_shape_fn)
      608     res = _call_cpp_shape_fn_impl(op, input_tensors_needed,
      609                                   input_tensors_as_shapes_needed,
  --> 610                                   debug_python_shape_fn, require_shape_fn)
      611     if not isinstance(res, dict):
      612       # Handles the case where _call_cpp_shape_fn_impl calls unknown_shape(op).

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.pyc
  in _call_cpp_shape_fn_impl(op, input_tensors_needed,
  input_tensors_as_shapes_needed, debug_python_shape_fn,
  require_shape_fn)
      673       missing_shape_fn = True
      674     else:
  --> 675       raise ValueError(err.message)
      676
      677   if missing_shape_fn:

ValueError: Can not squeeze dim[1], expected a dimension of 1, got 7
  for 'cond/Squeeze' (op: 'Squeeze') with input shapes: [?,7].

答:
Right now, when using TrainingLossForest it assumes a classification problem.  I will fix this internally, but for now you can get around it with something like:

```<code>from tensorflow.contrib.losses.python.losses import loss_ops

def _loss_fn(values, targets):
  return loss_ops.mean_squared_error(values, targets)

def _builder_class(params, **kwargs):
  return tensor_forest.TrainingLossForest(
      params, loss_fn=_loss_fn, **kwargs)

TensorForestEstimator(..., graph_builder_class=_builder_class)
</code>```

Or whatever loss function you want (MSE here as example).  Also, simply using (graph_builder_class = tensor_forest.RandomForestGraphs) should suffice, but the loss is the number of nodes, so training stops when the forest stops growing or reaches max_nodes, which is maybe not what you want.

ContentLicense: CC BY-SA 3.0

Body:
Code :
    from sklearn import cross_validation as cv
    import numpy as np
    from tensorflow.contrib.learn.python.learn.estimators import estimator
    from tensorflow.contrib.tensor_forest.python import tensor_forest

X = np.array([[  74.,  166.,  331.,  161.,  159.,  181.,  180.],
   [ 437.,  427.,  371.,  361.,  393.,  465.,  464.],
   [ 546.,  564.,  588.,  595.,  536.,  537.,  520.],
   [  89.,   89.,   87.,   87.,  108.,  113.,  111.],
   [  75.,   90.,   74.,   89.,  130.,  140.,  135.]])
Y = np.array([[ 51.,  43.,  29.,  43.,  43.,  41.,  42.],
   [ 22.,  23.,  26.,  27.,  25.,  19.,  19.],
   [  7.,   7.,   5.,   5.,   9.,   8.,  10.],
   [ 55.,  54.,  55.,  53.,  51.,  51.,  51.],
   [ 58.,  57.,  57.,  58.,  55.,  55.,  55.]])
train_X, test_X, train_Y, test_Y = cv.train_test_split(X, Y,
test_size=0.50, random_state=42)

def build_estimator() :
 params = tensor_forest.ForestHParams(num_classes=7, num_features=7,
 num_trees=30, max_nodes=100)
 graph_builder_class = tensor_forest.RandomForestGraphs

 graph_builder_class = tensor_forest.TrainingLossForest
 return estimator.SKCompat(random_forest.TensorForestEstimator(
   params, graph_builder_class=graph_builder_class,
   model_dir=None))
est = build_estimator()
train_X = train_X.astype(dtype = np.float32)
train_Y = train_Y.astype(dtype = np.float32)
est = est.fit(x=train_X, y=train_Y, batch_size = 100)

My both input and output shape is [Number_of_samples,7]. It perfectly runs with scikitlearn random forest classifier. However for tf learn, I get the following error when fitting the estimator :

INFO:tensorflow:Constructing forest with params =
  INFO:tensorflow:{'valid_leaf_threshold': 1, 'split_after_samples':
  250, 'num_output_columns': 8, 'feature_bagging_fraction': 1.0,
  'split_initializations_per_input': 1, 'bagged_features': None,
  'min_split_samples': 5, 'max_nodes': 100, 'num_features': 7,
  'num_trees': 30, 'num_splits_to_consider': 7, 'base_random_seed': 0,
  'num_outputs': 1, 'dominate_fraction': 0.99, 'max_fertile_nodes': 50,
  'bagged_num_features': 7, 'dominate_method': 'bootstrap',
  'bagging_fraction': 1.0, 'regression': False, 'num_classes': 7}

ValueErrorTraceback (most recent call last)
   in ()
  ----> 1 est = est.fit(x=train_X, y=train_Y, batch_size = 100)

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in fit(self, x, y, batch_size, steps, max_steps, monitors)    1351

  steps=steps,    1352                         max_steps=max_steps,
  -> 1353                         monitors=all_monitors)    1354     return self    1355

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/client/random_forest.pyc
  in fit(self, x, y, input_fn, steps, batch_size, monitors, max_steps)
      262     elif input is not None:
      263       self._estimator.fit(input_fn=input_fn, steps=steps, monitors=monitors,
  --> 264                           max_steps=max_steps)
      265     else:
      266       raise ValueError('fit: Must provide either both x and y or input_fn.')

/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.pyc
  in new_func(*args, **kwargs)
      278             _call_location(), decorator_utils.get_qualified_name(func),
      279             func.module, arg_name, date, instructions)
  --> 280       return func(*args, **kwargs)
      281     new_func.doc = _add_deprecated_arg_notice_to_docstring(
      282         func.doc, date, instructions)

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in fit(self, x, y, input_fn, steps, batch_size, monitors, max_steps)
      424       hooks.append(basic_session_run_hooks.StopAtStepHook(steps, max_steps))
      425
  --> 426     loss = self._train_model(input_fn=input_fn, hooks=hooks)
      427     logging.info('Loss for final step: %s.', loss)
      428     return self

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _train_model(self, input_fn, hooks)
      932       features, labels = input_fn()
      933       self._check_inputs(features, labels)
  --> 934       model_fn_ops = self._call_legacy_get_train_ops(features, labels)
      935       ops.add_to_collection(ops.GraphKeys.LOSSES, model_fn_ops.loss)
      936       all_hooks.extend([

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _call_legacy_get_train_ops(self, features, labels)    1001     1002
  def _call_legacy_get_train_ops(self, features, labels):
  -> 1003     train_ops = self._get_train_ops(features, labels)    1004     if isinstance(train_ops, model_fn_lib.ModelFnOps):  # Default
  signature    1005       return train_ops

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _get_train_ops(self, features, labels)    1160       ModelFnOps
  object.    1161     """
  -> 1162     return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)    1163     1164   def
  _get_eval_ops(self, features, labels, metrics):

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.pyc
  in _call_model_fn(self, features, labels, mode)    1131     if
  'model_dir' in model_fn_args:    1132       kwargs['model_dir'] =
  self.model_dir
  -> 1133     model_fn_results = self._model_fn(features, labels, **kwargs)    1134     1135     if isinstance(model_fn_results, model_fn_lib.ModelFnOps):

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/client/random_forest.pyc
  in _model_fn(features, labels)
      128     if labels is not None:
      129       training_loss = graph_builder.training_loss(
  --> 130           features, labels, name=LOSS_NAME)
      131       training_graph = control_flow_ops.group(
      132           graph_builder.training_graph(

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in training_loss(self, features, labels, name)
      559
      560   def training_loss(self, features, labels, name='training_loss'):
  --> 561     return array_ops.identity(self._get_loss(features, labels), name=name)
      562
      563

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in _get_loss(self, features, labels)
      548     self._loss = control_flow_ops.cond(
      549         self.average_size() > 0, _average_loss,
  --> 550         lambda: constant_op.constant(sys.maxsize, dtype=dtypes.float32))
      551
      552     return self._loss

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.pyc
  in cond(pred, fn1, fn2, name)    1757     context_t =
  CondContext(pred, pivot_1, branch=1)    1758     context_t.Enter()
  -> 1759     orig_res, res_t = context_t.BuildCondBranch(fn1)    1760     context_t.ExitResult(res_t)    1761     context_t.Exit()

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.pyc
  in BuildCondBranch(self, fn)    1658   def BuildCondBranch(self, fn):
  1659     """Add the subgraph defined by fn() to the graph."""
  -> 1660     r = fn()    1661     original_r = r    1662     result = []

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in _average_loss()
      544       probs = self.inference_graph(features)
      545       return math_ops.reduce_sum(self.loss_fn(
  --> 546           probs, labels)) / math_ops.to_float(array_ops.shape(labels)[0])
      547
      548     self._loss = control_flow_ops.cond(

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/python/tensor_forest.pyc
  in _loss(probs, targets)
      508   def _loss(probs, targets):
      509     if targets.get_shape().ndims > 1:
  --> 510       targets = array_ops.squeeze(targets, squeeze_dims=[1])
      511     one_hot_labels = array_ops.one_hot(
      512         math_ops.to_int32(targets),

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.pyc
  in squeeze(input, axis, name, squeeze_dims)    2270   if
  np.isscalar(axis):    2271     axis = [axis]
  -> 2272   return gen_array_ops._squeeze(input, axis, name)    2273     2274

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.pyc
  in _squeeze(input, squeeze_dims, name)    3496   """    3497   result
  = _op_def_lib.apply_op("Squeeze", input=input,
  -> 3498                                 squeeze_dims=squeeze_dims, name=name)    3499   return result    3500

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.pyc
  in apply_op(self, op_type_name, name, **keywords)
      761         op = g.create_op(op_type_name, inputs, output_types, name=scope,
      762                          input_types=input_types, attrs=attr_protos,
  --> 763                          op_def=op_def)
      764         if output_structure:
      765           outputs = op.outputs

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc
  in create_op(self, op_type, inputs, dtypes, input_types, name, attrs,
  op_def, compute_shapes, compute_device)    2395

  original_op=self._default_original_op, op_def=op_def)    2396     if
  compute_shapes:
  -> 2397       set_shapes_for_outputs(ret)    2398     self._add_op(ret)    2399

  self._record_op_seen_by_control_dependencies(ret)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc
  in set_shapes_for_outputs(op)    1755       shape_func =
  _call_cpp_shape_fn_and_require_op    1756
  -> 1757   shapes = shape_func(op)    1758   if shapes is None:    1759     raise RuntimeError(

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc
  in call_with_requiring(op)    1705     1706   def
  call_with_requiring(op):
  -> 1707     return call_cpp_shape_fn(op, require_shape_fn=True)    1708     1709   _call_cpp_shape_fn_and_require_op =
  call_with_requiring

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.pyc
  in call_cpp_shape_fn(op, input_tensors_needed,
  input_tensors_as_shapes_needed, debug_python_shape_fn,
  require_shape_fn)
      608     res = _call_cpp_shape_fn_impl(op, input_tensors_needed,
      609                                   input_tensors_as_shapes_needed,
  --> 610                                   debug_python_shape_fn, require_shape_fn)
      611     if not isinstance(res, dict):
      612       # Handles the case where _call_cpp_shape_fn_impl calls unknown_shape(op).

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.pyc
  in _call_cpp_shape_fn_impl(op, input_tensors_needed,
  input_tensors_as_shapes_needed, debug_python_shape_fn,
  require_shape_fn)
      673       missing_shape_fn = True
      674     else:
  --> 675       raise ValueError(err.message)
      676
      677   if missing_shape_fn:

ValueError: Can not squeeze dim[1], expected a dimension of 1, got 7
  for 'cond/Squeeze' (op: 'Squeeze') with input shapes: [?,7].

Body:
Right now, when using TrainingLossForest it assumes a classification problem.  I will fix this internally, but for now you can get around it with something like:

from tensorflow.contrib.losses.python.losses import loss_ops

def _loss_fn(values, targets):
  return loss_ops.mean_squared_error(values, targets)

def _builder_class(params, **kwargs):
  return tensor_forest.TrainingLossForest(
      params, loss_fn=_loss_fn, **kwargs)

TensorForestEstimator(..., graph_builder_class=_builder_class)

Or whatever loss function you want (MSE here as example).  Also, simply using (graph_builder_class = tensor_forest.RandomForestGraphs) should suffice, but the loss is the number of nodes, so training stops when the forest stops growing or reaches max_nodes, which is maybe not what you want.

ContentLicense: CC BY-SA 4.0


问:
Spring Integration - JMS to Kafka message transfer - End to End Transaction
I am consuming messages from JMS ActiveMQ using the following code:

```<code><jms:message-driven-channel-adapter
        id="helloJMSAdapater" destination="helloJMSQueue" connection-factory="jmsConnectionfactory"
        channel="helloChannel" extract-payload="true" />
<integration:channel id="helloChannel" />
</code>```

My requirement is to consume from here and post it to Kafka outbound adapter. Using the below config:

```<code><int-kafka:outbound-channel-adapter
            id="kafkaOutboundChannelAdapter"
            kafka-producer-context-ref="kafkaProducerContext"
            channel="inputToKafka">
</int-kafka:outbound-channel-adapter>
</code>```

Here are what i want to achieve:

My queue is a durable topic and dont want to acknowledge the records unless it is successfully published to Kafka. In short, i want to have a transaction behaviour from consuming message from jms to publishing it to Kafka.

I noticed that my messages are immediately dequeued and if processing encounters some exception, i am unable to reprocess it. I dont want that to happen.

Also, when kafka encounters some issue, i want it to be returned to some method so that i can persist the failure message and as said before does not want to acknowledge it.

I am really struggling to get it to work. Can someone please help me out?

答:
You really can have transaction-manager on the <jms:message-driven-channel-adapter> to start TX.

When <int-kafka:outbound-channel-adapter> throws an exception it causes the TX to be ralled back and therefore the message will be requeued.

If you are interested in the persisting errors, there is an error-channel option on the <jms:message-driven-channel-adapter>, but you still have to re-throw exception to let TX to rallback.

To make all that to work you should be sure that there is only single thread from the begging to the end. No <queue> or executor channel in the flow.

Also it isn't clear why do you use so old Apache Kafka still...

Body:
I am consuming messages from JMS ActiveMQ using the following code:

<jms:message-driven-channel-adapter
        id="helloJMSAdapater" destination="helloJMSQueue" connection-factory="jmsConnectionfactory"
        channel="helloChannel" extract-payload="true" />
<integration:channel id="helloChannel" />

My requirement is to consume from here and post it to Kafka outbound adapter. Using the below config:

<int-kafka:outbound-channel-adapter
            id="kafkaOutboundChannelAdapter"
            kafka-producer-context-ref="kafkaProducerContext"
            channel="inputToKafka">
</int-kafka:outbound-channel-adapter>

Here are what i want to achieve:

My queue is a durable topic and dont want to acknowledge the records unless it is successfully published to Kafka. In short, i want to have a transaction behaviour from consuming message from jms to publishing it to Kafka.

I noticed that my messages are immediately dequeued and if processing encounters some exception, i am unable to reprocess it. I dont want that to happen.

Also, when kafka encounters some issue, i want it to be returned to some method so that i can persist the failure message and as said before does not want to acknowledge it.

I am really struggling to get it to work. Can someone please help me out?


问:
c# pick out data form json
I want to be able to use c# to extract all the data point sin the below json. I need all the values of all the StandardId. not just a single data point but rather all instances of StandardId

```<code>{
  "CreatedBy": null,
  "CanBeRemoved": false,
  "ConfigurationItems": [ "" ],
  "ApprovalReasons": [
    {
      "AssociatedCI": "",
      "AssociatedRuleName": "BRS: ",
      "AssociatedRuleApprovalType": null,
      "AssociatedRulePartyType": "Group",
      "AssociatedRulePartyName": "Digital ",
      "AssociatedAdditionalComment": "Added to all "
    }
  ],
  "PossibleApprovers": [
    {
      "Approver": {
        "Display": "Jag",
        "StandardId": "I6",
        "RoleName": null,
        "FullName": null,
        "LineOfBusiness": null,
        "ErrorMessage": null
      },
      "IsEscalation": false,
      "IsDelegate": false
    },
    {
      "Approver": {
        "Display": "Will",
        "StandardId": "U55",
        "RoleName": null,
        "FullName": null,
        "LineOfBusiness": null,
        "ErrorMessage": null
      },
      "IsEscalation": false,
      "IsDelegate": false
    },

    {
      "Approver": {
        "Display": "Su",
        "StandardId": "U2",
        "RoleName": null,
        "FullName": null,
        "LineOfBusiness": null,
        "ErrorMessage": null
      },
      "IsEscalation": false,
      "IsDelegate": false
    }
  ],
  "OriginalApprovals": [],
  "AggregatedApproval": null,
  "IsAggregated": false,
  "AggregationId": 0,
  "UpdatedBy": null,
  "UpdatedDt": null,
  "IsGroupActive": false
}
</code>```

答:
The easiest way is the one share by @maccettura.

Create a C# object

Open json2csharp a generate your class. Visual Studio can generate it for you too:

Deserialize your class with JSON.NET

The doc is easy to use and you can find your information in the first page.

```<code>Foo foo = JsonConvert.DeserializeObject<Foo>(json);
</code>```

Demo

Try it online

```<code>using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        string json = @"{
""CreatedBy"": null,
""CanBeRemoved"": false,
""ConfigurationItems"": [ """" ],
""ApprovalReasons"": [
{
  ""AssociatedCI"": """",
  ""AssociatedRuleName"": ""BRS: "",
  ""AssociatedRuleApprovalType"": null,
  ""AssociatedRulePartyType"": ""Group"",
  ""AssociatedRulePartyName"": ""Digital "",
  ""AssociatedAdditionalComment"": ""Added to all ""
}],
""PossibleApprovers"": [
{
  ""Approver"": {
    ""Display"": ""Jag"",
    ""StandardId"": ""I6"",
    ""RoleName"": null,
    ""FullName"": null,
    ""LineOfBusiness"": null,
    ""ErrorMessage"": null
  },
  ""IsEscalation"": false,
  ""IsDelegate"": false
},
{
  ""Approver"": {
    ""Display"": ""Will"",
    ""StandardId"": ""U55"",
    ""RoleName"": null,
    ""FullName"": null,
    ""LineOfBusiness"": null,
    ""ErrorMessage"": null
  },
  ""IsEscalation"": false,
  ""IsDelegate"": false
},
{
  ""Approver"": {
    ""Display"": ""Su"",
    ""StandardId"": ""U2"",
    ""RoleName"": null,
    ""FullName"": null,
    ""LineOfBusiness"": null,
    ""ErrorMessage"": null
  },
  ""IsEscalation"": false,
  ""IsDelegate"": false
}],
""OriginalApprovals"": [],
""AggregatedApproval"": null,
""IsAggregated"": false,
""AggregationId"": 0,
""UpdatedBy"": null,
""UpdatedDt"": null,
""IsGroupActive"": false
}";

        var m = JsonConvert.DeserializeObject<RootObject>(json);

        foreach(var possibleApprovers in m.PossibleApprovers)
        {
            Console.WriteLine(possibleApprovers.Approver.StandardId);
        }
    }

    public class ApprovalReason
    {
        public string AssociatedCI { get; set; }
        public string AssociatedRuleName { get; set; }
        public object AssociatedRuleApprovalType { get; set; }
        public string AssociatedRulePartyType { get; set; }
        public string AssociatedRulePartyName { get; set; }
        public string AssociatedAdditionalComment { get; set; }
    }

    public class Approver
    {
        public string Display { get; set; }
        public string StandardId { get; set; }
        public object RoleName { get; set; }
        public object FullName { get; set; }
        public object LineOfBusiness { get; set; }
        public object ErrorMessage { get; set; }
    }

    public class PossibleApprover
    {
        public Approver Approver { get; set; }
        public bool IsEscalation { get; set; }
        public bool IsDelegate { get; set; }
    }

    public class RootObject
    {
        public object CreatedBy { get; set; }
        public bool CanBeRemoved { get; set; }
        public List<string> ConfigurationItems { get; set; }
        public List<ApprovalReason> ApprovalReasons { get; set; }
        public List<PossibleApprover> PossibleApprovers { get; set; }
        public List<object> OriginalApprovals { get; set; }
        public object AggregatedApproval { get; set; }
        public bool IsAggregated { get; set; }
        public int AggregationId { get; set; }
        public object UpdatedBy { get; set; }
        public object UpdatedDt { get; set; }
        public bool IsGroupActive { get; set; }
    }
}
</code>```

Title: c# pick out data form json

Body:
I want to be able to use c# to extract all the data point sin the below json. I need all the values of all the StandardId. not just a single data point but rather all instances of StandardId

{
  "CreatedBy": null,
  "CanBeRemoved": false,
  "ConfigurationItems": [ "" ],
  "ApprovalReasons": [
    {
      "AssociatedCI": "",
      "AssociatedRuleName": "BRS: ",
      "AssociatedRuleApprovalType": null,
      "AssociatedRulePartyType": "Group",
      "AssociatedRulePartyName": "Digital ",
      "AssociatedAdditionalComment": "Added to all "
    }
  ],
  "PossibleApprovers": [
    {
      "Approver": {
        "Display": "Jag",
        "StandardId": "I6",
        "RoleName": null,
        "FullName": null,
        "LineOfBusiness": null,
        "ErrorMessage": null
      },
      "IsEscalation": false,
      "IsDelegate": false
    },
    {
      "Approver": {
        "Display": "Will",
        "StandardId": "U55",
        "RoleName": null,
        "FullName": null,
        "LineOfBusiness": null,
        "ErrorMessage": null
      },
      "IsEscalation": false,
      "IsDelegate": false
    },

    {
      "Approver": {
        "Display": "Su",
        "StandardId": "U2",
        "RoleName": null,
        "FullName": null,
        "LineOfBusiness": null,
        "ErrorMessage": null
      },
      "IsEscalation": false,
      "IsDelegate": false
    }
  ],
  "OriginalApprovals": [],
  "AggregatedApproval": null,
  "IsAggregated": false,
  "AggregationId": 0,
  "UpdatedBy": null,
  "UpdatedDt": null,
  "IsGroupActive": false
}

Body:
The easiest way is the one share by @maccettura.

Create a C# object

Open json2csharp a generate your class. Visual Studio can generate it for you too:

Deserialize your class with JSON.NET

The doc is easy to use and you can find your information in the first page.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Demo

Try it online

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        string json = @"{
""CreatedBy"": null,
""CanBeRemoved"": false,
""ConfigurationItems"": [ """" ],
""ApprovalReasons"": [
{
  ""AssociatedCI"": """",
  ""AssociatedRuleName"": ""BRS: "",
  ""AssociatedRuleApprovalType"": null,
  ""AssociatedRulePartyType"": ""Group"",
  ""AssociatedRulePartyName"": ""Digital "",
  ""AssociatedAdditionalComment"": ""Added to all ""
}],
""PossibleApprovers"": [
{
  ""Approver"": {
    ""Display"": ""Jag"",
    ""StandardId"": ""I6"",
    ""RoleName"": null,
    ""FullName"": null,
    ""LineOfBusiness"": null,
    ""ErrorMessage"": null
  },
  ""IsEscalation"": false,
  ""IsDelegate"": false
},
{
  ""Approver"": {
    ""Display"": ""Will"",
    ""StandardId"": ""U55"",
    ""RoleName"": null,
    ""FullName"": null,
    ""LineOfBusiness"": null,
    ""ErrorMessage"": null
  },
  ""IsEscalation"": false,
  ""IsDelegate"": false
},
{
  ""Approver"": {
    ""Display"": ""Su"",
    ""StandardId"": ""U2"",
    ""RoleName"": null,
    ""FullName"": null,
    ""LineOfBusiness"": null,
    ""ErrorMessage"": null
  },
  ""IsEscalation"": false,
  ""IsDelegate"": false
}],
""OriginalApprovals"": [],
""AggregatedApproval"": null,
""IsAggregated"": false,
""AggregationId"": 0,
""UpdatedBy"": null,
""UpdatedDt"": null,
""IsGroupActive"": false
}";

        var m = JsonConvert.DeserializeObject<RootObject>(json);

        foreach(var possibleApprovers in m.PossibleApprovers)
        {
            Console.WriteLine(possibleApprovers.Approver.StandardId);
        }
    }

    public class ApprovalReason
    {
        public string AssociatedCI { get; set; }
        public string AssociatedRuleName { get; set; }
        public object AssociatedRuleApprovalType { get; set; }
        public string AssociatedRulePartyType { get; set; }
        public string AssociatedRulePartyName { get; set; }
        public string AssociatedAdditionalComment { get; set; }
    }

    public class Approver
    {
        public string Display { get; set; }
        public string StandardId { get; set; }
        public object RoleName { get; set; }
        public object FullName { get; set; }
        public object LineOfBusiness { get; set; }
        public object ErrorMessage { get; set; }
    }

    public class PossibleApprover
    {
        public Approver Approver { get; set; }
        public bool IsEscalation { get; set; }
        public bool IsDelegate { get; set; }
    }

    public class RootObject
    {
        public object CreatedBy { get; set; }
        public bool CanBeRemoved { get; set; }
        public List<string> ConfigurationItems { get; set; }
        public List<ApprovalReason> ApprovalReasons { get; set; }
        public List<PossibleApprover> PossibleApprovers { get; set; }
        public List<object> OriginalApprovals { get; set; }
        public object AggregatedApproval { get; set; }
        public bool IsAggregated { get; set; }
        public int AggregationId { get; set; }
        public object UpdatedBy { get; set; }
        public object UpdatedDt { get; set; }
        public bool IsGroupActive { get; set; }
    }
}


问:
Get feature extent using gdal/ogr
This feels like something that should already have a function to do easily, but I can't find one.

What I'm ultimately trying to do: I have a shapefile with 3 features that show bounding boxes; I want to use one of those features to select all the features within it in another shapefile or polygons. I have this running using ogr2ogr, using the -clipsrc and -clipsrcwhere flags to select my bounding box from my bounding box shapefile. This works great, but I cannot include or disclude polygons that fall along the border, and I do not want them clipped. So, I figured I'd use the -spat flag instead and just import the bounding box polygon extent.

I know I can get the extent of my polygon with:

```<code>polygon = 'mouth'
inDriver = ogr.GetDriverByName("ESRI Shapefile")
inDataSource = inDriver.Open(extent_shpfile, 1)
inLayer = inDataSource.GetLayer()
select = "name = '" + polygon + "'"
inLayer.SetAttributeFilter(select)
for feature in inLayer: #inLayer is always of size one because polygon is a unique value
    geom=feature.GetGeometryRef()
</code>```

From here I can parse out the values of geom to get the min and max x and y values. Is there not an ogr call to do this already (like inLayer.GetFeatureExtent() or inLayer.GetExtent(feature_fid)? The latter simply returns the layer extent, and the former doesn't exist, but having to parse it from the feature geometry feels clunky.

答:
Turns out there IS a built in function to do this, my 4 hours of searching (prior to the original post) just failed to bring it to light until I switched to working on something else and stumbled across it accidentally.

```<code>extent = geom.GetEnvelope()
</code>```

Hopefully this post will save someone else the headache of trying to find this function.

Title: Get feature extent using gdal/ogr

Body:
This feels like something that should already have a function to do easily, but I can't find one.

What I'm ultimately trying to do: I have a shapefile with 3 features that show bounding boxes; I want to use one of those features to select all the features within it in another shapefile or polygons. I have this running using ogr2ogr, using the -clipsrc and -clipsrcwhere flags to select my bounding box from my bounding box shapefile. This works great, but I cannot include or disclude polygons that fall along the border, and I do not want them clipped. So, I figured I'd use the -spat flag instead and just import the bounding box polygon extent.

I know I can get the extent of my polygon with:

polygon = 'mouth'
inDriver = ogr.GetDriverByName("ESRI Shapefile")
inDataSource = inDriver.Open(extent_shpfile, 1)
inLayer = inDataSource.GetLayer()
select = "name = '" + polygon + "'"
inLayer.SetAttributeFilter(select)
for feature in inLayer: #inLayer is always of size one because polygon is a unique value
    geom=feature.GetGeometryRef()

From here I can parse out the values of geom to get the min and max x and y values. Is there not an ogr call to do this already (like inLayer.GetFeatureExtent() or inLayer.GetExtent(feature_fid)? The latter simply returns the layer extent, and the former doesn't exist, but having to parse it from the feature geometry feels clunky.

Body:
Turns out there IS a built in function to do this, my 4 hours of searching (prior to the original post) just failed to bring it to light until I switched to working on something else and stumbled across it accidentally.

extent = geom.GetEnvelope()

Hopefully this post will save someone else the headache of trying to find this function.


问:
Rotate a string in C
I am trying to shift a string both left and right given the number of positions to shift the string by.

This is what I wrote so far but it does not work.

```<code>void Shift(char* string, shift)
{
    int length = strlen(string)-1;
    int i;
    char *buff;
    buff = malloc((sizeof(char) *shift) + 1);
    strncpy(buff, string, shift);
    buff[shift] = '/0';
    while (string[i + shift] != '/0')
        string[i++] = string[i + shift];
    strcat(string, buff);
}
</code>```

How can I fix this?
This should be the example:
shift = 1

HELLO ->
OHELL

答:
you can use XOR bitwise operator to swap characters and loop to reverse them.

```<code>#include <stdio.h>
#include <stdlib.h>

void reverse(char *a, int n) {

  for (int i=0, j=n-1; i < j; i++, j--) {
      a[i] = a[i] ^ a[j];
      a[j] = a[j] ^ a[i];
      a[i] = a[i] ^ a[j];
  }
}

int main(int argc, char const *argv[]) {

int k = 1; // shift count
int n = 5;
char a[] = "HELLO";

reverse(&a[n-k], k); // reverse end of array
reverse(a, n-k);     // reverse beginning of array
reverse(a, n);       // reverse entire array

// print output
for (int i=0; i < n; i++) {
    printf("%c\n", a[i]);
}

return 0;
</code>```

}

Title: Rotate a string in C

Body:
I am trying to shift a string both left and right given the number of positions to shift the string by.

This is what I wrote so far but it does not work.

void Shift(char* string, shift)
{
    int length = strlen(string)-1;
    int i;
    char *buff;
    buff = malloc((sizeof(char) *shift) + 1);
    strncpy(buff, string, shift);
    buff[shift] = '/0';
    while (string[i + shift] != '/0')
        string[i++] = string[i + shift];
    strcat(string, buff);
}

How can I fix this?
This should be the example:
shift = 1

HELLO ->
OHELL

Body:
you can use XOR bitwise operator to swap characters and loop to reverse them.

#include <stdio.h>
#include <stdlib.h>

void reverse(char *a, int n) {

  for (int i=0, j=n-1; i < j; i++, j--) {
      a[i] = a[i] ^ a[j];
      a[j] = a[j] ^ a[i];
      a[i] = a[i] ^ a[j];
  }
}

int main(int argc, char const *argv[]) {

int k = 1; // shift count
int n = 5;
char a[] = "HELLO";

reverse(&a[n-k], k); // reverse end of array
reverse(a, n-k);     // reverse beginning of array
reverse(a, n);       // reverse entire array

// print output
for (int i=0; i < n; i++) {
    printf("%c\n", a[i]);
}

return 0;

}


问:
Origin of try/catch/finally syntax
Question for the etymology wizards out there: which programming language was the first to use the try/catch/finally syntax found in today's Java/.NET languages?</p>

答:
Posted on Twitter by Mike Fikes, shared with me by Paweł Kapała:

MacLisp added the function ERR, which signals an error. If ERR is invoked within the dynamic context of an ERRSET form, then the argument to ERR is returned as the value of the ERRSET form.

Programmers soon began to use ERRSET and ERR not to trap and signal errors but for more general control purposes (dynamic non-local exits). Unfortunately, this use of ERRSET also quietly trapped unexpected errors, making programs harder to debug. A new pair of primitives, CATCH and THROW, was introduced into MacLisp in June 1972 [emphasis mine] so that ERRSET could be reserved for its intended use of error trapping.

The lesson of ERRSET and CATCH is important. The designers of ERRSET and later ERR had in mind a particular situation and defined a pair of primitives to address that situation. But because these facilities provided a combination of useful and powerful capabilities (error trapping plus dynamic non-local exits), programmers began to use these facilities in unintended ways. Then the designers had to go back and split the desired into pieces with alternative interfaces. This pattern of careful design, unintended use, and later redesign is common in the evolution of Lisp.

— from “The Evolution of Lisp,” by Guy Steele and Richard Gabriel

Source: https://twitter.com/mfikes/status/881943130588753920

“The Evolution of Lisp,” by Guy Steele and Richard Gabriel
— Mike Fikes (@mfikes) July 3, 2017

```

Title: Origin of try/catch/finally syntax

Body:
Posted on Twitter by Mike Fikes, shared with me by Paweł Kapała:

MacLisp added the function ERR, which signals an error. If ERR is invoked within the dynamic context of an ERRSET form, then the argument to ERR is returned as the value of the ERRSET form.

Programmers soon began to use ERRSET and ERR not to trap and signal errors but for more general control purposes (dynamic non-local exits). Unfortunately, this use of ERRSET also quietly trapped unexpected errors, making programs harder to debug. A new pair of primitives, CATCH and THROW, was introduced into MacLisp in June 1972 [emphasis mine] so that ERRSET could be reserved for its intended use of error trapping.

The lesson of ERRSET and CATCH is important. The designers of ERRSET and later ERR had in mind a particular situation and defined a pair of primitives to address that situation. But because these facilities provided a combination of useful and powerful capabilities (error trapping plus dynamic non-local exits), programmers began to use these facilities in unintended ways. Then the designers had to go back and split the desired into pieces with alternative interfaces. This pattern of careful design, unintended use, and later redesign is common in the evolution of Lisp.

— from “The Evolution of Lisp,” by Guy Steele and Richard Gabriel

Source: https://twitter.com/mfikes/status/881943130588753920

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">“The Evolution of Lisp,” by Guy Steele and Richard Gabriel</p>&mdash; Mike Fikes (@mfikes) <a href="https://twitter.com/mfikes/status/881950560508940288">July 3, 2017</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>


问:
Best way to represent constraints on values in Scala?
What is the best way to express that, say, an Int field or parameter should never be negative?

The first thing that comes to mind is an annotation on the type, like case class Foo(x: Int @NotNegative). But I'd have to invent my own annotation, and there wouldn't be any sort of compile-time checking or anything.

Is there a better way?

答:
Why not using a separate data type?

```<code>class Natural private (val value: Int) {
   require(value >= 0)

   def +(that:Natural) = new Natural(this.value + that.value)
   def *(that:Natural) = new Natural(this.value * that.value)
   def %(that:Natural) = new Natural(this.value % that.value)
   def |-|(that:Natural) = Natural.abs(this.value - that.value) //absolute difference

   override def toString = value.toString
}

object Natural {
  implicit def nat2int(n:Natural) = n.value
  def abs(n:Int) = new Natural(math.abs(n))
}
</code>```

Usage:

```<code>val a = Natural.abs(4711)
val b = Natural.abs(-42)
val c = a + b
val d = b - a  // works due to implicit conversion, but d is typed as Int
println(a < b) //works due implicit conversion
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Why not using a separate data type?

class Natural private (val value: Int) {
   require(value >= 0)

   def +(that:Natural) = new Natural(this.value + that.value)
   def *(that:Natural) = new Natural(this.value * that.value)
   def %(that:Natural) = new Natural(this.value % that.value)
   def |-|(that:Natural) = Natural.abs(this.value - that.value) //absolute difference

   override def toString = value.toString
}

object Natural {
  implicit def nat2int(n:Natural) = n.value
  def abs(n:Int) = new Natural(math.abs(n))
}

Usage:

val a = Natural.abs(4711)
val b = Natural.abs(-42)
val c = a + b
val d = b - a  // works due to implicit conversion, but d is typed as Int
println(a < b) //works due implicit conversion


问:
How to implement caching with Kleisli
I've followed the design principle from the book Functional and Reactive Modeling.

So all the service methods return Kleisli.

The question is how can I add an updatable cache over these services.

Here is my current implementation, is there a better way (existing combinators, more functional approach, …) ?

```<code>import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scalaz.Kleisli

trait Repository {
  def all : Future[Seq[String]]
  def replaceAll(l: Seq[String]) : Future[Unit]
}

trait Service {
  def all = Kleisli[Future, Repository, Seq[String]] { _.all }
  def replaceAll(l: Seq[String]) = Kleisli[Future, Repository, Unit] { _.replaceAll(l) }
}

trait CacheService extends Service {
  var cache : Seq[String] = Seq.empty[String]

  override def all = Kleisli[Future, Repository, Seq[String]] { repo: Repository =>
    if (cache.isEmpty) {
      val fcache = repo.all
      fcache.foreach(cache = _)
      fcache
    }
      else
      Future.successful(cache)
  }

  override def replaceAll(l: Seq[String]) = Kleisli[Future, Repository, Unit] { repo: Repository =>
    cache = l
    repo.replaceAll(l)
  }
}

object CacheTest extends App {
  val repo = new Repository {
    override def replaceAll(l: Seq[String]): Future[Unit] = Future.successful()
    override def all: Future[Seq[String]] = Future.successful(Seq("1","2","3"))
  }
  val service = new CacheService {}

  println(Await.result(service.all(repo), Duration.Inf))
  Await.result(service.replaceAll(List("a"))(repo), Duration.Inf)
  println(Await.result(service.all(repo), Duration.Inf))
}
</code>```

[update] Regarding the comment of @timotyperigo, I've implementing the caching at the repository level

```<code>class CachedTipRepository(val self:TipRepository) extends TipRepository {
  var cache: Seq[Tip] = Seq.empty[Tip]

  override def all: Future[Seq[Tip]] = …

  override def replace(tips: String): Unit = …
}
</code>```

I'm still interested for feedback to improve the design.

答:
Timothy is totally right: caching is an implementation feature of the repository (and not of the service). Implementation features / details should not be exposed in contracts and at this point you are doing good with your design (not with your implementation, though!)

Digging a little deeper in your design problem, it is interesting to you look at how  dependency injection can be done in Scala:

Constructor injection

Cake pattern

Reader monad

The cake pattern and the constructor injection have one similarity: dependencies are bound at creation time . With the Reader monad (Kleisli just provides an additional layer on top of it) you delay binding which results in more composability (due to the combinators), more testability and more flexibility

In case of decorating an existing TipRepository by adding caching functionality, the benefits of Kleisli would probably not be needed and they might even make the code harder to read. Using constructor injection seems appropriate, since it is the simplest pattern that let you do things "well"

Title: How to implement caching with Kleisli

Body:
I've followed the design principle from the book Functional and Reactive Modeling.

So all the service methods return Kleisli.

The question is how can I add an updatable cache over these services.

Here is my current implementation, is there a better way (existing combinators, more functional approach, …) ?

import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scalaz.Kleisli

trait Repository {
  def all : Future[Seq[String]]
  def replaceAll(l: Seq[String]) : Future[Unit]
}

trait Service {
  def all = Kleisli[Future, Repository, Seq[String]] { _.all }
  def replaceAll(l: Seq[String]) = Kleisli[Future, Repository, Unit] { _.replaceAll(l) }
}

trait CacheService extends Service {
  var cache : Seq[String] = Seq.empty[String]

  override def all = Kleisli[Future, Repository, Seq[String]] { repo: Repository =>
    if (cache.isEmpty) {
      val fcache = repo.all
      fcache.foreach(cache = _)
      fcache
    }
      else
      Future.successful(cache)
  }

  override def replaceAll(l: Seq[String]) = Kleisli[Future, Repository, Unit] { repo: Repository =>
    cache = l
    repo.replaceAll(l)
  }
}

object CacheTest extends App {
  val repo = new Repository {
    override def replaceAll(l: Seq[String]): Future[Unit] = Future.successful()
    override def all: Future[Seq[String]] = Future.successful(Seq("1","2","3"))
  }
  val service = new CacheService {}

  println(Await.result(service.all(repo), Duration.Inf))
  Await.result(service.replaceAll(List("a"))(repo), Duration.Inf)
  println(Await.result(service.all(repo), Duration.Inf))
}

[update] Regarding the comment of @timotyperigo, I've implementing the caching at the repository level

class CachedTipRepository(val self:TipRepository) extends TipRepository {
  var cache: Seq[Tip] = Seq.empty[Tip]

  override def all: Future[Seq[Tip]] = …

  override def replace(tips: String): Unit = …
}

I'm still interested for feedback to improve the design.


问:
Deploying project in Docker with Angular 4, Django and postgresql
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend with Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I assume that if I use Docker I don't have to create Procfile etc.? May the error be caused by lack of migration of database?

I have no idea that I'm moving into the right direction but I'm trying to migrate my database. Maybe my error is caused by lack of db?

When I run heroku run python manage.py migrate, I get:

django.db.utils.OperationalError: could not translate host name "db"
  to address: Name or service not known

Logs:

```<code>2017-07-07T10:27:30.448951+00:00 heroku[web.1]: State changed from crashed to starting
2017-07-07T10:27:30.436282+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:50.846928+00:00 heroku[web.1]: Starting process with command `python3`
2017-07-07T10:27:53.350381+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:53.365013+00:00 heroku[web.1]: State changed from starting to crashed
2017-07-07T10:27:53.876208+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=e1f8edfc-7dc4-4bd3-91be-0a853e948452 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.444860+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=361846d1-41cd-403a-989f-4c29a0d1179e fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.984059+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host= myproject.herokuapp.com request_id=658795c8-0ba7-4988-9d39-34601b1334c7 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:44.673789+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=63fbabdc-7ba7-4997-81be-c601a0d83368 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:53.091547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=a3943544-9dc4-44f0-b788-a462cdfba7d0 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:54.419623+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=eb5191e2-21d9-410c-823e-c57bb0fb7fa4 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
</code>```

Project tree:

```<code>├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── init.sql
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt
</code>```

Frontend's Dockerfile:

```<code># Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]
</code>```

Main directory's Dockerfile:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
</code>```

docker-compose.yml:

```<code>version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django
</code>```

init.sql:

```<code>CREATE USER myUser;
CREATE DATABASE myProject;
GRANT ALL PRIVILEGES ON DATABASE myProject TO myUser;
</code>```

答:
Looks to me you didn't linked the containers where needed. If you want db to be visible by django add the links directive to your docker-compose.yml:

```<code>...

  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
    links:
      - db
</code>```

This way the db hostname will be resolved correctly. Hopefully.

Hope this helps.
    ...

Body:
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend with Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I assume that if I use Docker I don't have to create Procfile etc.? May the error be caused by lack of migration of database?

I have no idea that I'm moving into the right direction but I'm trying to migrate my database. Maybe my error is caused by lack of db?

When I run heroku run python manage.py migrate, I get:

django.db.utils.OperationalError: could not translate host name "db"
  to address: Name or service not known

Logs:

2017-07-07T10:27:30.448951+00:00 heroku[web.1]: State changed from crashed to starting
2017-07-07T10:27:30.436282+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:50.846928+00:00 heroku[web.1]: Starting process with command `python3`
2017-07-07T10:27:53.350381+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:53.365013+00:00 heroku[web.1]: State changed from starting to crashed
2017-07-07T10:27:53.876208+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=e1f8edfc-7dc4-4bd3-91be-0a853e948452 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.444860+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=361846d1-41cd-403a-989f-4c29a0d1179e fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.984059+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host= myproject.herokuapp.com request_id=658795c8-0ba7-4988-9d39-34601b1334c7 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:44.673789+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=63fbabdc-7ba7-4997-81be-c601a0d83368 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:53.091547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=a3943544-9dc4-44f0-b788-a462cdfba7d0 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:54.419623+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=eb5191e2-21d9-410c-823e-c57bb0fb7fa4 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https

Project tree:

├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── init.sql
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt

Frontend's Dockerfile:

# Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]

Main directory's Dockerfile:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/

docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django

init.sql:

CREATE USER myUser;
CREATE DATABASE myProject;
GRANT ALL PRIVILEGES ON DATABASE myProject TO myUser;

Body:
Looks to me you didn't linked the containers where needed. If you want db to be visible by django add the links directive to your docker-compose.yml:

...

  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
    links:
      - db

This way the db hostname will be resolved correctly. Hopefully.

Hope this helps.
    ...


问:
Modal width (increase)
I want a modal to be 80% or so of a screen width. modal-lg isn't large enough. This:

```<code>.modal .modal-dialog {
  width: 80%;
}
</code>```

Doesn't work with Bootstrap 4.

答:
If you use Sass,

according to the documentation you can customize your default values.

In your case, you can easily override the variable named $modal-lg in your _custom.scss file.

Title: Modal width (increase)

Body:
I want a modal to be 80% or so of a screen width. modal-lg isn't large enough. This:

.modal .modal-dialog {
  width: 80%;
}

Doesn't work with Bootstrap 4.


问:
SCSS: Fixed and fluid table-cells
I'm building a div-list as a table with scss. I've converted it into css for the demonstartion.

The first and the last column is fixed with 90px and 30px.

The surrounded link is the table-row

| 90px | fluid sdfsdfsdfsdfd sd... | 30px |

| 90px | fluid  asdasdasd (blank)     | 30px |

The Table width should be 100%.
The width of the fluid part should get automatically 100% - 30px - 90px

My plan is to get the fluid width automatically depending on the fixed widths without

```<code>width: calc(100% - 30px - 90px)
</code>```

The table should not be stretched greater than 100% and the content of the fluid container should be get the nice ellipsis tag.

Is there a mistake in my stylesheet?

div.menu {
  display: table;
  border-collapse: collapse;
  width: 100%;
}
div.menu .head {
  display: table-row;
  height: 34px;
  line-height: 34px;
}
div.menu .head div {
  padding: 0 5px;
  display: table-cell;
}
div.menu .head div:first-of-type {
  width: 90px;
}
div.menu .head div:last-of-type {
  width: 30px;
}
div.menu a {
  height: 60px;
  line-height: 60px;
  display: table-row;
  border-top: 1px solid #f2f2f2;
  text-decoration: none !important;
}
div.menu a div {
  display: table-cell;
  padding: 0 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
div.menu a div:first-of-type {
  width: 90px;
}
div.menu a div:last-of-type {
  width: 30px;
}
div.menu a:last-of-type {
  border-bottom: 1px solid #f2f2f2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
  <div class="head">
    <div>Text</div>
    <div>Name</div>
    <div></div>
  </div>

    <div>Info</div>
    <div>Name of the item</div>
    <div>icon</div>

    <div>Info</div>
    <div>Name of another item</div>
    <div>icon</div>

    <div>Info</div>
    <div>This is a very long name, and it should not be greater than the page, and i want to see the icon. But it's not working.</div>
    <div>icon</div>

</div></code>```

答:
Using table-layout: fixed; solves the issue for me.

```<code>div.menu {
  display: table;
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
}
</code>```

JSFiddle example: https://jsfiddle.net/jennifergoncalves/1tv3ygka/

table-layout Documentation: https://www.w3schools.com/cssref/pr_tab_table-layout.asp

Title: SCSS: Fixed and fluid table-cells

Body:
I'm building a div-list as a table with scss. I've converted it into css for the demonstartion.

The first and the last column is fixed with 90px and 30px.

The surrounded link is the table-row

| 90px | fluid sdfsdfsdfsdfd sd... | 30px |

| 90px | fluid  asdasdasd (blank)     | 30px |

The Table width should be 100%.
The width of the fluid part should get automatically 100% - 30px - 90px

My plan is to get the fluid width automatically depending on the fixed widths without

width: calc(100% - 30px - 90px)

The table should not be stretched greater than 100% and the content of the fluid container should be get the nice ellipsis tag.

Is there a mistake in my stylesheet?

div.menu {
  display: table;
  border-collapse: collapse;
  width: 100%;
}
div.menu .head {
  display: table-row;
  height: 34px;
  line-height: 34px;
}
div.menu .head div {
  padding: 0 5px;
  display: table-cell;
}
div.menu .head div:first-of-type {
  width: 90px;
}
div.menu .head div:last-of-type {
  width: 30px;
}
div.menu a {
  height: 60px;
  line-height: 60px;
  display: table-row;
  border-top: 1px solid #f2f2f2;
  text-decoration: none !important;
}
div.menu a div {
  display: table-cell;
  padding: 0 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
div.menu a div:first-of-type {
  width: 90px;
}
div.menu a div:last-of-type {
  width: 30px;
}
div.menu a:last-of-type {
  border-bottom: 1px solid #f2f2f2;
}

Text

Name

Info

Name of the item

icon

Info

Name of another item

icon

Info

This is a very long name, and it should not be greater than the page, and i want to see the icon. But it's not working.

icon

Body:
Using table-layout: fixed; solves the issue for me.

div.menu {
  display: table;
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
}

JSFiddle example: https://jsfiddle.net/jennifergoncalves/1tv3ygka/

table-layout Documentation: https://www.w3schools.com/cssref/pr_tab_table-layout.asp


问:
Spring cloud sleuth + Spring Boot 1.4.0 transitive dependencies issue
I am using Spring Boot 1.4.0 and spring-cloud-sleuth, here is my pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring-boot-test</groupId>
    <artifactId>spring-boot-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <start-class>com.igor.Application</start-class>
        <spring-cloud-sleuth.version>1.0.4.RELEASE</spring-cloud-sleuth.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-sleuth</artifactId>
                <version>${spring-cloud-sleuth.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

and here is my dependency tree:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-boot-test 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ spring-boot-test ---
[INFO] spring-boot-test:spring-boot-test:jar:1.0-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.4.0.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.7:compile
[INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.7:compile
[INFO] |  |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.21:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.21:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.21:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.4:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.4:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.4:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.3.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.1:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.1:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.1:compile
[INFO] |  +- org.springframework:spring-web:jar:4.2.6.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.2.6.RELEASE:compile
[INFO] |  |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  |  +- org.springframework:spring-beans:jar:4.2.6.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-context:jar:4.2.6.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.2.6.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:4.2.6.RELEASE:compile
[INFO] \- org.springframework.boot:spring-boot-starter-test:jar:1.4.0.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test:jar:1.4.0.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.4.0.RELEASE:test
[INFO]    +- com.jayway.jsonpath:json-path:jar:2.2.0:test
[INFO]    |  +- net.minidev:json-smart:jar:2.2.1:test
[INFO]    |  |  \- net.minidev:accessors-smart:jar:1.1:test
[INFO]    |  |     \- org.ow2.asm:asm:jar:5.0.3:test
[INFO]    |  \- org.slf4j:slf4j-api:jar:1.7.21:compile
[INFO]    +- junit:junit:jar:4.12:test
[INFO]    +- org.assertj:assertj-core:jar:2.5.0:test
[INFO]    +- org.mockito:mockito-core:jar:1.10.19:test
[INFO]    |  \- org.objenesis:objenesis:jar:2.1:test
[INFO]    +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO]    +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO]    +- org.skyscreamer:jsonassert:jar:1.3.0:test
[INFO]    |  \- org.json:json:jar:20140107:test
[INFO]    +- org.springframework:spring-core:jar:4.3.2.RELEASE:compile
[INFO]    \- org.springframework:spring-test:jar:4.2.6.RELEASE:test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.126 s
[INFO] Finished at: 2017-07-07T20:25:23+03:00
[INFO] Final Memory: 21M/437M
[INFO] ------------------------------------------------------------------------
</code>```

it looks like spring-boot-sleuth has overridden dependencies, cause Spring Boot 1.4 uses spring 4.3.2.RELEASE.
I don't need it, how to avoid this behavior??

答: You can exclude dependencies in Maven. However you should consider using a release train BOM so that best matching dependencies are picked for you </p>

Body:
I am using Spring Boot 1.4.0 and spring-cloud-sleuth, here is my pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring-boot-test</groupId>
    <artifactId>spring-boot-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <start-class>com.igor.Application</start-class>
        <spring-cloud-sleuth.version>1.0.4.RELEASE</spring-cloud-sleuth.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-sleuth</artifactId>
                <version>${spring-cloud-sleuth.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

and here is my dependency tree:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-boot-test 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ spring-boot-test ---
[INFO] spring-boot-test:spring-boot-test:jar:1.0-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.4.0.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.7:compile
[INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.7:compile
[INFO] |  |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.21:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.21:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.21:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.4:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.4:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.4:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.3.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.1:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.1:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.1:compile
[INFO] |  +- org.springframework:spring-web:jar:4.2.6.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.2.6.RELEASE:compile
[INFO] |  |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  |  +- org.springframework:spring-beans:jar:4.2.6.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-context:jar:4.2.6.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.2.6.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:4.2.6.RELEASE:compile
[INFO] \- org.springframework.boot:spring-boot-starter-test:jar:1.4.0.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test:jar:1.4.0.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.4.0.RELEASE:test
[INFO]    +- com.jayway.jsonpath:json-path:jar:2.2.0:test
[INFO]    |  +- net.minidev:json-smart:jar:2.2.1:test
[INFO]    |  |  \- net.minidev:accessors-smart:jar:1.1:test
[INFO]    |  |     \- org.ow2.asm:asm:jar:5.0.3:test
[INFO]    |  \- org.slf4j:slf4j-api:jar:1.7.21:compile
[INFO]    +- junit:junit:jar:4.12:test
[INFO]    +- org.assertj:assertj-core:jar:2.5.0:test
[INFO]    +- org.mockito:mockito-core:jar:1.10.19:test
[INFO]    |  \- org.objenesis:objenesis:jar:2.1:test
[INFO]    +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO]    +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO]    +- org.skyscreamer:jsonassert:jar:1.3.0:test
[INFO]    |  \- org.json:json:jar:20140107:test
[INFO]    +- org.springframework:spring-core:jar:4.3.2.RELEASE:compile
[INFO]    \- org.springframework:spring-test:jar:4.2.6.RELEASE:test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.126 s
[INFO] Finished at: 2017-07-07T20:25:23+03:00
[INFO] Final Memory: 21M/437M
[INFO] ------------------------------------------------------------------------

it looks like spring-boot-sleuth has overridden dependencies, cause Spring Boot 1.4 uses spring 4.3.2.RELEASE.
I don't need it, how to avoid this behavior??


问:
ASP.NET *.resx serialization
I'm contributing on an I18N project and there's a call to serialize our *.resx files as JSON objects (for whatever reason).

What I'm wondering is:

Is there a way to get a list of all of the valid keys for a given *.resx file so that we could use HttpContext.GetGlobalResourceObject to grab the tokens?

If that won't work, has anyone come up with a clever solution that does?

答:
```<code>  Sub ReadRessourceFile()
       ''#Requires Assembly System.Windows.Forms
        Dim rsxr As System.Resources.ResXResourceReader = New System.Resources.ResXResourceReader("items.resx")

        ''# Iterate through the resources and display the contents to the console.
        Dim d As System.Collections.DictionaryEntry
        For Each d In rsxr
            Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString())
        Next d

        ''#Close the reader.
        rsxr.Close()
    End Sub
</code>```

Then you need to add this to a Serializable Dictionary, which you can then serialize to JSON using System.Web.Extensions.dll

```<code>Public Class JSONHelper

Public Shared Function Serialize(Of T)(ByVal obj As T) As String
    Dim JSONserializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
    Return JSONserializer.Serialize(obj)
End Function

Public Shared Function Deserialize(Of T)(ByVal json As String) As T
    Dim obj As T = Activator.CreateInstance(Of T)()
    Dim JSONserializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
    obj = JSONserializer.Deserialize(Of T)(json)
    Return obj
End Function

End Class
</code>```

Edit: C# :

```<code>public void ReadRessourceFile()
{
    //Requires Assembly System.Windows.Forms '
    System.Resources.ResXResourceReader rsxr = new System.Resources.ResXResourceReader("items.resx");

    // Iterate through the resources and display the contents to the console. '
    System.Collections.DictionaryEntry d = default(System.Collections.DictionaryEntry);
    foreach (DictionaryEntry d_loopVariable in rsxr) {
        d = d_loopVariable;
        Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString());
    }

    //Close the reader. '
    rsxr.Close();
}
</code>```

And the JSON helper:

```<code>public class JSONHelper
{

    public static string Serialize<T>(T obj)
    {
        System.Web.Script.Serialization.JavaScriptSerializer JSONserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return JSONserializer.Serialize(obj);
    }

    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        System.Web.Script.Serialization.JavaScriptSerializer JSONserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        obj = JSONserializer.Deserialize<T>(json);
        return obj;
    }

}
</code>```

Also, if you want to get the comment as well, you can set UseResXDataNodes to true.

Example:

```<code>public static string ReadRessourceFile()
{
    string[] languages = new string[] { "de", "fr", "it", "en" };
    string pathPattern = System.AppDomain.CurrentDomain.BaseDirectory;
    pathPattern = System.IO.Path.Combine(pathPattern, "..", "..", "..", "libQrCodeGenerator", "Resources", "QRBillText-{0}.resx");
    pathPattern = System.IO.Path.GetFullPath(pathPattern);

    System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>> dict = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>(System.StringComparer.InvariantCultureIgnoreCase);

    foreach (string lang in languages)
    {
        dict[lang] = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.InvariantCultureIgnoreCase);

        string file = string.Format(pathPattern, lang);
        System.Resources.ResXResourceReader rr = new System.Resources.ResXResourceReader(file);
        rr.UseResXDataNodes = true;

        // '# Iterate through the resources and display the contents to the console.
        foreach (System.Collections.DictionaryEntry d in rr)
        {
            System.Resources.ResXDataNode node = (System.Resources.ResXDataNode)d.Value;
            string value = (string) node.GetValue((System.ComponentModel.Design.ITypeResolutionService)null);
            string comment = node.Comment;

            if(!string.IsNullOrEmpty(comment))
            {
                System.Console.WriteLine(comment);
            }

            // dict[lang][d.Key.ToString()] = d.Value.ToString(); // when not using UseResXDataNodes = true
            dict[lang][d.Key.ToString()] = value;
        }

        // '#Close the reader.
        rr.Close();
    }

    string json = Newtonsoft.Json.JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented);
    return json;
}
</code>```

Title: ASP.NET *.resx serialization

Body:
  Sub ReadRessourceFile()
       ''#Requires Assembly System.Windows.Forms
        Dim rsxr As System.Resources.ResXResourceReader = New System.Resources.ResXResourceReader("items.resx")

        ''# Iterate through the resources and display the contents to the console.
        Dim d As System.Collections.DictionaryEntry
        For Each d In rsxr
            Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString())
        Next d

        ''#Close the reader.
        rsxr.Close()
    End Sub

Then you need to add this to a Serializable Dictionary, which you can then serialize to JSON using System.Web.Extensions.dll

Public Class JSONHelper

Public Shared Function Serialize(Of T)(ByVal obj As T) As String
    Dim JSONserializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
    Return JSONserializer.Serialize(obj)
End Function

Public Shared Function Deserialize(Of T)(ByVal json As String) As T
    Dim obj As T = Activator.CreateInstance(Of T)()
    Dim JSONserializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
    obj = JSONserializer.Deserialize(Of T)(json)
    Return obj
End Function

End Class

Edit: C# :

public void ReadRessourceFile()
{
    //Requires Assembly System.Windows.Forms '
    System.Resources.ResXResourceReader rsxr = new System.Resources.ResXResourceReader("items.resx");

    // Iterate through the resources and display the contents to the console. '
    System.Collections.DictionaryEntry d = default(System.Collections.DictionaryEntry);
    foreach (DictionaryEntry d_loopVariable in rsxr) {
        d = d_loopVariable;
        Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString());
    }

    //Close the reader. '
    rsxr.Close();
}

And the JSON helper:

public class JSONHelper
{

    public static string Serialize<T>(T obj)
    {
        System.Web.Script.Serialization.JavaScriptSerializer JSONserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return JSONserializer.Serialize(obj);
    }

    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        System.Web.Script.Serialization.JavaScriptSerializer JSONserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        obj = JSONserializer.Deserialize<T>(json);
        return obj;
    }

}

Also, if you want to get the comment as well, you can set UseResXDataNodes to true.

Example:

public static string ReadRessourceFile()
{
    string[] languages = new string[] { "de", "fr", "it", "en" };
    string pathPattern = System.AppDomain.CurrentDomain.BaseDirectory;
    pathPattern = System.IO.Path.Combine(pathPattern, "..", "..", "..", "libQrCodeGenerator", "Resources", "QRBillText-{0}.resx");
    pathPattern = System.IO.Path.GetFullPath(pathPattern);

    System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>> dict = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>(System.StringComparer.InvariantCultureIgnoreCase);

    foreach (string lang in languages)
    {
        dict[lang] = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.InvariantCultureIgnoreCase);

        string file = string.Format(pathPattern, lang);
        System.Resources.ResXResourceReader rr = new System.Resources.ResXResourceReader(file);
        rr.UseResXDataNodes = true;

        // '# Iterate through the resources and display the contents to the console.
        foreach (System.Collections.DictionaryEntry d in rr)
        {
            System.Resources.ResXDataNode node = (System.Resources.ResXDataNode)d.Value;
            string value = (string) node.GetValue((System.ComponentModel.Design.ITypeResolutionService)null);
            string comment = node.Comment;

            if(!string.IsNullOrEmpty(comment))
            {
                System.Console.WriteLine(comment);
            }

            // dict[lang][d.Key.ToString()] = d.Value.ToString(); // when not using UseResXDataNodes = true
            dict[lang][d.Key.ToString()] = value;
        }

        // '#Close the reader.
        rr.Close();
    }

    string json = Newtonsoft.Json.JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented);
    return json;
}