text:
Q: Time based log compaction does not work in Kafka we have a need to create compact topics,
that need to get compacted after certain size (segment.bytes), but MOST IMPORTANTLY after certain time (segment.ms) has passed (even if segment.bytes has not reached) at the topic level config.
Now, we have seen the segment.bytes being honored, but segment.ms is not being honored.
I have reproduced this issue with Confluent kafka 5.x distribution
https://kafka.apache.org/documentation/#topicconfigs
this is what i read about segment.ms in apache kafka documentation, which makes me believe
that our understanding is right - that segment.ms will override the segment.bytes - when it comes
kafka doing the compaction on a topic.

segment.ms    This configuration controls the period of time after which
  Kafka will force the log to roll even if the segment file isn't full
  to ensure that retention can delete or compact old data.

I am sending the data with key rotating between 0-20 values, and the string
'Spring Kafka Producer and Consumer Example' and i append the key value to this string.
this is the producer code
@Override
    public void run(String... strings) throws Exception {
        String data = "Spring Kafka Producer and Consumer Example";
        for (int j = 0; j < 30000; j++) {
            for (int i = 0; i < 20; i++) {
                sender.send(new Integer(i).toString(), data + i);
            }
        }
    }

the code sample is here
https://github.com/leofoto/kafka-producer-consumer.git
I have taken the code sample from (and modified it for this testcase)
https://memorynotfound.com/spring-kafka-consume-producer-example/
I first created compact-topic, in the broker logs i see the following

Created log for partition my-topic-compact-0 in /tmp/kafka-logs with
  properties {compression.type -> producer, message.format.version ->
  2.0-IV1, file.delete.delay.ms -> 60000, max.message.bytes -> 1000012, min.compaction.lag.ms -> 0, message.timestamp.type -> CreateTime,
  message.downconversion.enable -> true, min.insync.replicas -> 1,
  segment.jitter.ms -> 0, preallocate -> false,
  min.cleanable.dirty.ratio -> 0.5, index.interval.bytes -> 4096,
  unclean.leader.election.enable -> false, retention.bytes -> -1,
  delete.retention.ms -> 86400000, cleanup.policy -> [delete], flush.ms
  -> 9223372036854775807, segment.ms -> 604800000, segment.bytes -> 1073741824, retention.ms -> 604800000,
  message.timestamp.difference.max.ms -> 9223372036854775807,
  segment.index.bytes -> 10485760, flush.messages ->
  9223372036854775807}. (kafka.log.LogManager) [2018-09-17 21:28:00,110]
  INFO [Partition my-topic-compact-0 broker=0] No checkpointed
  highwatermark is found for partition my-topic-compact-0
  (kafka.cluster.Partition)

then when i changed the configuration to make the topic compact

./kafka-configs --zookeeper localhost:2181 --entity-type topics
  --entity-name my-topic-compact --alter --add-config min.cleanable.dirty.ratio=0.01,cleanup.policy=compact,segment.ms=12000,delete.retention.ms=100,segment.bytes=200000 Completed Updating config for entity: topic 'my-topic-compact'.

Broker logs show it again (correctly reporting its a compact-topic now)

[2018-09-17 22:06:25,745] INFO Processing notification(s) to
  /config/changes (kafka.common.ZkNodeChangeNotificationListener)
  [2018-09-17 22:06:25,746] INFO Processing override for entityPath:
  topics/my-topic-compact with config: Map(cleanup.policy -> compact,
  segment.ms -> 12000, min.cleanable.dirty.ratio -> 0.01, segment.bytes
  -> 200000, delete.retention.ms -> 100) (kafka.server.DynamicConfigManager)

Also kafka-config --describe command shows it clearly

./kafka-configs --zookeeper localhost:2181 --entity-type topics
  --entity-name my-topic-compact --describe
Configs for topic 'my-topic-compact' are Configs for topic
  'my-topic-compact' are
  segment.bytes=200000,min.cleanable.dirty.ratio=0.01,delete.retention.ms=100,segment.ms=12000,cleanup.policy=compact

when i start the kafka server, i see the following message

<< Starting log cleanup with a period of 300000 ms >>  [[ i am sure
  300 seconds is the broker config value, the topic level  value is 12
  seconds in this case ]]
[2018-09-17 22:01:31,215] INFO [Log partition=my-topic-non-compact-0,
  dir=/tmp/kafka-logs] Completed load of log with 1 segments, log start
  offset 0 and log end offset 20 in 2 ms (kafka.log.Log) [2018-09-17
  22:01:31,218] INFO Logs loading complete in 378 ms.
  (kafka.log.LogManager) [2018-09-17 22:01:31,224] INFO Starting log
  cleanup with a period of 300000 ms. (kafka.log.LogManager) [2018-09-17
  22:01:31,225] INFO Starting log flusher with a default period of
  9223372036854775807 ms. (kafka.log.LogManager) [2018-09-17
  22:01:31,439] INFO Awaiting socket connections on 0.0.0.0:9092.
  (kafka.network.Acceptor) [2018-09-17 22:01:31,463] INFO [SocketServer
  brokerId=0] Started 1 acceptor threads (kafka.network.SocketServer)
  [2018-09-17 22:01:31,478] INFO [ExpirationReaper-0-Produce]: Starting
  (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
  [2018-09-17 22:01:31,478] INFO [ExpirationReaper-0-Fetch]: Starting
  (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
  [2018-09-17 22:01:31,479] INFO [ExpirationReaper-0-DeleteRecords]:
  Starting
  (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
  [2018-09-17 22:01:31,487] INFO [LogDirFailureHandler]: Starting
  (kafka.server.ReplicaManager$LogDirFailureHandler) [2018-09-17
  22:01:31,537] INFO Creating /brokers/ids/0 (is it secure? false)
  (kafka.zk.KafkaZkClient) [2018-09-17 22:01:31,541] INFO Result of
  znode creation at /brokers/ids/0 is: OK (kafka.zk.KafkaZkClient)
  [2018-09-17 22:01:31,542] INFO Registered broker 0 at path
  /brokers/ids/0 with addresses:
  ArrayBuffer(EndPoint(192.168.0.11,9092,ListenerName(PLAINTEXT),PLAINTEXT))
  (kafka.zk.KafkaZkClient)

then when i wrote a lot of data i saw segments rolling as well, i see a lot of activity ,
which pushes the compaction to happen. [ which is fine] i sent over 300k records and the compaction happens
and a new consumer that consumes the messages (after compaction has taken place), it sees around 3225 records.

[2018-09-17 22:09:21,602] INFO [Log partition=my-topic-compact-0,
  dir=/tmp/kafka-logs] Rolled new log segment at offset 185361 in 4 ms.
  (kafka.log.Log) [2018-09-17 22:09:21,673] INFO [ProducerStateManager
  partition=my-topic-compact-0] Writing producer snapshot at offset
  188897 (kafka.log.ProducerStateManager) [2018-09-17 22:09:21,675] INFO
  [Log partition=my-topic-compact-0, dir=/tmp/kafka-logs] Rolled new log
  segment at offset 188897 in 3 ms. (kafka.log.Log) [2018-09-17
  22:09:21,755] INFO [ProducerStateManager partition=my-topic-compact-0]
  Writing producer snapshot at offset 192348
  (kafka.log.ProducerStateManager) [2018-09-17 22:09:21,758] INFO [Log
  partition=my-topic-compact-0, dir=/tmp/kafka-logs] Rolled new log
  segment at offset 192348 in 3 ms. (kafka.log.Log) [2018-09-17
  22:09:21,831] INFO [ProducerStateManager partition=my-topic-compact-0]
  Writing producer snapshot at offset 195846
  (kafka.log.ProducerStateManager) [2018-09-17 22:09:21,834] INFO [Log
  partition=my-topic-compact-0, dir=/tmp/kafka-logs] Rolled new log
  segment at offset 195846 in 3 ms. (kafka.log.Log) [2018-09-17
  22:09:21,879] INFO [ProducerStateManager partition=my-topic-compact-0]
  Writing producer snapshot at offset 199461
  (kafka.log.ProducerStateManager) [2018-09-17 22:09:21,882] INFO [Log
  partition=my-topic-compact-0, dir=/tmp/kafka-logs] Rolled new log
  segment at offset 199461 in 3 ms. (kafka.log.Log) [2018-09-17
  22:09:21,909] INFO [ProducerStateManager partition=my-topic-compact-0]
  Writing producer snapshot at offset 203134
  (kafka.log.ProducerStateManager) [2018-09-17 22:09:21,915] INFO [Log
  partition=my-topic-compact-0, dir=/tmp/kafka-logs] Rolled new log
  segment at offset 203134 in 7 ms. (kafka.log.Log) [2018-09-17
  22:09:21,980] INFO [ProducerStateManager partition=my-topic-compact-0]
  Writing producer snapshot at offset 206703
  (kafka.log.ProducerStateManager) [2018-09-17 22:09:21,985] INFO [Log
  partition=my-topic-compact-0, dir=/tmp/kafka-logs] Rolled new log
  segment at offset 206703 in 6 ms. (kafka.log.Log)

now no matter how long a wait (past 12 seconds), the log compaction does not kick off
no matter how much i wait before running the following command (with new consumer group every time)

./kafka-console-consumer --bootstrap-server localhost:9092 --topic
  my-topic-compact --from-beginning  --property print.key=true --group
  new-group16

Every new consumer consumes exactly 3225 messages,
If the compaction was to have happened after the topic level segment.ms had passed,
it should have gotten it compacted down to just 20 keys and their latest values.
But we don't see that behaviour. Am i missing anything.
DELETES NOT WORKING
On top of that, when i send the null payload for the same keys, like this
@Override
public void run(String... strings) throws Exception {
    String data = "Spring Kafka Producer and Consumer Example";
    for (int j = 0; j < 2; j++) {
        for (int i = 0; i < 20; i++) {
            sender.send(new Integer(i).toString(), null);
        }
    }
}

We expect the messages to be eventually deleted by the next compaction cycle. That's not happening for us either after segment.ms time has passed (12 seconds in our case at the topic level config)

./kafka-configs --zookeeper localhost:2181 --entity-type topics
  --entity-name my-topic-compact --describe
Configs for topic 'my-topic-compact' are Configs for topic
  'my-topic-compact' are
  segment.bytes=200000,min.cleanable.dirty.ratio=0.01,delete.retention.ms=100,segment.ms=12000,cleanup.policy=compact

A: The time based log compaction is not supported yet in kafka (apache kafka 2.x or confluent distribution 5.x) This is what i got from a confluent engineer
For now, this is not going to work for us.
Sharing the following info for others' reference

Once
  https://cwiki.apache.org/confluence/display/KAFKA/KIP-354%3A+Add+a+Maximum+Log+Compaction+Lag
  is complete and implemented I would encourage you to revisit the use
  case.


text:
Q: Should not display empty and undefined values when using ng-repeat I am looping through the JSON to display values Company name and divisions under it , but the issue is that how can i stop to display division names for whose company name is empty
This is my code

            {{item.name}}
            {{form.name}}

As you can i tried using ng-if="item.name!='' && item.name"
I don't want to display the divisions if the company name is empty or undefined .
This is my fiddle
http://jsfiddle.net/9fR23/416/

A: item.name is not a boolean so you could just use ng-show without second condition.

   {{item.name}}
     {{form.name}}

Your Forked Plunker

A: Your Fiddle may not work because you are using Angular 1.0.1 which has some issue in ng-if. If you are really using this version, you can replace ng-if by ng-show (which will create hidden elements in the DOM).
Anyway, the best solution would be to use Angular 1.2+ which fixes ng-if bugs in ng-repeat. As you can see in the following snippet, I didn't change your code, and it works.

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function($scope) {
  $scope.tickets = [{

    "name": "",
    "forms": [{
      "id": 1,
      "name": "HR",
      "created_at": null,
      "updated_at": null,
      "role": "primary"
    }]
  }, {

    "name": "TCS",
    "forms": [{
      "id": 1,
      "name": "DEV",
      "created_at": null,
      "updated_at": null,
      "role": "primary"
    }, {
      "name": "HR",
      "created_at": null,
      "updated_at": null,
      "role": "primary"
    }]
  }]
});

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css"/>

          {{item.name}}
          {{form.name}}

Forked your Fiddle here (just changed Angular version).

redpajama_set_name: RedPajamaStackExchange


text:
Q: R use stats::optimize in Rcpp, simple example fails to compile I want to use the R stats::optimize function in Rcpp because I haven't been able to find an Rcpp equivalent. The code below is my attempt at a simple example based on the Example in the optimize help, but fails.
Here's the R function and results
f <- function (x) (x - .33)^2
xmin <- optimize(f, c(0, 1), tol = 0.0001)
xmin

This returns
$minimum
[1] 0.333

$objective
[1] 0

Here's the Rcpp code that fails when sourcing it.
    #include <Rcpp.h>
    const double tolerance = 1e-0;

   // [[Rcpp::export]]
    Rcpp::NumericVector f(Rcpp::NumericVector x) {
      return pow(x-0.33, 2);
    }

    Rcpp::List fTg_opt(const double optmin, const double optmax) {
      Rcpp::Environment base("package:stats");
      Rcpp::Function optimize_r = base["optimize"];
      Rcpp::NumericVector interval = {optmin,optmax};
      return optimize_r(f, interval, tolerance);
    }

The Rstudio console has the following error messages.
> Rcpp::sourceCpp("R/cpp/testopt.cpp")
In file included from testopt.cpp:1:
In file included from /Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp.h:27:
In file included from /Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/RcppCommon.h:157:
In file included from /Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/traits/traits.h:45:
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/traits/is_convertible.h:35:10: error: function cannot return function type 'Rcpp::Vector<14> (Rcpp::Vector<14>)'
                static T MakeT() ;
                       ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/internal/wrap.h:770:75: note: in instantiation of template class 'Rcpp::traits::is_convertible<Rcpp::Vector<14> (Rcpp::Vector<14>), SEXPREC *>' requested here
            return wrap_dispatch_unknown(object, typename ::Rcpp::traits::is_convertible<T,SEXP>::type());
                                                                          ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/internal/wrap.h:787:20: note: in instantiation of function template specialization 'Rcpp::internal::wrap_dispatch_eigen<Rcpp::Vector<14> (Rcpp::Vector<14>)>' requested here
            return wrap_dispatch_eigen(object, typename traits::is_eigen_base<T>::type());
                   ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/internal/wrap.h:807:20: note: in instantiation of function template specialization 'Rcpp::internal::wrap_dispatch_unknown_importable<Rcpp::Vector<14> (Rcpp::Vector<14>)>' requested here
            return wrap_dispatch_unknown_importable(object, typename ::Rcpp::traits::is_importer<T>::type());
                   ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/internal/wrap_end.h:30:25: note: in instantiation of function template specialization 'Rcpp::internal::wrap_dispatch<Rcpp::Vector<14> (Rcpp::Vector<14>)>' requested here
          return internal::wrap_dispatch( object, typename ::Rcpp::traits::wrap_type_traits<T>::wrap_category() ) ;
                           ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/grow.h:44:26: note: in instantiation of function template specialization 'Rcpp::wrap<Rcpp::Vector<14> (Rcpp::Vector<14>)>' requested here
            return grow( wrap(head), tail ) ;
                         ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/grow.h:65:26: note: in instantiation of function template specialization 'Rcpp::internal::grow__dispatch<Rcpp::Vector<14> (Rcpp::Vector<14>)>' requested here
        return internal::grow__dispatch(typename traits::is_named<T>::type(), head, y);
                         ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/generated/grow__pairlist.h:45:9: note: in instantiation of function template specialization 'Rcpp::grow<Rcpp::Vector<14> (Rcpp::Vector<14>)>' requested here
        return grow( t1, grow( t2, grow( t3, R_NilValue ) ) ) ;
               ^
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/generated/Function__operator.h:45:20: note: in instantiation of function template specialization 'Rcpp::pairlist<Rcpp::Vector<14> (Rcpp::Vector<14>), Rcpp::Vector<14>, double>' requested here
            return invoke(pairlist(t1, t2, t3), R_GlobalEnv);
                          ^
testopt.cpp:13:20: note: in instantiation of function template specialization 'Rcpp::Function_Impl<PreserveStorage>::operator()<Rcpp::Vector<14> (Rcpp::Vector<14>), Rcpp::Vector<14>, double>' requested here
  return optimize_r(f, interval, tolerance);
                   ^
1 error generated.
make: *** [testopt.o] Error 1
clang++ -mmacosx-version-min=10.13 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include" -I"/Users/gcn/Documents/workspace/ISIMIPData/R/cpp" -I/usr/local/include   -fPIC  -Wall -g -O2  -c testopt.cpp -o testopt.o
Error in Rcpp::sourceCpp("R/cpp/testopt.cpp") :
  Error 1 occurred building shared library.

A: One of your problems here is that you assume that becomes a function you submit to compilation under Rcpp::sourceCpp() is callable under its exported name.
It is not. Try Rcpp::sourceCpp(..., verbose=TRUE), i.e. add that arguments, to see what is really called.  Those you could pass around (using SEXP argunments and results, but they are unwieldy).
To prove, here is a 'working but useless' version of your code. If we pass f() from R too, everything is callable.
Morale:  The interface still is SEXP .Call("name", SEXP a, SEXP b, ...) even if Rcpp hides that.  No Free Lunch (TM).  But as my comment hinted, there are optimization packages you can use with Rcpp.
Code
#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List fTg_opt(Rcpp::Function f, const double optmin, const double optmax) {
    Rcpp::Environment base("package:stats");
    Rcpp::Function optimize_r = base["optimize"];
    Rcpp::NumericVector interval = {optmin,optmax};
    Rcpp::List res = optimize_r(f, interval);
    return res;
}

/*** R
f <- function (x) (x - .33)^2
xmin <- optimize(f, c(0, 1), tol = 0.0001)
xmin

fTg_opt(f, 0, 1)
*/

Output
> Rcpp::sourceCpp("~/git/stackoverflow/68674076/question.cpp")

> f <- function (x) (x - .33)^2

> xmin <- optimize(f, c(0, 1), tol = 0.0001)

> xmin
$minimum
[1] 0.33

$objective
[1] 0

> fTg_opt(f, 0, 1)
$minimum
[1] 0.33

$objective
[1] 0


text:
Q: How to generate a nested array of objects from an array of objects in nested set model? I'm trying to create a function that can convert a nested set model array of objects to a normal nested array of objects within array of objects.
Currently, I'm not satisfied with my temporary solution that is limited to a depth of 2. Basically it is server-side controller using some Knex:
const getCategories = (res, db) => {
  db.raw(`
    SELECT child.id, child.name, child.path
    FROM product_category parent
    JOIN product_category child
    ON child.lower BETWEEN parent.lower AND parent.upper
    WHERE parent.id = 1
      AND
        (
          SELECT COUNT(*)
          FROM product_category node
          WHERE child.lower BETWEEN node.lower AND node.upper
            AND node.lower BETWEEN parent.lower AND parent.upper
        ) = 2
    ORDER BY child.id
  `)
  .then(categories => {
    if (categories.rows.length) {
      const categoryPromises = categories.rows.map(category => {
        return db.raw(`
          SELECT child.id, child.name, child.path
          FROM product_category parent
          JOIN product_category child
          ON child.lower BETWEEN parent.lower AND parent.upper
          WHERE parent.id = ${category.id}
          AND
            (
              SELECT COUNT(*)
              FROM product_category node
              WHERE child.lower BETWEEN node.lower AND node.upper
                AND node.lower BETWEEN parent.lower AND parent.upper
            ) = 2
        `)
        .then(subcategories => {
          return { ...category, subcategories: subcategories.rows }
        })
      })

      return Promise.all(categoryPromises)
      .then(products => {
        res.json(products)
      })
    } else {
      res.status(400).json("No categories")
    }
  })
}

The schema is here: http://sqlfiddle.com/#!17/a20af
Nested set model is a way of handling hierarchical data that encloses the children node into boundaries (commonly called lft and rgt). So if the lft and rgt values of node1 are between the lft and rgt value of node2, it means that node1 is a children of node2 (I hope that cleared things up).
For example, I have the following array:
const categories = [
  {
      id: 1,
      name: "Products",
      lft: 1,
      rgt: 22
  },
  {
      id: 2,
      name: "Boats",
      lft: 2,
      rgt: 15
  },
  {
      id: 3,
      name: "Rescue Boats",
      lft: 3,
      rgt: 4
  },
  {
      id: 4,
      name: "Dive Boats",
      lft: 5,
      rgt: 6
  },
  {
      id: 5,
      name: "Tamarans",
      lft: 7,
      rgt: 8
  },
  {
      id: 6,
      name: "Dragon Boats",
      lft: 9,
      rgt: 10
  },
  {
      id: 7,
      name: "Kayaks",
      lft: 11,
      rgt: 12
  },
  {
      id: 8,
      name: "Speedboats",
      lft: 13,
      rgt: 14
  },
  {
      id: 9,
      name: "Other Products",
      lft: 16,
      rgt: 21
  },
  {
      id: 10,
      name: "Slides",
      lft: 17,
      rgt: 18
  },
  {
      id: 11,
      name: "Buoys",
      lft: 19,
      rgt: 20
  }
]

I want it to have an output something like this (or an array if there are multiple root nodes):
{
  id: 1,
  name: "Products",
  subcategories: [
    {
      id: 2,
      name: "Boats",
      subcategories: [
        {
          id: 3,
          name: "Rescue Boats"
        },
        {
          id: 4,
          name: "Dive Boats"
        },
        {
          id: 5,
          name: "Tamarans"
        },
        {
          id: 6,
          name: "Dragon Boats"
        },
        {
          id: 7,
          name: "Kayaks"
        },
        {
          id: 8,
          name: "Speedboats"
        }
      ]
    },
    {
      id: 9,
      name: "Other Products",
      subcategories: [
        {
          id: 10,
          name: "Slides"
        },
        {
          id: 11,
          name: "Buoys",
        }
      ]
    }
  ]
}

A: I wrote this recursive solution. Hope it can help. If you have any doubt please ask me.
I just check if an element is inside right and left property of another one. In this case I add it into his fathers (and each anchestor). I repeat the same operation until there are no more "fathers".

const categories = [
  {
      id: 1,
      name: "Products",
      lft: 1,
      rgt: 22
  },
  {
      id: 2,
      name: "Boats",
      lft: 2,
      rgt: 15
  },
  {
      id: 3,
      name: "Rescue Boats",
      lft: 3,
      rgt: 4
  },
  {
      id: 4,
      name: "Dive Boats",
      lft: 5,
      rgt: 6
  },
  {
      id: 5,
      name: "Tamarans",
      lft: 7,
      rgt: 8
  },
  {
      id: 6,
      name: "Dragon Boats",
      lft: 9,
      rgt: 10
  },
  {
      id: 7,
      name: "Kayaks",
      lft: 11,
      rgt: 12
  },
  {
      id: 8,
      name: "Speedboats",
      lft: 13,
      rgt: 14
  },
  {
      id: 9,
      name: "Other Products",
      lft: 16,
      rgt: 21
  },
  {
      id: 10,
      name: "Slides",
      lft: 17,
      rgt: 18
  },
  {
      id: 11,
      name: "Buoys",
      lft: 19,
      rgt: 20
  }
]

function create_tree(array){
  if(array.every(x => array.every(y => !(y.lft > x.lft && y.rgt < x.rgt))))
    return array.map(x => {return{id:x.id, name:x.name, subcategories: x.subcategories}});
  else
  return create_tree(array.map(x => {return {
    id: x.id,
    name: x.name,
    lft: x.lft,
    rgt: x.rgt,
    subcategories: array.filter(y => y.lft > x.lft && y.rgt < x.rgt).map(t => {return (t.subcategories) ? {id: t.id, name: t.name, subcategories: t.subcategories} : {id: t.id, name: t.name}})
  }}).filter(t => t.subcategories && t.subcategories.length > 0));
}

console.log(create_tree(categories));


text:
Q: Are all scripting languages interpreted? Are all scripting languages interpreted? I haven't come across a compiled + scripting language yet. the following languages are both interpreted and scripting languages. what is the connection between interpreted languages and scripting languages.

e.g JavaScript, python , perl

what about the reverse?

A: By definition, what makes a scripting language is that there is not a separate compile stage. A scripting language always need a copy of its interpreter around to run while a compiled language doesn't need the compiler to execute the resulting binary. For example in C we would first compile to a native executable then run that executable.  In a scripting language, we feed in the script as a text file and it is immediately executed.
How this is accomplished is another question.  Most scripting languages begin life with a purely interpreted implementation.  Inevitably the useful ones all acquire an implementation that takes advantage of the speed of Just In Time(JIT) compilation.  The difference is that this JIT is done during the running of the script and never produces a separate output. Scripts are still human readable text files that require some interpreter to run.
There are some interesting example of languages "on the border."  Haskell is normally compiled into a free standing binary, but can be run as a script as well (at least the GHC implementation can do so.)  Java compiles to a binary, but not a stand-alone executable.  A Java runtime must be present to run Java files.


text:
Q: How can I create a log file in java using loggers (log4j or slf4j) in the place where we run the application(jar) or source code? I am bundling my source code as jar or a standalone application which would be running in the Linux environment.So,whenever I run the application the log files must be generated in the drive where the application runs.
The output log file path is not static.
I tried using the log4j properties..but it doesn't worked as the path varies dynamically.

A: You can use System Properties as variables in your log configuration (as decribed in Log4j2 documentation)
Consider this example:
log4j2.xml - look for ${sys:loghome}
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <File name="A1" fileName="${sys:loghome}/A1.log" append="false">
      <PatternLayout pattern="%t %-5p %c{2} - %m%n"/>
    </File>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="stack" level="debug">
      <AppenderRef ref="A1"/>
    </Logger>
    <Root level="debug">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>
</Configuration>

LogMe.java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LogMe {
    public static void main(String[] args) {
        // For testing System.setProperty("loghome", "C:/Daten/");
        Logger log = LogManager.getLogger("stack");
        log.info("Logged");
    }
}

This will store the logfile relative to System property "loghome".
Final Step
Set System Property at start:
java -Dloghome=. LogMe

By passing in the correct directory where logs should be put, you can control the logfile creation.
log4j2.properties just a quick example
status = error
name = PropertiesConfig

property.filename = ${sys:loghome}/FromProperty.log

appenders = console, rolling

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %m%n

appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = ${sys:loghome}/log-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 2
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.strategy.max = 5

loggers = rolling

logger.rolling.name = stack
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRefs = rolling
logger.rolling.appenderRef.rolling.ref = RollingFile

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT


text:
Q: Updating database with for loop in Flask? I'm trying to automatize updates on database since I have a lot of columns.
I have succeeded to display the database using for loop, but I have problem commiting changes to database:
@app.route('/listvehicle/<int:vehicle_id>/update', methods=['GET', 'POST'])
@login_required
def update_vehicle(vehicle_id):
    vehicle = Vehicle.query.get_or_404(vehicle_id)
    form = VehicleUpdateForm()
    if form.validate_on_submit():
        for attr,value in vehicle.__dict__.items():
            for ia in form:
                if ia == attr:
                    vehicle.__dict__[attr] = form.__dict__[ia]
        db.session.commit()
        flash(f'The user has been updated', 'success')
        return redirect(url_for('listvehicle'))
    elif request.method == 'GET':
        for attr,value in vehicle.__dict__.items():
            for ia,iv in form.__dict__.items():
                if ia == attr:
                    iv.data = value
    return render_template('updatevehicle.html', form=form)

Any help with commiting changes to database?

A: I would suggest you posting the Model and Form definitions, but without seeing it, I suggest you use a different approach, changing anything with double underscores (__dict__ for example) is highly discouraged.
I see an improvement that can be made simply by using setattr and iterating over the form data:
def update_vehicle(vehicle_id):
    vehicle = Vehicle.query.get_or_404(vehicle_id)
    form = VehicleUpdateForm()
    if form.validate_on_submit():
        for fieldname, value in form.data.items():
            setattr(vehicle, fieldname, value)
        db.session.commit()
        flash(f'The user has been updated', 'success')
        return redirect(url_for('listvehicle'))
    elif request.method == 'GET':
        for attr,value in vehicle.__dict__.items():
            for ia,iv in form.__dict__.items():
                if ia == attr:
                    iv.data = value
    return render_template('updatevehicle.html', form=form)


text:
Q: Use Excel as a modal spreadsheet control in Word? As an alternative to either using any of the no longer extant Grid or Spreadsheet controls or attempting to write my own in VBA (lousy and primitive) I thought to try to use Excel itself as a kind of GridView control.  The idea would be to attempt to replicate a kind of modal dialogue box.  I need this to work from Word.  So far I got this far:
Public Function xlmat() As Variant

    Dim xl As Excel.Application: Set xl = New Excel.Application
    Dim wb As Excel.Workbook: Set wb = xl.Workbooks.Add
    Dim ws As Excel.Worksheet: Set ws = wb.Sheets(1)
    Dim r As Variant
    xl.ShowStartupDialog = False
    xl.Visible = True
    ws.Activate

    On Error GoTo islands

    While -1 <> xl.ActiveSheet.Columns.Count
        r = xl.ActiveSheet.UsedRange.Value
        Sleep 1000
        DoEvents
    Wend

islands:
    Set ws = Nothing
    Set wb = Nothing
    Set xl = Nothing
    xlmat = r

End Function

Third party controls and the like are right out.
The idea is that the code starts up an Excel instance (that much works) and then the user would enter whatever data and close Excel.  In a loop, the code attempts to determine that Excel is finally dead, closed by the user.  The result of the latest result of xl.ActiveSheet.UsedRange.Value would be whatever the user entered and the result of the function.
Is there a better way to do this?

A: I did the following to implement a modal Excel callable from Word.  Its one disadvantage is that it needs a tiny Excel addin to function.  The contents of the Excel addin are two subs which are called when the OK and Cancel buttons are pressed.  These would be stored in a module called Modal.
Option Explicit
Public Sub doCancel()
    Application.ActiveWorkbook.CustomDocumentProperties("rc") = 1
End Sub
Public Sub doOk()
    Application.ActiveWorkbook.CustomDocumentProperties("rc") = 2
End Sub

The function which invokes modal Excel from Word is the following:
Option Explicit

First, the sleep function
#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMs As LongPtr) ' 64 bit
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMs As Long) ' 32 bit
#End If

The xlmat function, started in the question.  Best of all, no usage of VBA error handling.
Public Function xlmat() As String

Start up Excel
    Dim xl As Excel.Application: Set xl = New Excel.Application
    Dim wb As Excel.Workbook: Set wb = xl.Workbooks.Add
    Dim ws As Excel.Worksheet: Set ws = wb.Sheets(1)
    Dim addin As Excel.addin
    Dim i As Long
    Dim j As Long
    Dim n As Long
    Dim rc As Integer
    Dim r As String
    Dim t As Variant
    Dim ec(-1 To 0) As String: ec(-1) = ",": ec(0) = ";"

Prepare Excel for modal use.  "Dictator" application code would go here
    xl.ScreenUpdating = False
    xl.ShowStartupDialog = False
    xl.Visible = True
    ws.Activate

The OK and Cancel buttons on the spreadsheet.
    ws.Buttons.Add 500, 160, 50, 25
    ws.Buttons.Add 500, 260, 50, 25

The addin itself has to be loaded.  I called it ExcelModal.xlam.
    For i = 1 To xl.AddIns.Count
        If xl.AddIns(i).Name = "ExcelModal.xlam" Then
            xl.AddIns(i).Installed = False
            xl.AddIns(i).Installed = True
        End If
    Next i

Assign captions and actions to the buttons.  Note the addin is called from here.
    ws.Buttons(1).Caption = "Cancel"
    ws.Buttons(1).OnAction = "Modal.doCancel"

    ws.Buttons(2).Caption = "OK"
    ws.Buttons(2).OnAction = "Modal.doOk"

I could have parked this value on an Excel cell, but I prefer parking the data
somewhere the user can't get to it.
    wb.CustomDocumentProperties.Add Name:="rc", LinkToContent:=False, _
        Type:=MsoDocProperties.msoPropertyTypeNumber, Value:=0

Excel spreadsheet starts to become usable here
    xl.ScreenUpdating = True

This loop has the effect of making Excel modal.  When one of the buttons are
pressed, wb.CustomDocumentProperties("rc") is no longer zero and the loop exits
    While 0 = wb.CustomDocumentProperties("rc")
        Sleep 500
        DoEvents
    Wend

Depending on the value of rc, return either an empty string when Cancel pressed, or return a flattened string version of whatever was in the spreadsheet.  Works for me.
    rc = wb.CustomDocumentProperties("rc")
    xlmat = ""
    If rc = 2 Then
        t = ws.UsedRange.Value
        For i = 1 To UBound(t, 1)
            n = UBound(t, 2)
            For j = 1 To n
                r = r & t(i, j) & ec(j <> n)
            Next j
        Next i
        xlmat = Left(r, Len(r) - 1)
    End If

Close up and clean up
    wb.Close False
    xl.Quit

    Set ws = Nothing
    Set wb = Nothing
    Set xl = Nothing

End Function

I would be interested in suggestions to eliminate the need of the Excel addin.


text:
Q: Dynamic routing with an ingress controller Is it possible to do a dynamic routing with a nginx ingress controller? By dynamic I mean based on the url I need to strip and fetch a value from the url and route based on that value. Let me know how if it's possible. If it's not possible with nginx controller , let me know any other way in which this is possible. Appreciate any help.

A: Ingress controllers are based on Ingress objects. Kubernetes objects definitions are static by nature (so we could version control them).
From what I gathered in the comments, when a user requests domain.com/foo they will be redirected to their instance of your app ? You will need a source to get the updated info.
I could see 2 ways of doing that:

*

*Edit the ingress object manually or programmatically (using helm or some other templating software)

*Make a dedicated app using a persistent database and trigger redirections from there: domain.com/* -> redirect app -> `user app. This way you can control your users list as you want.

It depends if the end user will stay on domain.com/user or if they get redirected to another unique domain. I would need more info to discuss that.

A: Attach tags to your services and let Traefik do the rest!
https://docs.traefik.io/routing/providers/consul-catalog/
I guess this could be very close to what you want to acheeve.
Best of luck!

A: Dynamic routing with Ambassador Header-based Routing
Ambassador is another Envoy-based solution. It has free and commercial versions. Ambassador is described as a «Kubernetes-native API gateway for microservices» and it brings corresponding benefits — such as the tight integration with the primitives of K8s. Having a pack of features you'd expect from an Ingress controller, it can also be used with a variety of service mesh solutions (Consul, Linkerd, Istio).
The headers Annotation
The headers attribute is a dictionary of header: value pairs. Ambassador Edge Stack will only allow requests that match the specified header: value pairs to reach the target service.
You can also set the value of a header to true to test for the existence of a header.
---
apiVersion: getambassador.io/v2
kind:  Mapping
metadata:
  name:  user-header-based-routing
spec:
  prefix: /backend/
  service: userA
  headers:
    x-authenticated-user: userA
...


text:
Q: Hierarchical data storage for read intensive application I'm trying to save a tree like hierarchy (data comes in json) to my database. I'm trying to decide what database technology and technique to use for read efficiency of the data.

*

*All nodes in one level have the same schema (all nodes in one level in the tree have the same set of attributes)

*Nodes in different levels in the tree do not have the same schema.
So the same color implies the same type (see fig).

*The tree structure Root -> A -> B -> D doesn't hold true all the time. Some times I get root node directly having child node type of D. Or node of type A having child of type D.

*Leaf nodes can either be type B or D. The tree can never stop at level A, or root.

*I will be storing around 700 nodes in the tree.

I wanted to represent this data in some database. I will write this once but read it multiple times.
Reading queries will be something like - give me the children of B3; or give me grand-grand children (Type D) of the root node...etc.
What/how would be the most efficient way of storing this data?


text:
Q: The value of $\sum_{0\le i
Find the value of
$$\sum_{0\le i<j\le n}\binom ni\binom nj$$
I get the result: $$\frac{1}{2}\left(2^{2n}-\binom{2n}{n}\right)$$ via a numeric argument.
My question is: Can we solve it using a combinational argument?
My Numeric Argument: $$\left(\sum^{n}_{r=0}\binom{n}{i}\right)^2=\sum^{n}_{r=0}\binom{n}{i}^2+2\mathop{\sum\sum}_{0\leq i<j\leq n}\binom{n}{i}\cdot \binom{n}{j}$$
So here $$\displaystyle \sum^{n}_{r=0}\binom{n}{i} = \binom{n}{0}+\binom{n}{1}+.....+\binom{n}{n} = 2^n$$
and $$\displaystyle \sum^{n}_{r=0}\binom{n}{i}^2=\binom{n}{0}^2+\binom{n}{1}^2+.....+\binom{n}{n}^2 = \binom{2n}{n}$$
above we have calculate Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+.....+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-2}+.....+\binom{n}{n}x^0$$
Now calcualting Coefficient of $x^n$ in $$(1+x)^n\cdot (x+1)^n = (1+x)^{2n} = \binom{2n}{n}$$
So we get $$\mathop{\sum\sum}_{0\leq i<j\leq n}\binom{n}{i}\cdot \binom{n}{j} = \frac{1}{2}\left[2^{2n} - \binom{2n}{n}\right]$$
Thanks

A: Consider two sets, $A$ and $B$ each with $n$ elements. All elements are considered distinct.
$\displaystyle \sum_{0 \leq i < j \leq n} \binom{n}{i} \binom{n}{j}$ can be interpreted as the number of ways to pick a non-empty subset of $A \cup B$ with the requirement that the number of elements from $A$ who are picked is strictly smaller than the number of elements from $B$ who are picked.
$2^{2n}$ counts the total number of ways to pick a subset of any size from $A \cup B$. The number of cases where the same number of elements are picked from $A$ and $B$ (including the empty set) is obtained from the sum $\displaystyle \sum_{i=0}^n \binom{n}{i}^2$.
By symmetry, half of the $\displaystyle 2^{2n} - \sum_{i=0}^n \binom{n}{i}^2$ cases have more elements from $A$ compared to $B$.
The identity $\displaystyle \sum_{i=0}^n \binom{n}{i}^2 = \binom{2n}{n}$ matches the result with yours.
I do not know of a combinatorial argument for this last identity though. Does anyone have any?

A: A bijective correspondence can be established between this issue and the following one:
[Dealing with the LHS of the equation :]
Let $S$ be a set with Card(S)=n.
Consider all (ordered) pairs of subsets $(A,B)$ such that
$$A \subsetneqq B \subset S. \ \ (1)$$
[Dealing with the RHS of the equation :]
Consider all subsets of a set $T$ with $2n$ elements, then exclude a certain number of them (to be precised later), $T$ being defined as :
$$T:=S \cup I \ \ \ \ \text{with} \ \ \ \ \ I:=\{1,2,\cdots n\}.$$
Let $C$ be any subset of $T$. We are going to establish (in the "good cases") a correspondence between $C$ and an ordered pair $(A,B)$ verifying (1).
Let us define first a certain fixed ordering of the elements of $S$ :
$$a_1 < a_2 < \cdots < a_n. \ \ (2)$$
Let $B:=T \cap S$ and $J:=T \cap I$. Three cases occur :

*

*If $Card(J)<Card(B)$, $J$ is the set of indices "selecting" the elements of $B$ that belong to $A$ in the ordered set $S$.

*If $Card(J)>Card(B)$, we switch the rôles of indices and elements. This accounts for the half part of the formula: indeed this second operation will give the same sets $(A,B)$.

*If $Card(J)=Card(B)$, which happens in $2n \choose n$ cases, such cases cannot be placed in correspondence with a case considered in (1), thus have to be discarded.
I know this could be written in a more rigorous way, but I believe the main explanations are there.


text:
Q: how to deal with failover primary service when using mirroring nginx? I have to flask app that both are the same, running on port 8080 and 8081.
service 8080 is primary.
I want to mirror request to 8081.
till now everything works with following nginx config file.
but when the primary service (8080) goes down, nginx return 502.
how to configure
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
        worker_connections 768;
        # multi_accept on;
}

http {
        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

upstream backend {
    server localhost:8080;

 }

upstream test_backend {
    server localhost:8081;
}

server {
    server_name mirroring;
    listen 80;

    access_log /var/log/nginx/proxy.log;
    error_log /var/log/nginx/proxy.error.log info;

    location / {
        mirror /mirror;
        proxy_pass http://backend;
    }

    location = /mirror {
        proxy_pass http://test_backend$request_uri;
    }

  }
}

How to adjust this issue to overcome request not responding.


text:
Q: How to change XML attribute value? I want change an attribute value of a XML file.
I already change a node value, in this manner:
xercesc_3_2::XMLPlatformUtils::Initialize();

xercesc_3_2::XercesDOMParser* parser = new xercesc_3_2::XercesDOMParser;
parser->setValidationScheme(xercesc_3_2::XercesDOMParser::Val_Never);
parser->parse(fileName.c_str());

xercesc_3_2::DOMDocument* doc = parser->getDocument();

xercesc_3_2::DOMElement* root = doc->getDocumentElement();

xercesc_3_2::DOMXPathResult* result = doc->evaluate(
    xercesc_3_2::XMLString::transcode("/document/child1/child2"),
    root,
    NULL,
    xercesc_3_2::DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
    NULL);
result->getNodeValue()->getFirstChild()->setNodeValue(xercesc_3_2::XMLString::transcode(value.c_str()));

But I don't understand how to change the attribute value.
How can I do?


text:
Q: Jquery - need help on usage Is this the right way of using the php script in the jquery function?
The pathToTabImage variable
<script type="text/javascript">
    $(function(){
        $('.slide-out-div').tabSlideOut({
            tabHandle: '.handle',                     //class of the element that will become your tab
            pathToTabImage: '<?php echo $this->baseurl ?>/templates/<?php echo $this->template; ?>/images/ack.jpg';, //path to the image for the tab //Optionally can be set using css
            alert(pathToTabImage);
            imageHeight: '122px',                     //height of tab image           //Optionally can be set using css
            imageWidth: '125px',                       //width of tab image            //Optionally can be set using css
            tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
            speed: 600,                               //speed of animation
            action: 'click',                          //options: 'click' or 'hover', action to trigger animation
            topPos: '600px',                          //position from the top/ use if tabLocation is left or right
            leftPos: '550px',                          //position from left/ use if tabLocation is bottom or top
            fixedPosition: false                      //options: true makes it stick(fixed position) on scroll
        });

    });

A: Remove the semi-colon.
/images/ack.jpg';,
to
/images/ack.jpg',
Also, this alert isn't doing you any favours either, and needs to go.
alert(pathToTabImage);

A: It is one of the available ways to inject PHP codes, inside as HTML, CSS, or JS Document/Snippet. However, syntactically, there are few errors.
PHP Error
<?php echo $this->baseurl ?>

No selicolon on the end statement
JavaScript Error
pathToTabImage: '...';, //...

Unneeded semicolon, ending a statement in an incorrect way
alert(pathToTabImage);

Injecting an independant statement inside another statement


text:
Q: NullPointerException, even though object is pointing to the FXML instance (I am using Scene Builder...)
Here is the MusicGeneratorGUI class...
public class MusicGeneratorGUI extends Application {
    @FXML private Sphere icon;
    ...
}

Here I have instantiated the object from the FXML file with the same ID...
<Sphere fx:id="icon" ... />

However, System.out.println(icon); in the main method of the controller class produces null.
The 'icon' Sphere object is null.
Here is the main class... ('controller class')
public class Main implements Initializable {
    @FXML public static Sphere icon;

    public static void main(String args[]) {
        System.out.println(icon);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //Nothing here...
    }
    ...
}

A: You need to create an instance of your loader.
FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));

Then you can get access to an instance of your controller.
Main main = loader.getController();

Then you can access the icon from the controller.
System.out.println(main.icon);

Note, you can still get the parent via.
Parent root = loader.load();

You might want to consider doing this from the initialize method of the controller, then you don't need to expose the icon of the Controller. Also, why is your icon static? I think you need to ditch the static.


text:
Q: How Can I write UART function without vsnprintf How can I use Serialdebug function without vsnprintf or args. I want to use just
  HAL_UART_Transmit function to print my string.

instead of this function:
void Serialdebug(const char *serial_data, ...)
{
  char uartbuffer[1024]="";
  va_list arg;
  va_start(arg, serial_data);
  uint16_t len = vsnprintf(uartbuffer, 1024, serial_data, arg);
  va_end(arg);
  HAL_UART_Transmit(&huart2, (uint8_t *)uartbuffer, len, 100);

}

How can I do that?

A: You can basically reduce the function to a call to HAL_UART_Transmit:
void Serialdebug(const char *str)
{
    HAL_UART_Transmit(&huart2, (uint8_t *)str, strlen(str), 100);
}


text:
Q: Three body problem with point interactions I've studied the HVZ theorem for the three body problem interacting with regular potentials. I'd like to extend this result to the three body problem with point interactions (delta potentials).
Is there anyone who have studied this problem and knows some references about it?


text:
Q: Angular form submit IE9 I am building an angular application that requires user to login in a form.
This form is working on both Chrome and Firefox, but not on IE9.
The html form submit:
<button  class="btn  btn-theme-bg btn-lg" ng-click="!form.$invalid?login():null"  ng-disabled="loading">Log in  <i ng-show="loading" class="fa fa-spinner fa-spin"></i></button>

The controller:
$scope.login = function(){
        $scope.loading = true;
        $scope.doShake = false;
        $scope.invalidCredentials = false;
        userRestService.login($scope.user).$promise.then(function(client){
            console.log('login ok');
            sharedDataService.setCurrentClient(client);
            $rootScope.$broadcast('userLoggedIn');
            $state.go('root.dashboard.list');

        }).catch(function(){
            $scope.attemptCount = $scope.attemptCount+1;
            if($scope.attemptCount>1){$scope.doShake = true;};
            $scope.loading = false;
            $scope.user.password = '';
            $scope.passwordError = false;
            $scope.invalidCredentials = true;
        });
    };

On IE9, after submit, the API is targeted via HTTP POST with the right parameters and works as expected, and after returning that the user is ok, the routing is wrong and the login and the password appear in clear in the URL before the #:
http://localhost:3000/?email=test@test.com&password=test#/home
Any idea what might cause this error in IE9 only?


text:
Q: Cannot set font-family to AvantGard in React.js I want to add AvantGard font to one paragraph in my React app, but it seems the font has no effect and I don't know why, here is how I am adding it:

*

*I keep it as a ttf file in my assets folder.

*I have global scss file index.css and I declare it there like this:

@font-face {
  font-family: 'AvantGard';
  font-style: normal;
  src: url('./assets/fonts/avant_gartt/AvantGard.ttf');
}

*I also have a variables.scss in which I keep it like this:

$avantGard: 'AvantGuard';

*I import my variables in my component's css like this:

@import './variables.scss';

and then I just set the font-size of my paragraph:
 font-family: $avantGard;

Does anyone have any idea why my font does not work? The rest of my fonts work the same way, but not this one.

A: Check your spelling on number 3.
AvantGard or AvantGuard?


text:
Q: Swagger renders in app.use but not in app.get I am trying to render a Swagger Document using swagger-ui-express. But only when using app.use, it renders in the browser, but when posting it in app.get, the HTML page is not rendered(blank screen) but the HTML code is generated in response body when I checked in Postman
Below is my code,
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc))
The above renders the required HTML page.
app.get('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc))
The above generates the HTML code but not rendered in browser, am I missing something ?
Update :
I use the generateHTML method, but it still seems to work the same way,
app.use('/api-docs-html/BOOKING-CANCELLATION', function(req, res, next) {
    var pathArraySplit = req.originalUrl.split('/');
    var apiNameWithHyphen = pathArraySplit[2].trim()
    var apiNameWithUnderScore = apiNameWithHyphen.replace('-', '_');
    swaggerDocument = JSONConstructor.JSONConstructorTest(apiNameWithUnderScore)
    swaggerHtml = swaggerUi.generateHTML(swaggerDocument, swaggerUiOpts)
    next()
},swaggerUi.serveFiles(swaggerDocument, swaggerUiOpts))
app.get('/api-docs-html/BOOKING-CANCELLATION', (req, res) => { res.send(swaggerHtml) });

A: swaggerUi.serve is a middleware function so its need to be used with app.use(), Refer
Middleware (app.use()) and  Route Handler(app.get()) are not same function for handling request, Refer
next() call inside a middleware invokes the next middleware or route handler depending on whichever is declared next. But next() call inside a route handler invokes the next route handler only. If there is a middleware next then it's skipped. Therefore middlewares must be declared above all route handlers.
You can use like this as alternative,
app.use('/api-docs', swaggerUi.serve);
app.get('/api-docs', swaggerUi.setup(swaggerDocument));


text:
Q: Improving laravel mails to outlook/hotmail I have a Laravel app sending emails via MailGun. For Gmail addresses it works right of the bat, but for Outlook/Hotmail they are marked as spam and have broken formatting. I have identified some issues but not sure how to best fix them.
I am aware this post is broad but the common thing is how to please outlook/hotmail.
Multipart messages
According to MailGun help:

It is best to send multi-part emails using both text and HTML or text only. Sending HTML the only email is not well received by ESPs.

Given my Mailables' build function below, how can I achieve that?
public function build()
{
    return $this->from('name@mysite.com')
        ->subject('Welcome to mysite!')
        ->view('emails.welcome_new_user', [
            'updateLink' => env('APP_URL') . '/subscribers/' . $this->subscriber->id . "/edit/" . $this->subscriber->token,
            'deleteLink' => env('APP_URL') . '/subscribers/' . $this->subscriber->id . "/delete/" . $this->subscriber->token
        ]);
}

Headers
According to MailGun help:

Make sure you are using unsubscribe links and headers in your emails. Many ESPs (particularly Hotmail) pay attention to this and if they are not there, you are likely to get filtered.

In the view I have two unsubscribe links, one as a button in the body and one in the footer as plain text link so that should be fine. But how do I supply Headers and which headers? I assume it is done similar to this section in Laravel docs:
$message->getHeaders()->addTextHeader('Custom-Header', 'HeaderValue');

Other tips on specific Outlook/Hotmail requirements
Also most appreciated


text:
Q: Hibernate META-INF Location wrong? For some weird reason my Hibernate can't find my persistence.xml in the META-INF folder. I have following project structure:

*

*src

*

*eu.bsmusin.pupil.project.db.DataBase.java

*META-INF/persistence.xml

My class DataBase.java calls the method
Persistence.createEntityManagerFactory("LocalUnit");

The error says it can't find a persistence unit called LocalUnit. I triple checked the name and all other properties and tried multiple example persistence.xml files from the internet. I believe, that Hibernate can't find my meta-inf folder for some stupid reason.
Did this happen to anyone or does somebody know how to fix that problem?

A: In all cases, persistence.xml always resides in {root-of-persistence-unit}/META-INF/ directory. For example,
foo.war:
WEB-INF/classes/META-INF/persistence.xml  //good
WEB-INF/classes/com/foo123/jpa/Project.class
WEB-INF/web.xml
index.jsp

You may also package entity classes and persistence.xml inside a library jar, which is packaged inside the war: WEB-INF/lib
foo.war:
WEB-INF/lib/my-entities.jar
WEB-INF/web.xml
index.jsp

my-entities.jar:
META-INF/persistence.xml  //good
com/foo123/jpa/Project.class

If you are using maven project :
src/main/resources is the place. When it comes to persistence.xml it should be placed in the META-INF folder. So to conclude: src/main/resources/META-INF/persistence.xml.


text:
Q: Mute For-loop output I have this for-loop batch to convert a bunch of text files to PDF. Sometimes there are literally thousands of files, which I do not want the output to fill up the log files.
How can I mute the output of this for-loop batch?  I've tried placing 2>NUL in a few places, without much success.
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%F IN (D:\TEMP\FILE*.TXT) DO (
    SET TMPFILE=%%F
    SET NEWFILE=!TMPFILE:~0,-4!.PDF
    C:\EXE\txt2pdf.exe !TMPFILE! !NEWFILE! -PFS9
)

Thanks in advance!

A: To prevent output of individual lines you can both turn echoing off individually for the line, using @, and prevent both stdOut and stdIn using command redirection 1> and 2>.
You can also completely remove SETLOCAL ENABLEDELAYEDEXPANSION, SET TMPFILE=%%F, and SET NEWFILE=!TMPFILE:~0,-4!.PDF, then change C:\EXE\txt2pdf.exe !TMPFILE! !NEWFILE! -PFS9 to "C:\EXE\txt2pdf.exe" "%%F" "%%~dpnF.PDF" -PFS9.
Essentially your entire batch file, (or single line if you have others), could look like this:
@For %%G In ("D:\TEMP\FILE*.TXT") Do @"C:\EXE\txt2pdf.exe" "%%G" "%%~dpnG.pdf" -PFS9 1>NUL 2>&1


text:
Q: how to connect to Oracle 11g database using Asp.Net How do I connect to an Oracle 11g database using asp.net3.5?
what is the name space and how to write connection string in web.config file?
please help me..

A: It depends on the data provider. See: ConnectionString.com And perhaps more specifically: The .NET Data Provider for Oracle. The connection string should look very similar in your web.config file. The only differences, obiously, will be the system/db name(s), user id, pwd etc.
Namespaces:

it is necessary to know which type of
  objects can have the same name and
  which are not. For this it is
  necessary to introduce the concept of
  a namespace. A namespace defines a
  group of object types, within which
  all names must be uniquely
  identified—by schema and name. Objects
  in different namespaces can share the
  same name.

Here's also a nice tutorial you can follow that is ASP.NET-specific. And another article that may be of interest.
And a code snippet (using .NET Oracle provider:)
public DataTable myDataTable(string SQL, string ConnStr)
{
    OracleConnection cn = default(OracleConnection);
    DataSet dsTemp = null;
    OracleDataAdapter dsCmd = default(OracleDataAdapter);

    cn = new OracleConnection(ConnStr);
    cn.Open();

    dsCmd = new OracleDataAdapter(SQL, cn);
    dsTemp = new DataSet();
    dsCmd.Fill(dsTemp, "myQuery");
    cn.Close();
    return dsTemp.Tables[0];
}


text:
Q: Generalization of mat2str to cell arrays I sometimes miss a function to produce a string representation of a (possibly nested) cell array. It would be a generalization of mat2str, which only works for non-cell arrays (of numeric, char or logical type).

Given an array x, how to obtain a string representation y, such that evaluating this string produces x?

For example, the input
x = {[10 20], {'abc'; false; true;}};

should produce an output string like
y = '{[10 20], {''abc''; false; true}}';

(or some variation regarding spacing an separators), such that
isequal(x, eval(y))

is true.

A: This process, transforming a data structure into a string that later can be evaled, is named serialization.
There is a serialize function for Octave that can be used for this purpose which supports any core data type (not only cell arrays) with any number of dimensions (not only 2d).
Examples:
## Works for normal 2d numeric arrays
octave> a = magic (4);
octave> serialize (a)
ans = double([16 2 3 13;5 11 10 8;9 7 6 12;4 14 15 1])
octave> assert (eval (serialize (a)), a)

## Works for normal 3d numeric arrays with all precision
octave> a = rand (3, 3, 3);
octave> serialize (a)
ans = cat(3,double([0.53837757395682650507 0.41720691649633284692 0.66860079620859769189;0.018390655109800025518 0.56538265981533797344 0.20709955358395887304;0.86811365238275806089 0.18398187533949311723 0.20280927116918162634]),double([0.40869259684132724919 0.96877003954154328191 0.32138458265911834522;0.37357584261201565168 0.69925333907961184643 0.10937000120952171389;0.3804633375950405294 0.32942660641033155722 0.79302478034566603604]),double([0.44879474273802461015 0.78659287316710135851 0.49078191654039543534;0.66470978375890155121 0.87740365914996953922 0.77817214018098579409;0.51361398808500036139 0.75508941052835898411 0.70283088935085502591]))
octave> assert (eval (serialize (a)), a)

## Works for 3 dimensional cell arrays of strings
octave> a = reshape ({'foo', 'bar' 'qux', 'lol', 'baz', 'hello', 'there', 'octave'}, [2 2 2])
a = {2x2x2 Cell Array}
octave> serialize (a)
ans = cat(3,{["foo"],["qux"];["bar"],["lol"]},{["baz"],["there"];["hello"],["octave"]})
octave> assert (eval (serialize (a)), a)

However, a better question is why do you want to do this in the first place? If the reason you're doing this is to send variables between multiple instances of Octave, consider using the parallel and mpi packages which have functions specialized designed for this purpose.

A: The following function works for arbitrary arrays, with any nesting structure and for any shape of the arrays, as long as they are all 2D arrays. Multidimensional arrays are not supported (same as mat2str).
The function also allows specifying arbitrary row and column separators for cell arrays (for example, to choose between comma and space), and optionally forcing those separators for non-cell arrays too (thus overriding mat2str'behaviour). Default separators in cell arrays are ' ' for columns and '; ' for rows.
function y = array2str(x, col_sep, row_sep, sep_noncell)
% Converts a (possibly cell, nested) array to string representation
%
% Optional inputs col_sep and row_sep specify separators for the cell arrays.
% They can be arbitrary strings (but they should be chosen as per Matlab rules
% so that the output string evaluates to the input). Optional flag sep_noncell
% can be used to force those separators with non-cell arrays too, instead of
% the separators produced by mat2str (space and semicolon)

% Default values
if nargin<4
    sep_noncell = false;
end
if nargin<3
    row_sep = '; ';
end
if nargin<2
    col_sep = ' ';
end

x = {x}; % this is to initiallize processing
y = {[]}; % [] indicates content unknown yet: we need to go on
done = false;
while ~done
    done = true; % tentatively
    for n = 1:numel(y);
        if isempty(y{n}) % we need to go deeper
            done = false;
            if ~iscell(x{1}) % we've reached ground
                s = mat2str(x{1}); % final content
                if sep_noncell % replace mat2str's separators if required
                    s = regexprep(s,'(?<=^[^'']*(''[^'']*'')*[^'']*) ', col_sep);
                    s = regexprep(s,'(?<=^[^'']*(''[^'']*'')*[^'']*);', row_sep);
                end
                y{n} = s; % put final content...
                x(1) = []; % ...and remove from x
            else % advance one level
                str = ['{' repmat([{[]}, col_sep], 1, numel(x{1})) '}'];
                ind_sep = find(cellfun(@(t) isequal(t, col_sep), str));
                if ~isempty(ind_sep)
                    str(ind_sep(end)) = []; % remove last column separator
                    ind_sep(end) = [];
                end
                step_sep = size(x{1}, 2);
                str(ind_sep(step_sep:step_sep:end)) = {row_sep};
                y = [y(1:n-1) str y(n+1:end)]; % mark for further processing...
                x = [reshape(x{1}.', 1, []) x(2:end)]; % ...and unbox x{1},
                    % transposed and linearized
            end
        end
    end
end
y = [y{:}]; % concatenate all strings

The above function uses regular expressions to force the specified separators in non-cell arrays. This works in Matlab but not in Octave, due to limitations in supported lookbehind patterns. The following modified version avoids regular expressions, and thus works in Matlab and in Octave. Only the part between if sep_noncell and the matching end changes with respect to the first version.
function y = array2str(x, col_sep, row_sep, sep_noncell)
% Converts a (possibly cell, nested) array to string representation.
% Octave-friendly version
%
% Optional inputs col_sep and row_sep specify separators for the cell arrays.
% They can be arbitrary strings (but they should be chosen as per Matlab rules
% so that the output string evaluates to the input). Optional flag sep_noncell
% can be used to force those separators with non-cell arrays too, instead of
% the separators produced by mat2str (space and semicolon)

% Default values
if nargin<4
    sep_noncell = false;
end
if nargin<3
    row_sep = '; ';
end
if nargin<2
    col_sep = ' ';
end

x = {x}; % this is to initiallize processing
y = {[]}; % [] indicates content unknown yet: we need to go on
done = false;
while ~done
    done = true; % tentatively
    for n = 1:numel(y);
        if isempty(y{n}) % we need to go deeper
            done = false;
            if ~iscell(x{1}) % we've reached ground
                s = mat2str(x{1}); % final content
                if sep_noncell % replace mat2str's separators if required
                    for k = flip(find(~mod(cumsum(s==''''),2) & s==' ')) % process
                        % backwards, because indices to the right will become invalid
                        s = [s(1:k-1) col_sep s(k+1:end)];
                    end
                    for k = flip(find(~mod(cumsum(s==''''),2) & s==';'))
                        s = [s(1:k-1) row_sep s(k+1:end)];
                    end
                end
                y{n} = s; % put final content...
                x(1) = []; % ...and remove from x
            else % advance one level
                str = ['{' repmat([{[]}, col_sep], 1, numel(x{1})) '}'];
                ind_sep = find(cellfun(@(t) isequal(t, col_sep), str));
                if ~isempty(ind_sep)
                    str(ind_sep(end)) = []; % remove last column separator
                    ind_sep(end) = [];
                end
                step_sep = size(x{1}, 2);
                str(ind_sep(step_sep:step_sep:end)) = {row_sep};
                y = [y(1:n-1) str y(n+1:end)]; % mark for further processing...
                x = [reshape(x{1}.', 1, []) x(2:end)]; % ...and unbox x{1},
                    % transposed and linearized
            end
        end
    end
end
y = [y{:}]; % concatenate all strings

How it works
I chose a non-recursive approach because I'm usually more confortable with iteration than with recursion.
The output is gradually built by keeping substrings or empty arrays ([]) in a cell array (y). An empty array in a cell of y indicates "further processing is needed". Substrings define the "structure", or eventually the numeric, character or logical contents in the deepest level of the cell nesting.
In each iteration, the first empty array found in y is substituted by actual content, or by substrings and other empty arrays to be processed later. When y doesn't contain any empty array the process ends, and all substrings of y are concatenated to obtain the final string output.
For example, given input x = {[10 20], {'abc'; false; true;}}; and calling y = array2str(x) the array y in each step is a cell array containing:
'{'   []   ', '   []   '}'

'{'   '[10 20]'   ', '   []   '}'

'{'   '[10 20]'   ', '   '{'   []   '; '   []   '; '   []   '}'   '}'

'{'   '[10 20]'   ', '   '{'   ''abc''   '; '   []   '; '   []   '}'   '}'

'{'   '[10 20]'   ', '   '{'   ''abc''   '; '   'false'   '; '   []   '}'   '}'

'{'   '[10 20]'   ', '   '{'   ''abc''   '; '   'false'   '; '   'true'   '}'   '}'

and the latter is finally concatenated into the string
'{[10 20] {''abc''; false; true}}'

As an example with custom separators, array2str(x, ', ', '; ', true) would give
'{[10, 20], {''abc''; false; true}}'


text:
Q: UWP Device Manufacturer I am attempting to get the manufacturer of a radio device (on a Windows system). I retrieve the radio devices and look for the System.Devices.DeviceManufacturer property type. But it is not in the collection. I can see the radio active in device manager and when I check it's properties there is a manufacturer. So my question -- should the same manufacturer property exist in the device property list  that correlates to the manufacturer displayed in the device manager properties dialog. If not -- is it possible to get the manufacturer -- and how do I do this?
Peter

A: To get the Manufacturer, you need to use the Windows.Devices.Enumeration.Pnp API. The usage of PnpObject is similar to that of the Enumeration API. When you create the PnpObject with one of it's static methods, you need to add "System.Devices.Manufacturer" to the list of properties like the following:
private PnpObjectWatcher pnpObjectWatcher = null;

private void Button_Click(object sender, RoutedEventArgs e)
{
    List<string> properties = new List<string>();
    properties.Add("System.Devices.Manufacturer");
    pnpObjectWatcher = PnpObject.CreateWatcher(PnpObjectType.DeviceContainer,properties);
    pnpObjectWatcher.Added += PnpObjectWatcher_Added;
    pnpObjectWatcher.Start();
}

private void PnpObjectWatcher_Added(PnpObjectWatcher sender, PnpObject args)
{
    Debug.WriteLine(args.Properties["System.Devices.Manufacturer"]);
}

Note that the PnpObjectType must be of type DeviceContainer, otherwise the manufacturer name cannot be obtained.


text:
Q: как сделать так чтобы Text не выходил за границы в QML Как можно сделать так, чтобы в Text символы не выходили за границу ProgressBar или любого другого элемента? если символы выходят за границу они должны исчезать .
ProgressBar {
            id: progressBarDuration
            anchors.verticalCenter: controlRect.verticalCenter
            anchors.left: controlRect.left
            anchors.leftMargin: rectBackground.width / marginLeftRight
            value: 1
            width: 400
            style: touchStyle

            Text {
                anchors.verticalCenter: progressBarDuration.verticalCenter
                anchors.left: progressBarDuration.left
                anchors.leftMargin: getWidth(rectBackground.width, 10)
                anchors.right: progressBarDuration.right
                text: qsTr("texgfdshgfjdkghfdkghfdfgdsfdsslhgjfdshgjfdskjgfdshklghft")
            }
        }

A: Нужно использовать свойство elide у Text


text:
Q: text of a nested bullet-point list to HTML I have this:
Example input:
* First item
* Second item
    * Subitem 1
        * sub-subitem!
    * Subitem 3
* Third item

Example output:

First item

Second item

Subitem 1

sub-subitem!

Subitem 3

Third item

I have created a Java class that send every String line to an array of chars and I treat every character alone.
My problem is when to close the  tags
Any idea?
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TextToHtml {
    StringBuilder itemName = new StringBuilder();
    String sCurrentLine;
    int usingUlTAG=0;

public TextToHtml(){
        BufferedReader br = null;
        try {
            boolean closeLItag=false;
            br = new BufferedReader(new FileReader("NestedText.txt"));
            System.out.println("
");
            while ((sCurrentLine = br.readLine()) != null) {
                    char[] item = sCurrentLine.toCharArray();
                    for(int i=0; i<item.length;i++){
                            if(item[i]!='*' && item[i]!='\n' && item[i]!='\t'){
                                    itemName.append(item[i]);
                continue;
            }
            if(item[i]=='*'){
                itemName.append("
");
                closeLItag=true;
            }
            else if(item[i]=='\t'){
                if(item[i+1]=='*'){
                    if(usingUlTAG<1)
                    itemName.append("\t
\n\t\t");
                    itemName.append("\t\n\t\t");
                    usingUlTAG= 1;
                    continue;
                }
                if(item[i+1]=='\t'){
                    itemName.append("\t\t
\n\n\t\t");
                    usingUlTAG=2;
                    continue;
                }
            }
        }
        if(closeLItag){
            itemName.append("
\n");
        }

    }
    System.out.println(itemName+"/ul>");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

public static void main(String[] args) {
    new TextToHtml();
}
}

A: You'll have to look ahead to the next line and see if its list level is different from the current item's. Then you can add or close tags based on the difference in level, if any. Here's code that does this:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TextToHtml
{
    StringBuilder itemName = new StringBuilder();
    String sCurrentLine;
    String sNextLine; // A "peek" at what's next to determine if
 is needed

    public TextToHtml()
    {
        BufferedReader br = null;
        try
        {
            br = new BufferedReader(new FileReader("NestedText.txt"));
            System.out.println("
");
            sNextLine = br.readLine();
            while ((sCurrentLine = sNextLine) != null)
            {
                sNextLine = br.readLine();

                char[] item = sCurrentLine.toCharArray();
                int itemLevel = 0;
                for (int i = 0; i < item.length; i++)
                {
                    if (item[i] != '*' && item[i] != '\n' && item[i] != '\t')
                    {
                        itemName.append(item[i]);
                    }
                    else if (item[i] == '*')
                    {
                        itemName.append("\t
");

                        // Trim leading space character
                        if (item[i + 1] == ' ')
                            i++;
                    }
                    else if (item[i] == '\t')
                    {
                        itemLevel++;
                        itemName.append("\t\t");
                    }
                }

                int nextItemLevel = 0;
                if (sNextLine != null)
                {
                    char[] nextItem = sNextLine.toCharArray();
                    for (int i = 0; i < nextItem.length; i++)
                    {
                        if (nextItem[i] == '\t')
                            nextItemLevel++;
                        else
                            break;
                    }
                }
                // Next is the same level; there are no subitems
                if (itemLevel == nextItemLevel)
                    itemName.append("
");
                // Next is a deeper level; there are subitems
                else if (itemLevel < nextItemLevel)
                {
                    // In case the next item is more than 1 level deeper
                    for (int i = itemLevel + 1; i <= nextItemLevel; i++)
                    {
                        itemName.append("\n");
                        for (int j = 0; j < i; j++)
                            itemName.append("\t\t");
                        itemName.append("
");

                        // If the next item's level is reached, it will create its own

                        if (i != nextItemLevel)
                        {
                            itemName.append("\n");
                            for (int j = 0; j  nextItemLevel)
                {
                    itemName.append("
");
                    for (int i = itemLevel - 1; i >= nextItemLevel; i--)
                    {
                        itemName.append("\n");
                        for (int j = 0; j <= i; j++)
                            itemName.append("\t\t");
                        itemName.append("
\n");
                        for (int j = 0; j < i; j++)
                            itemName.append("\t\t");
                        itemName.append("\t
");
                    }
                }
                itemName.append("\n");
            }
            System.out.println(itemName + "
");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (br != null)
                    br.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        new TextToHtml();
    }
}

Note that this will only work if the levels are indented with tabs, not spaces.

A: If, as your current code suggests, the list item lines in the original text all use hard tabs for indentation then all you need to do is work through the text a line at a time, keeping track of the indentation level (number of tabs) of the previous line.  This code doesn't produce nice indentation in the resulting HTML but it gets the
 and
 nesting right which is all an HTML browser really cares about
import java.io.*;
import java.util.regex.*;

public class Main {
  public static void main(String[] args) throws Exception {
    StringBuilder result = new StringBuilder();
    BufferedReader br = new BufferedReader(new FileReader("NestedText.txt"));
    try {
      int lastIndent = -1; // indent level of last line
      int depth = 0; // number of levels of
 we are currently inside
      String line;
      Pattern indentPattern = Pattern.compile("((\\t*)\\* )?(.*)");
      while((line = br.readLine()) != null) {
        Matcher m = indentPattern.matcher(line);
        m.matches(); // guaranteed to be true, but needed to update matcher state

        if(m.group(1) != null) { // this is a new list item
          int thisIndent = m.end(2); // number of leading tabs, may be zero

          // there are three possible cases
          if(thisIndent == lastIndent) {
            // same level as last list item
            result.append("
");
          } else if(thisIndent > lastIndent) {
            // starting a child list
            result.append("
");
            depth++;
          } else {
            // returning to parent list
            result.append("
");
            depth--;
            result.append("
");
            result.append("
");
          }

          result.append("
");
          lastIndent = thisIndent;
        } else { // this is a continuation of the previous list item
          result.append(" ");
        }
        // append this line's text (not including the indent and *)
        result.append(m.group(3));
      }

      // run out of items, close any outstanding lists
      while(depth-- > 0) {
        result.append("
");
        result.append("
");
      }

      System.out.println(result);
    } finally {
      br.close();
    }
  }
}

Here, I treat any line that doesn't start with tabs and a star as a continuation of the previous
, i.e.
* This is a very long list
item that continues over several
  lines
* This is a second item
    * this is a child item
  that also continues
   over several lines

is OK.

A: I have fixed the problem following Jan Dvorak´s advice.
the following code works for and I am putting below in case if it helps someone else.
Thanks for all your contribution
MarkdownProcessor m = new MarkdownProcessor();
String html = null;
try {
html = m.markdown(MyString));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(html);


text:
Q: Manually Handling WCF Session Timeout I am manually maintaining WCF Session. When client login a GUID is given to the client as
sessionId. All others methods have sessionId as parameter that client will provide.
Every thing working fine. Now how can i manually manage Session Timeout ?

A: Let's first get the fact that you are trying to maintain state between WCF calls, which rather violates the principle in the first place, out of the way first. (Take a look at the question: Manually Handling WCF Session Timeout)
Assuming that you are generating the guid that is the sessionid then you'll need to store that somewhere, a database seems likely. Store the sessionID there with the current DateTime. Each time a request is received, check the store for the sessionID and see if your timeout has been exceeded, if so the dispose of the sessionID and report the state back to the client. If the timeout has not been exceeded then update the DateTime to the now current DateTime and process the request.


text:
Q: How to convert NSString to a date formattted string I have string with value 01012016 which i want to show to user like 01-01-2016. For this, i am using the below code
-(NSString *)dateToFormatedDate:(NSString *)dateStr {

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

    [dateFormatter setDateFormat:@"MM-dd-yyyy"];
    NSDate *date = [dateFormatter dateFromString:dateStr];

    NSLog(@"date is %@", [dateFormatter stringFromDate:date]);
    return [dateFormatter stringFromDate:date];
}

But this method is always returning nil. I have tried on simulator and device both.
I am not able to figure it out what i did wrong here

A: The format of your NSDateFormatter does not match the string you're trying to pass it. Take a look at this related question...
Converting a string to an NSDate
What you want to do is set the NSDateFormatter to match the string, then once you've created an NSDate object from the string, change the NSDateFormatter to your desired output format. Something like this...
-(NSString *)dateToFormatedDate:(NSString *)dateStr {

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

  [dateFormatter setDateFormat:@"MMddyyyy"];
  NSDate *date = [dateFormatter dateFromString:dateStr];
  [dateFormatter setDateFormat:@"MM-dd-yyyy"];

  NSLog(@"date is %@", [dateFormatter stringFromDate:date]);
  return [dateFormatter stringFromDate:date];
}


text:
Q: Proper ways/strategies of observing and transforming ODE / PDE I encountered with a lot of problem about ODE, many of which needs a proper observing or transforming before continuing, but to me, seeking the "key" out is very hard, for an observing example:

We consider the following ordinary differential equation:
$$\begin{cases}x''(t)+x(t)+x(t)^3=0,\\(x(0),x'(0))=(x_0,0),\end{cases}$$
where $x(t)$ takes values in $\mathbb R$. Prove that for all $x_0 \in\mathbb R$, the solution of the above system is periodic.

I didn't manage to solve it first, but after a hint namely "Observe that $E(t):=\frac{1}{2}x'(t)^2+\frac{1}{2}x(t)^2+\frac{1}{4}x(t)^4$ is conserved" this problem becomes very easy, but this observation is very hard to me. For another transforming example:

Solve the following ordinary differential equation
$$x\frac{dy}{dx}=\sqrt{x^6-y^2}+3y$$

I spent a large amount of time observing this problem and finally figured out that we should take $g(x):=\frac{y(x)}{x^3}$ and this problem will reduce to a much simpler form. (a hint says this can be solved by integration, but I didn't figure it out) But observing or transforming the proper thing takes a large amount of time and sometimes need something like "AHA" moment. So my question is, are there any "good strategies" that we should know of observing or transforming an ODE/PDE?
Thank you very much.

A: That first one is not that bad; in particular you have probably seen $x''+x=0$ before, which has the same basic feature. Basically if there's a periodic solution then there must be a conserved quantity, and the way to go look for that in a "force balance" type equation is to multiply by $x'$ and integrate in time, or equivalently to do a vector line integral over a trajectory in space.
Once you have the conserved quantity, you have periodicity if the level set is closed and contains no equilibrium points (and the solutions are unique).  The generalization of that to multidimensional systems is $x''+\nabla F(x)=0$, in which case $F$ is the conserved quantity. This is a relatively general strategy with physical meaning, so it is worth keeping it in mind.
The second one is a little bit contrived, I think, but one motivation for that substitution comes from thinking about dimensional analysis. If $x$ and $y$ both have units then $y$ must be $x^3 g(x)$ for some dimensionless $g$ just so that $x^6-y^2$ makes sense. This will at least simplify the square root. The fact that the problem in terms of $x$ and $g$ turns out to be separable seems like an artifact of the problem "design" to me, rather than being especially general. Nor does it seem obvious that this will happen at a first glance.
Personally I don't think it is worth actively developing the skill of "getting into the head of the problem author", even though it can help you in coursework, competitions, etc.
Sadly I can't give much completely general advice; differential equations as a subject is full of "pockets" where a strategy helps in that pocket and nowhere else.


text:
Q: Does a "Full Format" on a modern Windows system really check for bad sectors? First things first: I know I could use CHKDSK or any other third-party tool to detect bad sectors but this question is especially dedicated to whether a "Full Format" on modern Windows systems checks for bad sectors.
I've found this answer which says:

When you choose to run a regular format on a volume, files are removed from the volume that you are formatting and the hard disk is scanned for bad sectors. The scan for bad sectors is responsible for the majority of the time that it takes to format a volume. source

In Vista and later, this is accomplished by writing zeros to the entire partition.

The link for the first quote to the Microsoft pages is dead, the link for the second is alive but only says this (emphasize mine):

"The behavior of the format command changed in Windows Vista and later Windows versions. By default in Windows Vista and later versions, the format command writes zeros to the whole disk when a full format is performed. In Windows XP and earlier versions of Windows, the format command doesn't write zeros to the whole disk when a full format is performed."

Microsoft only speaks about that in any modern Windows version beginning at Vista doing a "Full Format" would perform a complete zero-write to the hard disk, but they do not say that the zero-writing process would be connected to a check for bad sectors.
What I am basically looking for is an alive link to the first or any similar quote from Microsoft itself, confirming a "Full Format" on any modern Windows (7, 8 and/or 10) system would perform a bad sector check by writing the zeroes OR any proof that it does that (maybe by personal experience).
Thank you for your time. Any help appreciated.

A: Yes, a Full Format checks for bad sectors.
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/format

The format command creates a new root directory and file system for
the disk. It can also check for bad areas on the disk, and it can
delete all data on the disk. To be able to use a new disk, you must
first use this command to format the disk

.

A: Does a "Full Format" on modern Windows systems check for bad sectors?
By implication, yes.
The documentation for the format command says:

Applies to: Windows 10, Windows Server 2016

...

/q  Performs a quick format. Deletes the file table and the root
directory of a previously formatted volume, but does not perform a
sector-by-sector scan for bad areas.

(emphasis mine)
This implies that a full format (not using the /q option) does check for bad sectors.
In addition:

The format command creates a new root directory and file system for the disk. It can also check for bad areas on the disk, and it can delete all data on the disk. To be able to use a new disk, you must first use this command to format the disk.

(emphasis mine)
Source format | Microsoft Docs


text:
Q: Magento2 : How to get active payment methods list store wise I want to get all active payment method list store wise.
I have two store
-- store indstore
-- store usstore
And i have set payment methods for only indstore
and if i try to get all active methods ,it returns from default store settings
and from default settings payment methods are disable.
if i enable from default settings than i got all payment methods.
Does anyone know how i can get methods store wise?

app\code\Vendor\Extension\Model\System\Methods.php

<?php

namespace Vendor\Extension\Model\System;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Payment\Model\Config;
class Methods implements \Magento\Framework\Option\ArrayInterface
{
    protected $scopeConfig;
    protected $paymentmodelconfig;

    public function __construct(Config $paymentmodelconfig, ScopeConfigInterface $scopeConfig)
    {
        $this->paymentmodelconfig = $paymentmodelconfig;
        $this->scopeConfig = $scopeConfig;
    }

    public function toOptionArray()
    {
        $payments = $this->paymentmodelconfig->getActiveMethods();

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);

        $methodList = $this->scopeConfig->getValue('payment',\Magento\Store\Model\ScopeInterface::SCOPE_STORE,1);

            foreach ($methodList as $code => $_method) {
                $active_status = "";
                $title = "";
                if (isset($_method['active']))
                {
                    if ($_method['active'] == 1)
                    {
                        if (isset($_method['title']))
                        {
                            $title = $_method['title'];
                            $logger->info($title);
                        }
                    }
                }
                 $methods = array();
                 return $methods;
        }
    }
}

Output IN Log File

2019-12-24T05:55:20+00:00 INFO (6): Check / Money order

Paypal is also active but i am getting only check/money order

A: class ABC{
    protected $paymentMethodList;
    public function __construct(
        \Magento\Payment\Model\PaymentMethodList $paymentMethodList
    ) {
        $this->paymentMethodList = $paymentMethodList;
    }

    public function getmethods()
    {
        $storeId = 'your store id';
        $this->paymentMethodList->getActiveList($storeId);
    }
}

A: namespace VendorName\ModuleName\Model;

use \Magento\Framework\App\Config\ScopeConfigInterface;
use \Magento\Payment\Model\Config;

class Paymentmethod extends \Magento\Framework\DataObject
    implements \Magento\Framework\Option\ArrayInterface
{
    /**
     * @var ScopeConfigInterface
     */
    protected $_appConfigScopeConfigInterface;
    /**
     * @var Config
     */
    protected $_paymentModelConfig;

    /**
     * @param ScopeConfigInterface $appConfigScopeConfigInterface
     * @param Config               $paymentModelConfig
     */
    public function __construct(
        ScopeConfigInterface $appConfigScopeConfigInterface,
        Config $paymentModelConfig
    ) {

        $this->_appConfigScopeConfigInterface = $appConfigScopeConfigInterface;
        $this->_paymentModelConfig = $paymentModelConfig;
    }

    public function toOptionArray()
    {
        $payments = $this->_paymentModelConfig->getActiveMethods();
        $methods = array();
        foreach ($payments as $paymentCode => $paymentModel) {
            $paymentTitle = $this->_appConfigScopeConfigInterface
                ->getValue('payment/'.$paymentCode.'/title');
            $methods[$paymentCode] = array(
                'label' => $paymentTitle,
                'value' => $paymentCode
            );
        }
        return $methods;
    }
}

Here $_appConfigScopeConfigInterface is an object of Magento\Framework\App\Config\ScopeConfigInterface class.
$_paymentModelConfig is an object of Magento\Payment\Model\Config class.
and in toOptionArray() function we use a method: getActiveMethods() which returns model of all the active methods.
In return array we have all payment methods with their code and title.


text:
Q: How to serve html code from nginx and also ping upstream server for same request? We are using nginx running on one host as a proxy to a java servlet running in tomcat on another host.
What we want to do is say for a request http://a.xyz.com/a/b?q1=v1&q2=v2, we want to serve an HTML code to client from nginx and also ping an upstream server http://ipaddress[colon]port/a/b?q1=v1&q2=v2. The uri path and query params remains same while pinging upstream server.
I've figured how to do both the tasks individually but I'm unable to figure how to do both of them together for the same request.
This is how my conf file is looking so far.I have written two if conditions below. On using if condition 1 alone, I'm able to serve the HTML code. On using if condition 2 alone, I'm able to ping upstream server and in that case upstream server responds back with 200 OK which is sent to client via nginx. Could some one please help in achieving both of them together ? Nginx should serve the html code and release the client and then ping upstream server which will return back 200 OK to nginx which nginx can just swallow.
upstream u_server {
    server <ip_address>:8080;
}
server {
    listen 80;
    server_name a.xyz.com;
    # if condition 1
    if ($host = "a.xyz.com") {
         rewrite ^ /pqr.html last;
    }
    # if condition 2
    if ($host = "a.xyz.com") {
        set $upserver="u_server";
    }
    location /pqr.html {
            root /opt/mydir/html;
    }
    location / {
            proxy_pass http://$upserver;
    }
}

A: This сan be done by at least two methods (both with 3rd-party modules).
A) lua module.
upstream upserver {
    server <ip_address>:8080;
}

server {
    listen 80;
    server_name a.xyz.com;

    location / {

        root /opt/mydir/html;

        access_by_lua '
            local res = ngx.location.capture("/ping")
            return
        ';
    }

    location = /ping {
        proxy_pass http://upserver;
    }

}

B) auth_request module. Your ping backend MUST return "200 Ok" response ALWAYS, or the client will receive "403 Access denied" instead static file content.
upstream upserver {
    server <ip_address>:8080;
}

server {
    listen 80;
    server_name a.xyz.com;

    location / {
        root /opt/mydir/html;
        auth_request /ping;
    }

    location = /ping {
        proxy_pass http://upserver;
    }

}


text:
Q: How do I fix a 404 error using file_get_contents in PHP? When I run the following php file from a subfolder of htdocs, I get a 404 error: "The requested URL was not found on this server."
Let's call the subfolder "other".
When run the same file from htdocs folder, I get the error: "Fatal error: Class 'mysqli' not found in C:\xampp\htdocs\other\DBConnection.php on line 12 PHP."
I would like to be able to run the file successfully from the "other" folder because I will be using this to test multiple projects and websites.
I believe that the problem is that there is something missing from the file_get_contents("http://www.omdbapi.com/?t=Open+Water&y=&plot=full&r=json"); line.  ie. to tell this command to look in the htdocs folder where it will be able to access the internet or to authorize it to access the internet from the "other" file.
I have researched here and the web but cannot find the answer.  I have tried moving the connection code into the "OMDB query" file, but that produces an error similar to the 2nd error from above.  Can anyone help me fix this?
Windows 10
NetBeans 8.0.2
XAMPP
PHP 5.6.8
mySQL 5.6
Accessing OMDb.com api.
Code:
<?php
/*
 * File: OMDB query.php
 * Author:  Jim Stevens
 * Date: 08/14/2015
 * Description:  Imports records from OMDb and inserts results into local mySQL DB.
 */
require_once 'C:\xampp\htdocs\other\DBConnection.php';
$json = file_get_contents("http://www.omdbapi.com/?t=Open+Water&y=&plot=full&r=json");

// Decodes .json file, creates & populates an associative array.
$data = json_decode($json, TRUE);

// Extracts the array data.
$title = $data['Title'];
$year = $data['Year'];
$rated = $data['Rated'];
...more fields...

// Inserts extracted values into mySQL table 'myDB'.
$sql = "INSERT INTO movies.myDB(title, yr, rated, ...more fields...')";

if ($connection->query($sql) === TRUE) {
echo "New record created successfully";
}
...
?>

The DBConnection.php file is store in the "other" folder.  It successfully connects to "myDB" and works as expected:
Code:
<?php

/*
 * File: DBConnection.php
 * Author:  Jim Stevens
 * Date: 08/09/2015
 * Description:  Creates and manages myDB database connections.
 */

require_once 'config.php'; // The file with username, password, dbname, & dbhostname.

$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
    die($connection->connect_error);
}

//  The following works correctly but is a leftover from initial testing and will be removed eventually.
$query = "SELECT * FROM myDB";
$result = $connection->query($query);
if (!$result) {
    die($connection->error);
}
$rows = $result->num_rows;
for ($j=0; $j < $rows; ++$j) {
    $result->data_seek($j);
    $row = $result->fetch_array(MYSQLI_ASSOC);

    echo 'Title: ' . $row['title'] . '
';
    echo 'Year: '  . $row['yr']    . '
';
    echo 'Rated: ' . $row['rated'] . '
';
    echo 'Actors: '. $row['actors']. '
';
    echo 'Plot: '  . $row['plot']  . '

';
}
$result->close();
$connection->close();
?>

A: There's nothing wrong with your file_get_contents() function.
You're getting an error BEFORE the interpreter even touches this line.
As your error output said (and you really should trust it), the error is located at line 12 of your DBConnection.php file, so:
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

                  ^ here

You probably doesn't have Mysqli installed. Check the docs on how to install it on Windows, or check XAMPP's documentation.