text:
Q: Spark on Kubernetes, pods crashing abruptly Below is the scenario being tested,
Job :
Spark SQK job is written in Scala, and to run on 1TB TPCDS BENCHMARK DATA which is in parquet,snappy format and hive tables created on top of it.
Cluster manager :
Kubernetes
Spark sql configuration :
Set 1 :
spark.executor.heartbeatInterval 20s
spark.executor.cores 4
spark.driver.cores 4
spark.driver.memory 15g
spark.executor.memory 15g
spark.cores.max 220
spark.rpc.numRetries 5
spark.rpc.retry.wait 5
spark.network.timeout 1800
spark.sql.broadcastTimeout 1200
spark.sql.crossJoin.enabled true
spark.sql.starJoinOptimization true
spark.eventLog.enabled true
spark.eventLog.dir hdfs://namenodeHA/tmp/spark-history
spark.sql.codegen true
spark.kubernetes.allocation.batch.size 30

Set 2 :
spark.executor.heartbeatInterval 20s
spark.executor.cores 4
spark.driver.cores 4
spark.driver.memory 11g
spark.driver.memoryOverhead 4g
spark.executor.memory 11g
spark.executor.memoryOverhead 4g
spark.cores.max 220
spark.rpc.numRetries 5
spark.rpc.retry.wait 5
spark.network.timeout 1800
spark.sql.broadcastTimeout 1200
spark.sql.crossJoin.enabled true
spark.sql.starJoinOptimization true
spark.eventLog.enabled true
spark.eventLog.dir hdfs://namenodeHA/tmp/spark-history
spark.sql.codegen true
spark.kubernetes.allocation.batch.size 30

Kryoserialiser is being used and with spark.kryoserializer.buffer.mb value of 64mb.
50 executors are being spawned using spark.executor.instances=50 submit argument.
Issues Observed:
Spark SQL job is terminating abruptly and the drivers,executors are being killed randomly.
driver and executors pods gets killed suddenly the job fails.
Few different stack traces are found across different runs,
Stack Trace 1:
"2018-05-10 06:31:28 ERROR ContextCleaner:91 - Error cleaning broadcast 136
org.apache.spark.SparkException: Exception thrown in awaitResult:
        at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:205)"

File attached : StackTrace1.txt
Stack Trace 2:
"org.apache.spark.shuffle.FetchFailedException: Failed to connect to /192.178.1.105:38039^M
        at org.apache.spark.storage.ShuffleBlockFetcherIterator.throwFetchFailedException(ShuffleBlockFetcherIterator.scala:442)^M
        at org.apache.spark.storage.ShuffleBlockFetcherIterator.next(ShuffleBlockFetcherIterator.scala:418)"

File attached : StackTrace2.txt
Stack Trace 3:
"18/05/10 11:21:17 WARN KubernetesTaskSetManager: Lost task 3.0 in stage 48.0 (TID 16486, 192.178.1.35, executor 41): FetchFailed(null, shuffleId=29, mapId=-1, reduceId=3, message=^M
org.apache.spark.shuffle.MetadataFetchFailedException: Missing an output location for shuffle 29^M
        at org.apache.spark.MapOutputTracker$$anonfun$org$apache$spark$MapOutputTracker$$convertMapStatuses$2.apply(MapOutputTracker.scala:697)^M
        at org.apache.spark.MapOutputTracker$$anonfun$org$apache$spark$MapOutputTracker$$convertMapStatuses$2.apply(MapOutputTracker.scala:693)"

File attached : StackTrace3.txt
Stack Trace 4:
"ERROR KubernetesTaskSchedulerImpl: Lost executor 11 on 192.178.1.123: Executor lost for unknown reasons."

This is repeating constantly until the executors are dead completely without any stack traces.
Also, we see 18/05/11 07:23:23 INFO DAGScheduler: failed: Set()
what does this mean ? anything is wrong or it says failed set is empty that means no failure ?
Observations or changes tried out :
-  Monitored memory and CPU utilization across executors and none of them are hitting the limits.

*

*As per few readings and suggestions
spark.network.timeout was increased to 1800 from 600, but did not help.

*Also, driver and executor memory overhead was kept default in set 1 of the config and it was 0.1*15g=1.5gb.
Increased this value also, explicitly to 4gb and reduced driver and executor memory values to 11gb from 15gb as per set 2.
this did not yield any valuable results, same failures are being observed.
Spark SQL is being used to run the queries,
sample code lines :
val qresult = spark.sql(q)
    qresult.show()

No manual repartitioning is being done in the code.


text:
Q: Nuxt encode/decode URI with double colon My URLs have double colon on them.
I push a path to Nuxt router which has : as a part of it.
  export default {
  router: {
    extendRoutes (routes, resolve) {
      routes.push({
        name: 'custom',
        path: 'towns' + '(:[0-9].*)?/',
        component: resolve(__dirname, 'pages/404.vue')
      })
    }
  }
}

When I point to http://localhost:3000/towns:3 , for example, the : is translated as %3Aon the URL leading to this error message:
Expected "1" to match ":[0-9].*", but received "%3A2"

How to revert this to : ?
I tried encodeURI(), decodeURI(), encodeURIComponent() and decodeURIComponent() in vain.
A demo for the ones who wants to try: nuxt-extend-routes
Any suggestions are welcome

A: Vuex is using vue-router and vue-router is using path-to-regexp to parse router path configuration
It seems to me, that you are trying to use Unnamed Parameters which doesn't make sense because vue-router/vuex need the name of the parameter to pass it down to Vue component behind the route
Why don't just use named parameters ?
{
      path: '/towns:id(:\\d+)',
      name: 'Page 3',
      component: Page3
    }

Sure, result will be that $route.params.id value will be prefixed with : and all router-link params must be :XX instead of 'XX' but that's something you can deal with. vue-router (path-to-regexp) is using : to "mark" named path parameters ...there's no way around it
You can take a look at this sandbox. Its not Nuxt but I'm pretty sure it will work in Nuxt same way....
Update
Well it really doesn't work in Nuxt. It seems Nuxt is for some reason applying encodeURIComponent() on matched path segments and throws an error. It works when server-side rendering tho (it throws some error on client still)...

A: Firstly, I concur with Michal Levý's answer that there's a library bug here. The line throwing the error is here in the Nuxt source:
https://github.com/nuxt/nuxt.js/blob/112d836e6ebbf1bd0fbde3d7c006d4d88577aadf/packages/vue-app/template/utils.js#L523
You'll notice that a few lines up the segment is encoded, leading to : switching to %3A.
However, this line appears to have originated from path-to-regexp:
https://github.com/pillarjs/path-to-regexp/blob/v1.7.0/index.js#L212
It isn't trivial to fix this bug because the encoding is not simply 'wrong'. There's a lot of stuff going on here and by the time that line is reached the parameter values have been URL decoded from their original values. In the case of our unencoded : that causes problems but in other cases, such as matching %3A, the encoding would be required.
The handling of encoding within path-to-regexp is a delicate topic and we aren't helped by the old version being used. This also makes it more difficult to come up with a suitable workaround in your application.
So, let's see what we can do...
To start with, let's consider the path:
path: 'towns' + '(:[0-9].*)?/',

Bit odd to concatenate the strings like that, so I'm going to combine them:
path: 'towns(:[0-9].*)?/',

The / on the end isn't hurting but it seems to be unnecessary noise for the purposes of this question so I'm going to drop it.
On the flip side, not having a / at the start can cause major problems so I'm going to add one in.
The .* is suspicious too. Do you really mean match anything? e.g. The current route will match towns:3abcd. Is that really what you want? My suspicion is that you want to match just digits. e.g. towns:3214. For that I've used [0-9]+.
That leaves us with this:
path: '/towns(:[0-9]+)?',

Now, the : problem.
In general, route paths are used in both directions: to match/parse the URL and to build the URL. Your use of an unnamed parameter makes me wonder whether you only intend to use this route for matching purposes.
One option might be this:
path: '/towns:([0-9]+)',

By moving the : outside the parameter it dodges the encoding problem.
There are two problems with the code above:

*

*The colon/number suffix is no longer optional on the URL. i.e. It won't match the path /towns as the original route did. This can be solved by registering /towns as a separate route. I'm not aware of any other way to solve this problem with the available version of path-to-regexp.

*You won't be able to use it to build URLs, e.g. with nuxt-link.

If you need to be able to use it to build URLs too then you could use a named parameter instead:
path: '/towns::town([0-9]+)',

The :: part here is potentially confusing. The first : is treated literally whereas the second : is used as a prefix for the town parameter. You might then use that with nuxt-link like this:
<NuxtLink :to="{ name: 'custom', params: { town: 4 } }">
 ...
</NuxtLink>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django project folder doesn't push to gitlab When I try to push my Django project into my gitlab repository it, all the files gets pushed properly except for the project folder it gets uploaded with a remove icon and text next to it that looks like that: @ it 1080bae7

A: That looks like a submodule, or at least a gitlink (just a SHA1 entry)
Check if you see a .gitmodules in your repo.
If you don't see one, that means you have a nested git repo.
You can

*

*convert that folder (nested repo) into an actual submodule, or

*merge the nested repo into your main repo.

A: I renamed the folder, pushed it and renamed it again.


text:
Q: Sql LIKE не работает SELECT
  n.title,
  n.preview_image,
  n.date,
  news_type.name
FROM news n
  JOIN news_type
  ON n.id_news = news_type.id
WHERE news_type.name LIKE '%Аналитика%'

Этот запрос успешно работает в phpmyadmin в dbforge, но напрочь отказывается работать в с# коде. А именно ничего не возвращает. Если я удаляю WHERE news_type.name LIKE '%Аналитика%' то все работает. Я даже скопировал sql строку из дебага и вставил в phpmyadmin) Все равно не работает.
IDbCommand dbcmd = dbcon.CreateCommand();

            string sql = String.Format("SELECT " +
                         "n.title, " +
                         "n.preview_image," +
                         "n.date," +
                         "news_type.name " +
                         "FROM news n " +
                         "JOIN news_type " +
                         "ON n.id_news = news_type.id "+
                         "WHERE news_type.name LIKE '%{0}%'","Аналитика");

            dbcmd.CommandText = sql;
            IDataReader reader = dbcmd.ExecuteReader();
            while (reader.Read())
            {

            }

A: Для корректной работы вам скорее всего нужно:

*

*проверить что у таблицы в базе выставлен collation utf8_general_ci

*в connection string указан utf-8 в качестве charset:
"Server=localhost;Database=test;Uid=test;Pwd=test;Charset=utf8;"


text:
Q: XGBoost XGBRegressor predict with different dimensions than fit I am using the xgboost XGBRegressor to train on a data of 20 input dimensions:
    model = xgb.XGBRegressor(objective='reg:squarederror', n_estimators=20)
    model.fit(trainX, trainy, verbose=False)

trainX is 2000 x 19, and trainy is 2000 x 1.
In another word, I am using the 19 dimensions of trainX to predict the 20th dimension (the one dimension of trainy) as the training.
When I am making a prediction:
yhat = model.predict(x_input)

x_input has to be 19 dimensions.
I am wondering if there is a way to keep using the 19 dimensions to train prediction the 20th dimension. But during the prediction, x_input has only 4 dimensions to predict the 20th dimension. It is kinda of a transfer learning to different input dimension.
Does xgboost supports such a feature? I tried just to fill x_input's other dimensions to None, but that yields to terrible prediction results.

A: If I understand your question correctly, you are trying to train a model with 19 features, but then feed it only 1 feature to make a prediction.
That's not going to be possible. When you train a model, you are assuming that your data points are drawn from a probability distribution P(X,Y), where Y is your label and X is your features. If you try to change the dimensionality of X, it'll no longer belong to that distribution (at least intuitively, I am not a mathematician so, I cannot come up with a proof for this).
For instance, let's assume your data lies on a 3D cube. That means that you need three coordinate axes to represent a point on it. You cannot place a point using 2 dimensions without assuming the value of the remaining dimension.
You can assume the values of the features you try to drop, but they may not represent the data you originally trained on.

A: Fundamentally, you're training your model with a dense dataset (19/19 feature values), and are now wondering if you're allowed to make predictions with a sparse dataset (4/19 feature values).

Does xgboost supports such a feature?

Yes, it is technically possible with XGBoost, because XGBoost will treat the absent 15/19 feature values as missing. It will not be possible with some other ML framework (such as Scikit-Learn) that do not work with sparse input by default.
Alternatively, you can make your XGBoost model explicitly "missing-value-proof" by assembling a pipeline which contains feature imputation step(s).

I tried just to fill x_input's other dimensions to None, but that yields to terrible prediction results.

You should represent missing values as float("NaN") (not as None).


text:
Q: MySQL result ORDER BY reverse order? My query looks like ..
SELECT
        uid
    FROM
        user

    WHERE
        plz IN(24718,32326,32329,32328)

    ORDER BY
        FIELD(plz,24718,32326,32329,32328),
        uid DESC

Output:
97462
97407
97112
.
.
3037
891
15
91967
29360

I need to select / get first (97462) and last (29360) uid.
SELECT uid, MAX(uid), MIN(uid) does not work because of the ORDER BY.


text:
Q: count only males from a group I have this dataset.
data = pd.DataFrame({'sex':['male','female','female','male'],
                      'class':[1,2,3,2],
                      'smoking':[12,22,33,9]
})

   class     sex  smoking
0      1    male       12
1      2  female       22
2      3  female       33
3      2    male        9

I am grouping by sex and class:
smokers = data.groupby(['sex','class'])['smoking'].agg(sum)

sex     class
female  2        22
        3        33
male    1        12
        2         9

Now, I want to count only male smokers.
I know I can do :
male_smokers = data[data['sex'] == 'male'].groupby(['sex','class'])['smoking'].agg(sum)

but I want to be able to do it like:
male_smokers = smokers[smokers['sex'] == 'male'].count()

Is that possible?( right now I am receivig 'keyError' sex )

A: use loc to take a quick cross section.
smokers.loc['male'].sum()

or you can be more explicit with xs
smokers.xs('male', level='sex').sum()

or you could derive directly from data
data.query('sex == "male"').smoking.sum()


text:
Q: How do i call methods from JRuby into my Java code? Now i have a method in my Ruby script code and basicaly its returning a variable and this variable is pretty important to my code in java, So what i whant in my java code is to call this method that is in the Ruby script and the script returns a value and this value shall be assigned to my variable that i have..
Here is the code i have in ruby.. And i whant to call it in java and use what it returns and put it in a variable ..
def numberMethod
  number = 3
return number
end

If you know where i can read about it or if you know how to solve it please give me a comment or answear!
Thanks!

A: try reading RedBridge


text:
Q: HP DL380 G7 Disk swap to a HP DL380 G6 The HP DL380 G7 has 3 SAS disks in RAID 5 configuration. I need to change that server to another task and instead of make a clean install on the HP DL380 G6 can i just swap the 3 disks from HP DL380 G7 to the HP DL380 G6?
I expect some driver issues maybe on the OS itself because the processor is different.
They both use Smart Array P410i, if i power down the machines swap the disk by the same order
will the RAID 5 configuration remain and the OS will boot?

A: This should be no problem, as the RAID metadata is on the harddisks themselves.
You only need to make sure that both controllers use the same firmware (suggested using the last, so you might want to upgrade first).
Also see the Smart Array manual by HP, page 81-82: "Moving drives and arrays":
http://h20000.www2.hp.com/bc/docs/support/SupportManual/c01608507/c01608507.pdf

A: There are no issues making that switch. There won't be any driver issues. The DL380 G6 and the DL380 G7 have the same P410 RAID controller. It may make sense to run the HP Firmware DVD or HP Service Pack DVD to bring the server hardware up-to-date before or after making the switch, as there have been some major feature changes during the life of the components involved.
In general, the Smart Array RAID metadata is stored with the drives, so make sure you try to keep the disks in the same order. Watch the POST messages to ensure that the array is recognized before booting.


text:
Q: Select values between multiple parentheses in a string via SQL query I am using an Oracle database and I'm trying to select values between parentheses. Here is my table, which has ID and Roads as columns. I have read-only access to this database so I can only use SELECT:
ID   Roads
--   -----
1    #Chaussée de Waterloo (Ixelles)#
2    #Rue Reper-Vreven (Bruxelles)#
3    #Rue des Fraises (Anderlecht)#
4    #Chaussée de Roodebeek (Woluwe-Saint-Lambert)#
5    #Square Jean Absil (Etterbeek)#Avenue Hansen-Soulie (Etterbeek)#Avenue Le Marinel (Etterbeek)#

Basically, from the Roads column, I only want to keep the values between parentheses. As the final query has other tables in it, I want a select distinct. The desired output is:
 ID    Roads
------------------
  1      Ixelles
  2      Bruxelles
  3      Anderlecht
  4      Woluwe-Saint-Lambert
  5      Etterbeek, Etterbeek, Etterbeek

I tried the following query, which works fine when there is only one set of parentheses, but this doesn't work when there are several (like for ID 5), as it only gives back the values in the first set of parentheses:
select distinct substr(roads, instr(roads,'(') + 1, instr(roads,')') - instr(roads,'(') - 1) as roads
from table

Does anyone know where I'm going wrong?

A: One solution - based in part on the one referenced by przemo_pl:
SELECT SUBSTR( with_parentheses,2,length(with_parentheses)-2) between_parenthesis
FROM
  (select REGEXP_SUBSTR(dat, '\([^()]*\)+',1,level) AS with_parentheses
     from (select '#Square Jean Absil (Etterbeek)#Avenue Hansen-Soulie (Anderlecht)#Avenue Le Marinel (Ixelles)#' as dat from dual )
   connect by LEVEL <= ( LENGTH(dat) - LENGTH(REPLACE(dat, '(', '')))
  )

returns:
between_parenthesis
---------------------
"Etterbeek"
"Anderlecht"
"Ixelles"

If you want this re-assembled into a single row then that adds another wrinkle.

A: Please see my other post for a much simpler answer.  I am leaving this here as it is still an interesting approach and a lesson on how over-thinking a solution can get way too complicated and sometimes one must just step back and approach a problem a different way.  :-)
Ok, you need to loop through the rows and through the parentheses within the rows:
with tbl(ID, Roads) as (
  select 1, '#Chaussée de Waterloo (Ixelles)#' from dual
  union
  select 2, '#Rue Reper-Vreven (Bruxelles)#' from dual
  union
  select 3, '#Rue des Fraises (Anderlecht)#' from dual
  union
  select 4, '#Chaussée de Roodebeek (Woluwe-Saint-Lambert)#' from dual
  union
  select 5, '#Square Jean Absil (Etterbeek)#Avenue Hansen-Soulie (Etterbeek)#Avenue Le Marinel (Etterbeek)#' from dual
    )
    SELECT ID, Roads,
           COLUMN_VALUE AS match_nbr,
          REGEXP_SUBSTR( Roads ,'\(([^\)]*)\)', 1, COLUMN_VALUE, NULL, 1 ) AS match_value
   FROM   tbl,
          TABLE(
            CAST(
              MULTISET(
                SELECT LEVEL
                FROM   DUAL
                CONNECT BY LEVEL <= REGEXP_COUNT( Roads ,'\(' )
              ) AS SYS.ODCINUMBERLIST
            )
          );

Result:

See here for a similar post, which links to another post which provides more info.  I don't claim to understand it fully.  :-)
EDIT: Updated to get list of roads on one line using listagg( ):
SQL> with tbl(ID, Roads) as (
     select 1, '#Chaussée de Waterloo (Ixelles)#' from dual
     union
     select 2, '#Rue Reper-Vreven (Bruxelles)#' from dual
     union
     select 3, '#Rue des Fraises (Anderlecht)#' from dual
     union
     select 4, '#Chaussée de Roodebeek (Woluwe-Saint-Lambert)#' from dual
     union
     select 5, '#Square Jean Absil (Etterbeek)#Avenue Hansen-Soulie (Etterbeek)#Avenue Le Marinel (Etterbeek)#' from dual
       )
       select id,
       listagg(match_value, ', ') within group (order by id) road_list
       from (
       SELECT ID, Roads, COLUMN_VALUE AS match_nbr,
             REGEXP_SUBSTR( Roads ,'\(([^\)]*)\)', 1, COLUMN_VALUE, NULL, 1 ) AS match_value
      FROM   tbl,
             TABLE(
               CAST(
                 MULTISET(
                   SELECT LEVEL
                   FROM   DUAL
                   CONNECT BY LEVEL <= REGEXP_COUNT( Roads ,'\(' )
                 ) AS SYS.ODCINUMBERLIST
               )
             )
       )
       group by id
       order by id
       ;

        ID ROAD_LIST
---------- --------------------------------------------------
         1 Ixelles
         2 Bruxelles
         3 Anderlecht
         4 Woluwe-Saint-Lambert
         5 Etterbeek, Etterbeek, Etterbeek

SQL>

A: I am adding this as a new answer as it is so different from my previous one, which was a classic example of over-complicated thinking getting worse with each iteration and thus is still a good example of that!  lol  Sometimes you just need to feel when you are getting too complicated and don't be afraid to start over on a different tack!
Ok, check this out.  I went back to square one and studied the string for a pattern.  Whether one road or more (actually this design of multiple values in one column violates basic data modeling tenets and should be reworked but who hasn't had to deal with a crappy design that we have no control over?), each road is surrounded by pound signs.  My thought was to loop through the string using a regular expression, replacing the pattern of a pound sign through the closing parentheses with what is inside the parentheses.  Granted this leaves a pound sign at the end but we'll clean that up later.  Note that REGEXP_REPLACE will replace all occurrences of the pattern if found so by default loops through all roads and is WAY easier to maintain then a fugly mass of nested INSTR(), SUBSTR() :
SQL> with tbl(ID, Roads) as (
     select 1, '#Chaussée de Waterloo (Ixelles)#' from dual
     union
     select 2, '#Rue Reper-Vreven (Bruxelles)#' from dual
     union
     select 3, '#Rue des Fraises (Anderlecht)#' from dual
     union
     select 4, '#Chaussée de Roodebeek (Woluwe-Saint-Lambert)#' from dual
     union
     select 5, '#Square Jean Absil (Etterbeek)#Avenue Hansen-Soulie (Etterbeek)#Avenue Le Marinel (Etterbeek)#' from dual
   )
   select ID, rtrim(regexp_replace(Roads, '#.+?\((.+)\)', '\1, '), ', #') Roads
   from tbl;

        ID ROADS
---------- ----------------------------------------
         1 Ixelles
         2 Bruxelles
         3 Anderlecht
         4 Woluwe-Saint-Lambert
         5 Etterbeek, Etterbeek, Etterbeek

SQL>

The regular expression pattern explained:
#    Look for a literal pound sign
.    followed by any character
+    followed by one or more of the previous character (any character)
?    make the previous character optional (one or more any characters)
\(   a literal left paren
(    start remembered group 1
.    any character
+    one or more "any" characters
)    end remembered group 1
\)   followed by a literal closing right paren

If the above string is found, replace with the "replace-with" string:
\1       The first remembered group which is what is inside the parentheses.
,<space> followed by a comma and a space

Then its a tad quick and dirty, but just use RTRIM to remove the trailing comma-space-pound sign.  Wha-la!  Whew.


text:
Q: CSS : what is the difference between float: left or align: left? What is the difference between float: left and align: left if I want to keep HTML <div> elements in left position?
#left {
  align: left;
  background: pink;
}

vs
#left {
  float: left;
  background: pink;
}

A: See MDN which has a convenient list of all CSS properties.
float pushes the element it is applied to to the side and allows content that follows it to bubble up beside.

align is not a CSS property and will be ignored.

The type of document level layout it sounds like you want to do is usually best achieved with Flexbox or Grid.


text:
Q: Boolean expressions, visitor pattern and.. stack overflow Boolean expressions, visitor pattern and.. stack overflow
I have some kind of expression library than defines boolean expressions (something that can evaluate to true or false).
The code looks like this:
class ExpressionVisitor;

class Expression
{
public:
    virtual ~Expression() {}
    virtual void Accept(ExpressionVisitor &visitor) = 0;
    //.. other methods

}

class ConstantExpression : public Expression
{
public:
    ConstantExpression(bool val) : m_val(val){}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitConstantExpression(this); }
    bool GetValue() const { return m_val; }
private:
    bool m_val;
}

class NotExpression : public Expression
{
public:
    NotExpression(Expression *pInnerExpression) : m_pInnerExpression(pInnerExpression) {}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitNotExpression(this); }
    Expression* GetInnerExpression() const { return m_pInnerExpression; }
private:
    Expression *m_pInnerExpression;
}

class BinaryExpression : public Expression
{
public:
    AndExpression(Expression *pLeftExpression, Expression *pRightExpression) : m_pLeftExpression(pLeftExpression), m_pRightExpression(pRightExpression) {}
    Expression* GetLeftExpression() const { return m_pLeftExpression; }
    Expression* GetRightExpression() const { return m_pRightExpression; }
private:
    Expression m_pLeftExpression, m_pRightExpression;
}

class AndExpression : public BinaryExpression
{
public:
    AndExpression(Expression *pLeftExpression, Expression *pRightExpression) : BinaryExpression(pLeftExpression, pRightExpression) {}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitAndExpression(this); }
}

class OrExpression : public BinaryExpression
{
public:
    OrExpression(Expression *pLeftExpression, Expression *pRightExpression) : BinaryExpression(pLeftExpression, pRightExpression) {}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitOrExpression(this); }
}

class ExpressionVisitor
{
public:
    virtual ~ExpressionVisitor() {}
    void VisitConstantExpression(ConstantExpression*);
    void VisitNotExpression(NotExpression*);
    void VisitAndExpression(AndExpression*);
    void VisitOrExpression(OrExpression*);
}

Now to evalate an expression I have a concrete visitor:
class EvaluatorVisitor : public ExpressionVisitor
{
public:
    EvaluatorVisitor() : m_result(false){}

    bool GetResult() const { return m_result; }

    void VisitConstantExpression(ConstantExpression* pExpr)
    {
        m_result = pExpr->GetValue();
    }
    void VisitNotExpression(NotExpression* pExpr)
    {
        pExpr->GetInnerExpression()->Accept(this);
        auto innerResult = m_result;
        m_result = !innerResult;
    }
    void VisitAndExpression(AndExpression* pExpr)
    {
        pExpr->GetLeftExpression()->Accept(this);
        auto leftResult = m_result;
        pExpr->GetRightExpression()->Accept(this);
        auto rightResult = m_result;
        m_result = leftResult && rightResult;
    }
    void VisitOrExpression(OrExpression* pExpr)
    {
        pExpr->GetLeftExpression()->Accept(this);
        auto leftResult = m_result;
        pExpr->GetRightExpression()->Accept(this);
        auto rightResult = m_result;
        m_result = leftResult || rightResult;
    }

private:
    bool m_result;
}

And I use it like this:
EvaluatorVisitor evaluator;
Expression *pExpr = ...;
pExpr->Accept(&evaluator);
bool result = evaluator.GetResult();

Now for really large (deep) expressions that contains a lot of binary expressions, I get a stack overflow
because the EvaluatorVisitor is inherently recursive (because of the Accept() call).
How do I solve this (besides the obvious 'increase the stack size')?
EDIT1:
I'm pretty sure that I don't have an infinite recursion.
The code above is a simplified version of my code to show the problem.
The problem arises because between each Accept() call in the visitor each function create some state to produce a result.
I think the problem can be summarized using another example:
struct Node
{
    T Value;
    Node* Next;
}

T ComputeAllResult(Node *n)
{
    if (!n) return {};

    auto result1 = ProduceResult(n.Value); <--- state for this stack frame
    auto result2 = ComputeAllResult(n.Next);

    return CombineResults(result1, result2);
}

this will overflow the stack when the linked-list is really large AND the state is large (typeof(T))

A: This library is terrible. One of those made during OOP craze.
Instead of this crappy class-based approach that overflows the callstack - simply make a std::variant of all types that you use (I'd suggest enum but some of the types contain data instead of orders). You don't need the abstract class expression - just make a couple of simple switch cases to deal with the variations.
This way you can process everything in a while-loop instead of recursion. To do that you store your location in the expression via a std::stack of the variant plus current value. This way even expression with huge depth can be processed with ease as it is much harder to overflow std::stack.


text:
Q: Checkbox choice changed when listview expanded

I checked the first three checkbox on expandableListView. Why when I expand listview is the last CheckBox checked?
private ArrayList<Group_Items> setAllData() {

    String group_titles[] = {
            "Payment of Employer and employees contribution",
            "Monthly Return Filing in Form 5 and Declaration in form 2",
            "Monthly Return Filing in Form 10",
            "Monthly Return Filing in Form 12",
            "Statement of Recovery from contractor",
            "Annual Return in Form 6A",
            "Renewal of contribution card of an employee by filing Form 3 & 3A",
            "Submission of contribution card of employees leaving services" };

    String child_info[] = {
            "We have deployed secured web services framework in accordance with OASIS standards. Please refer the user manual (Secured Web service user manual) under the help section and do the necessary changes at your end to start consuming the same. Existing web services shall be discontinued w.e.f 1-Dec-2015.",
            "Return of employees qualifying for membership",
            "Return of members leaving the services during the month",
            "Statement of contribution",
            "Self Explnatory",
            "Consolidated annual contribution statement",
            "Self Explnatory",
            "Self Explnatory" };

    String dates[] = {
            "15th of Next Month + 5 Days Grace period",
            "15th of Next Month",
            "15th of Next Month",
            "25th of Next Month",
            "7th of Next Month",
            "30th April",
            "Within one month on the expiry of contribution card currancy to the commissioner",
            "20th of Next Month" };

    ArrayList<Group_Items> list = new ArrayList<Group_Items>();
    ArrayList<Child_Items> ch_list= new ArrayList<Child_Items>();
    ch = new Child_Items();
    int i=0;
    int size=1;

    for (String group_title : group_titles) {
        Group_Items gru = new Group_Items();

        gru.setName(group_title);

        ch_list = new ArrayList<Child_Items>();
        for (; i < size; i++) {
            Child_Items ch = new Child_Items();

            ch.setChild_title(child_info[i]);
            ch.setDd("Due Date:");
            ch.setDate(dates[i]);

            ch_list.add(ch);
        }

        gru.setItems(ch_list);
        list.add(gru);
        size=size+1;
    }
    return list;
}

I have created ExpandableListView with CheckBox beside each title and when I checked first three or four CheckBox from eight titles and first groupItem is expanded then automatically the last (8th) CheckBox is checked.

This is my custom adapter code

public class MyBaseExpandableListAdapter extends BaseExpandableListAdapter{
Context context;
ArrayList<Group_Items> group_al;

public MyBaseExpandableListAdapter(Context context,ArrayList<Group_Items> group_al) {
    this.context=context;
    this.group_al=group_al;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
    ArrayList<Child_Items> chList = group_al.get(groupPosition).getItems();

    return chList.get(childPosition);
}

@Override
public long getChildId(int groupPosition, int childPosition) {

    return childPosition;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
                         ViewGroup parent) {
    Child_Items ch = (Child_Items) getChild(groupPosition, childPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) context
                .getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.expandable_child_items, null);
    }
    TextView child = (TextView) convertView.findViewById(R.id.child);
    TextView dd = (TextView) convertView.findViewById(R.id.dd);
    TextView date= (TextView) convertView.findViewById(R.id.date);

    child.setText(ch.getChild_title().toString());
    dd.setText(ch.getDd().toString());
    date.setText(ch.getDate().toString());

    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    ArrayList<Child_Items> chList = group_al.get(groupPosition).getItems();

    return chList.size();
}

@Override
public Object getGroup(int groupPosition) {

    return group_al.get(groupPosition);
}

@Override
public int getGroupCount() {

    return group_al.size();
}

@Override
public long getGroupId(int groupPosition) {

    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    Group_Items gr = (Group_Items) getGroup(groupPosition);
    long group_id = getGroupId(groupPosition);

    if (convertView == null) {
        LayoutInflater inf = (LayoutInflater) context
                .getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = inf.inflate(R.layout.expandable_group_items, null);
    }

    TextView title = (TextView) convertView.findViewById(R.id.title);
    title.setText(gr.getName());
    CheckBox chk=(CheckBox) convertView.findViewById(R.id.chk);

    return convertView;
}

@Override
public boolean hasStableIds() {

    return true;
}

@Override
public boolean isChildSelectable(int arg0, int arg1) {

    return false;
}

}


text:
Q: Split Large csv File into multiple files depending on row value python Background
I have a large csv file in a specific format (NEM12) which is too big to work with. the file format is as below;

*

*The file always starts with 100

*Rows with a 200 represent the start of a new dataset

*Rows with 300 or 400 represent data for the dataset

*The File always ends with a 900

Example Below
100 NEM12
200 NMI INFO    INFO
300 20211001    0   0   0   0
400 20  20  F17
300 20211002    0   0   0   0
300 20211003    0   0   0   0
200 NMI INFO    INFO
300 20211001    0   0   0   0
300 20211002    0   0   0   0
300 20211003    0   0   0   0
300 20211004    0   0   0   0
300 20211005    0   0   0   0
…
200 NMI INFO    INFO
300 20211001    0   0   0   0
300 20211002    0   0   0   0
400 20  20  F17
300 20211003    0   0   0   0
300 20211004    0   0   0   0
900

What I'm Trying to do
I am trying to split the large file, into hundreds of smaller files. Each smaller file would contain a single 200 row with the corresponding 300 and 400 rows worth of values.
What I've tried
I've tried to read the file in via pandas, but due to its irregular shape, that hasn't worked.
I've successfully been able to iterate through lines via the below code, but it splits each value into its own column (i.e. instead of 200, it goes 2, 0, 0).
Any help be appreciated.
for line in open(test):
    if left(line, 3) == '200':
        try:
            with open(fname, 'a', newline='') as f_object:
                writer_object = writer(f_object)
                writer_object.writerow('900')
            f_object.close()
        except NameError:
            print('ignore')
        fname = str(line.replace(',', '').replace('\n', '')) + '.csv'
        with open(fname, 'w', newline='') as f_object:
            writer_object = writer(f_object)
            writer_object.writerow('100')
            writer_object.writerow(line)
    if left(line, 3) == '300' or left(line, 3) == '400':
        with open(fname, 'a', newline='') as f_object:
            writer_object = writer(f_object)
            writer_object.writerow(line)

A: Here is one approach.
fn = 'NEM12#000000000000001#CNRGYMDP#NEMMCO.csv'

cnt = 0
outfn = f'out_{cnt}.csv'

with open(fn, 'r') as f:
    for line in f:
        if line.startswith('100,'):  # don't write
            continue
        elif line.startswith('900'):  # don't write
            continue
        elif line.startswith('200,'):  # write detect start
            cnt += 1
            outfn = f'out_{cnt}.csv'  # new filename

        if line.startswith(('200,', '300,', '400,')):
            with open(outfn, 'a') as w:  # write
                w.write(f'{line}'):

The output will be out_1.csv, out_2.csv etc

A: Thanks to @Ferdy for the assistance,
Using the code you provided, as well as my original code, I was able to solve the issue
from csv import writer

for line in open(test):
    if line.startswith('200'):
        try:
            with open(fname, 'a', newline='') as f:
                w = writer(f)
                w.writerow(['900'])
            f.close()
        except NameError:
            print('ignore')
        flist = [str(line).split(",")[x] for x in [1, 3, 6, 7, 8]]
        fname = '_'.join(flist) + '.csv'
        print(fname)
        with open(fname, 'w', newline='') as f:
            w = writer(f)
            w.writerow(['100', 'NEM12', 'DATECREATED', 'MDYMDP', 'NAME'])
            w.writerow(str(line).split(","))
    if line.startswith(('300,', '400,')):
        with open(fname, 'a', newline='') as f:
            w = writer(f)
            w.writerow(str(line).split(","))


text:
Q: SQLite - too many levels of trigger recursion Estou recebendo o erro abaixo, quando tento fazer uma inserção no SQLite.

Error while executing SQL query on database 'BDTESTE': too many levels of trigger recursion

Criação da tabela
CREATE TABLE INSTANCES (
ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
NAME varchar(255) NOT NULL UNIQUE,
DESCRIPTION text,
CONFIG_TXT text,
EXTRA_TXT text,
CREATED varchar(50) NULL,
MODIFIED varchar(50) NULL
);

Criação da Trigger
CREATE TRIGGER INSTANCE_INSERT AFTER INSERT ON INSTANCES
BEGIN
UPDATE INSTANCES SET CREATED = DATETIME('NOW') WHERE ID = NEW.ID;
END;

Criação da Trigger - Update
CREATE TRIGGER INSTANCE_UPDATE AFTER UPDATE ON INSTANCES
BEGIN
UPDATE INSTANCES SET MODIFIED = DATETIME('NOW') WHERE ID = OLD.ID;
END;

Inserção
INSERT INTO INSTANCES (NAME, DESCRIPTION, CONFIG_TXT, EXTRA_TXT)
VALUES
('app02', 'Intancia de teste Windows', 'blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah', '');

A: O problema está na trigger de update. O update gerará o disparo da trigger, então você estará condenado a um laço infinito se não tratar corretamente.
Talvez o seguinte funcione (ignora atualizações que não setam informações novas):
CREATE TRIGGER INSTANCE_UPDATE AFTER UPDATE ON INSTANCES
BEGIN
    UPDATE INSTANCES SET MODIFIED = DATETIME('NOW')
    WHERE ID = OLD.ID AND MODIFIED != DATETIME('NOW');
END;

Isso vai evitar que você atualize de modo vacuoso uma linha qualquer.
Outra alternativa seria operar em views com triggers, depois eu coloco aqui. Exige um tanto a mais de código.


text:
Q: Cannot mount GFS2 filesystem on Raspberry Pi with DRBD I've been trying to setup a pair of Raspberry Pis with DRBD+GFS2, in a dual-primary configuration.
I've successfully got working:

*

*all packages installed

*DRBD userland packages built from source and working

*the 2 systems syncing an r0 device on /dev/drbd0
At this point I am having issues with getting the /dev/drbd0 device to mount on my /data dir. I get the error:
# mount -t gfs2 -o noatime,nodiratime,noquota /dev/drbd0 /data
mount: mount(2) failed: /data: No such file or directory

When I check my dmesg, I can see an error related to the lock_dlm protocol:
# dmesg | grep gfs
[159886.958163] gfs2: GFS2 installed
[159886.973908] gfs2: can't find protocol lock_dlm
[159925.272982] gfs2: can't find protocol lock_dlm
[160108.204231] gfs2: can't find protocol lock_dlm
[160139.555143] gfs2: can't find protocol lock_dlm
[161752.501161] gfs2: can't find protocol lock_dlm

The lock_dlm protocol is default when formatting GFS2:
mkfs.gfs2 -p lock_dlm -j 2 -t nfs:export /dev/drbd0

I've been doing some research on this, and as far as I can tell, the latest Rasbian kernel on the Raspberry Pi I'm using should support this and have the options enabled, notably CONFIG_GFS2_FS_LOCKING_DLM.
I'm having trouble verifying this, I'm not sure where to check.
I am not using custom compiled a kernel at this moment.
Can anyone advise how I can troubleshoot this?


text:
Q: Select an element with Javascript Hey Stackoverflow developers, I have this code

I want to be able to click on a div and for Javascript (not jQuery) to change the background color of only the clicked div. I've tried everything. How do I do it?

A: I think your div wasn't visible because it had no content and there for no height or width. I added height and width with css and then it worked.
 You could also add content as suggested above.

document.getElementsByClassName( 'test' )[0].addEventListener( 'click', function( event ){
 this.style.backgroundColor = 'red';
});
.test {
  width: 300px;
  height: 300px;
  background-color: blue;
}

A: You can use .querySelectorAll() to select all div elements with an id, iterate NodeList of div elements, attach click handler within a loop

A: div is ignored when there is no value/text. Your code is fine. Just add something to the div.

some value


text:
Q: How self works inside a class in python I need some help with the following code:
import logging

class TestLoggin:

    def __init__(self):
        # Create the Logger
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)

        # Create the Handler for logging data to a file
        logger_handler = logging.FileHandler('output.log')
        logger_handler.setLevel(logging.DEBUG)

        # Create a Formatter for formatting the log messages
        logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',  datefmt='%d-%m-%Y %H:%M:%S')

        # Add the Formatter to the Handler
        logger_handler.setFormatter(logger_formatter)

        # Add the Handler to the Logger
        self.logger.addHandler(logger_handler)

The logging module works fine when the setup is inside the __init__ method. But if I try to remove it to a new method, as below:
import logging

class TestLoggin:

    def __init__(self):
        self.logger = self.setup_logger(output_path)

    def example_using_logger(self):
        self.logger.error('it will raise an error')

    def setup_logger(self, output_path):
        # Create the Logger
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        # Create the Handler for logging data to a file
        logger_handler = logging.FileHandler(output_path)
        logger_handler.setLevel(logging.DEBUG)

        # Create a Formatter for formatting the log messages
        logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',  datefmt='%d-%m-%Y %H:%M:%S')

        # Add the Formatter to the Handler
        logger_handler.setFormatter(logger_formatter)

        # Add the Handler to the Logger
        return logger.addHandler(logger_handler)

And try to use the logger module self.logger.error('it will raise an error'), I got the following error: AttributeError: 'NoneType' object has no attribute 'error'.
I know the raised error is because logger is not recognized as part of the module, but as just a new variable. That is because I didn't grasp the fundamental of self. I'm new to Python, so I need some help here: How can I fix this, and the why of the problem. This last one would help me to understand a little more about the self.
Thanks in advance!

A: The issue is that logger.addHandler() isn't returning anything, so you're assigning None (returned from logger.addHandler()) to self.logger.
Try this:
# Add the Handler to the Logger
logger.addHandler(logger_handler)
return logger


text:
Q: Find Max(value) for each department using GROUP BY MYSQL I want to print the name of student in each department who has the highest gpa,
Students(stuID: String, stuName: String, gender: String,
        birthdate: Date, enterYear: Year, gpa: Float)
Departments(deptName: String, numPhDs: Integer)
Majors(deptName: String, stuID: String, degreeProgram: String,
        attendYear: Year, attendSemester: String)

My query looks like
SELECT S.StuName, M.DEPTNAME
FROM Students S NATURAL JOIN MAJORS M
WHERE S.GPA=(SELECT MAX(S2.GPA) FROM STUDENTS S2)
GROUP BY DEPTNAME;

I am only getting one student's name and their corresponding department (MATHEMATICS). How can I get the student with the highest GPA for each department? Where did I go wrong on my query?

A: You're missing the ON clause in your join.
The GROUP BY is not necessary, since you're selecting the MAX(GPA) entry for each student anyway. For this, the subquery needs to relate to the outer query.
SELECT S.StuName, M.DEPTNAME
FROM Students S NATURAL JOIN MAJORS M ON S.stuID = M.stuID
WHERE S.GPA=(SELECT MAX(S2.GPA) FROM STUDENTS S2 WHERE S2.StuName = S.StuName)
;

Here's a manual entry regarding your problem, where you can also see other ways of solving this.

A: You do need the GROUP BY if you want to SELECT the just the students with the highest GPA in each department. I added GPA to the statement for clarity.
SELECT S.StuName, S.gpa, M.DeptName
FROM Students S
JOIN Majors M ON S.StuID = M.StuID
WHERE S.gpa=(SELECT MAX(S2.gpa) FROM Students S2 WHERE S2.StuName = S.StuName) GROUP BY DeptName;


text:
Q: Writing a Code to Indent Code My goal is to write a C program that indents the C code given in char *input. The style of one level of indentation is given in the string const char *pad. I've wrote the following code, which works find in my head but doesn't in practice. There must be a mistake somewhere, but I can't find it.
Also, I can't figure out why Valgrind doesn't like the line containing while(...). Invalid read of size 1...
Any { increases the indentation level by one, and any } decreases the indentation level by one. No other indentation rules are applied. I assume there are no curly brackets inside string literals.
char *indent(char *input, const char *pad)
{
    int lenpad = strlen(pad);
    int inlen = strlen(input);
    char *output = malloc(inlen+lenpad*90); //Here I'm praying +lenpad*90 is enough
    int indent = 0;
    int i = 0;
    int j = 0;
    int ndx;
    int ondx;
    char current = 'a';
    int n;

    for(ndx=ondx=0; ndx<inlen; ndx++){
        current = input[ndx];
        if(current == '{') indent++;
        if(current == '\n'){
            output[ondx++] = '\n';
            n = ondx;
            while(input[n] != '\n' && input[n] != '\0'){ //Trying to check if the line to come has a curly bracket.
                if(input[n] == '}') //If it does, don't indent that line anymore.
                    indent--;
                n++;
            }
            for(j=0; j<indent; j++){
               for(i=0; i<lenpad; i++){
                output[ondx++] = pad[i];
                }
            }
        }
        else{
            output[ondx++] = current;
        }
    }
    free(input);
    output[ondx] = '\0';
    return output;
}

Instead of:
int main(void) {
    printf("asdfasdf\n");
    while (1)
    {
        while (2) {
            printf("printsomething\n");
        }
    }
}

My code gives:
int main(void) {
        printf("asdfasdf\n");
        while (1)
        {
            while (2) {
                printf("printsomething\n");
            }
            }
            }

A: In a code beautifier as the one you are trying to write, you must :

*

*swallow (do not output) all initial white spaces in a line (following a \n)

*replace them by the proper indentation computed as you do from the number of { and }
Implement it and ask here if you cannot make it work

A: Change your line
n = ondx;

to
n = ndx + 1;

You want n be the index of the next item in the input, not the output.


text:
Q: Windows 7 not using VPN DNS Server I'm connecting to my company VPN using OpenVPN.  My VPN network is 192.168.32.x and it resolves to the company network which uses 10.0.x.x.  My home network users 192.168.1.x.
When I connect, Open VPN adds the routes and installs the primary DNS, which is what is supposed to happen.  I've verified that this is the case by using ipconfig /all, and route print.
Ethernet adapter Local Area Connection 2:

Connection-specific DNS Suffix  . : xxxxx.net <-I've xxx'd the actual domain
Description . . . . . . . . . . . : TAP-Windows Adapter V9
Physical Address. . . . . . . . . : 00-FF-35-83-90-6D
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::cc01:9ac9:695f:87e2%32(Preferred)
IPv4 Address. . . . . . . . . . . : 192.168.32.6(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.252
Lease Obtained. . . . . . . . . . : Wednesday, April 23, 2014 9:08:21 PM
Lease Expires . . . . . . . . . . : Thursday, April 23, 2015 9:08:35 PM
Default Gateway . . . . . . . . . :
DHCP Server . . . . . . . . . . . : 192.168.32.5
DHCPv6 IAID . . . . . . . . . . . : 453050165
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-1A-E0-67-2F-A0-B3-CC-20-FC-87

DNS Servers . . . . . . . . . . . : xxx.x.xxx.xx <-I've xxx'd the actual public IP
Primary WINS Server . . . . . . . : 10.0.0.82
NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : lan
Description . . . . . . . . . . . : Atheros AR8151 PCI-E Gigabit Ethernet Con
troller (NDIS 6.20)
Physical Address. . . . . . . . . : A0-B3-CC-20-FC-87
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::e86f:e3f8:585b:2be6%13(Preferred)
IPv4 Address. . . . . . . . . . . : 192.168.1.116(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Lease Obtained. . . . . . . . . . : Wednesday, April 23, 2014 9:08:20 PM
Lease Expires . . . . . . . . . . : Thursday, April 24, 2014 9:08:20 PM
Default Gateway . . . . . . . . . : 192.168.1.1
DHCP Server . . . . . . . . . . . : 192.168.1.1
DHCPv6 IAID . . . . . . . . . . . : 295744460
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-1A-E0-67-2F-A0-B3-CC-20-FC-87

DNS Servers . . . . . . . . . . . : 192.168.1.1
NetBIOS over Tcpip. . . . . . . . : Enabled

Here is my route print:
C:\Users\Phil>route print
===========================================================================
Interface List
 32...00 ff 35 83 90 6d ......TAP-Windows Adapter V9
 17...c4 85 08 07 68 aa ......Microsoft Virtual WiFi Miniport Adapter #2
 16...c4 85 08 07 68 aa ......Microsoft Virtual WiFi Miniport Adapter
 15...c4 85 08 07 68 a9 ......Intel(R) Centrino(R) Advanced-N 6235
 13...a0 b3 cc 20 fc 87 ......Atheros AR8151 PCI-E Gigabit Ethernet Controller (
NDIS 6.20)
  1...........................Software Loopback Interface 1
 29...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 14...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
 27...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
 30...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
 28...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #5
 34...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #6
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      192.168.1.1    192.168.1.116     10
         10.0.0.0    255.255.255.0     192.168.32.5     192.168.32.6     30
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
      192.168.1.0    255.255.255.0         On-link     192.168.1.116    266
    192.168.1.116  255.255.255.255         On-link     192.168.1.116    266
    192.168.1.255  255.255.255.255         On-link     192.168.1.116    266
     192.168.32.1  255.255.255.255     192.168.32.5     192.168.32.6     30
     192.168.32.4  255.255.255.252         On-link      192.168.32.6    286
     192.168.32.6  255.255.255.255         On-link      192.168.32.6    286
     192.168.32.7  255.255.255.255         On-link      192.168.32.6    286
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     192.168.1.116    266
        224.0.0.0        240.0.0.0         On-link      192.168.32.6    286
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     192.168.1.116    266
  255.255.255.255  255.255.255.255         On-link      192.168.32.6    286
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
...
Persistent Routes:
  None

When I use nslookup (nslookup somehost.somedomain.com), I'm able to resolve the hostname on the VPN to the correct VPN IP address.  So this works as expected.
When I ping the same hostname (ping somehost.somedomain.com) I get an error: Ping request could not find host somehost.somedomain.com.  Please check the name and try again.  If I try to use any other services, the hostnames do not resolve.
Using NetMon, when I ping the VPN hostname, the only DNS server it checks is my home network DNS server (which is my home router, 192.168.1.1, running dd-wrt).  So it's ignoring the VPN dns server all together.
I'm kind of at a loss.  This configuration has worked for me for some time up until about 2 weeks ago, and is still working on other clients, so it's something local to my machine or my home network.  I'm not sure what changed, other than possibly my wireless router during that time.


text:
Q: Fitting Flex Image in Canvas How do I scale an Image in Flex to fit a Canvas?  My code follows:
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
         horizontalAlign="center"
         width="100" height="100"
         verticalGap="0" borderStyle="solid"
         initialize="onLoad()"
         horizontalScrollPolicy="off"
         verticalScrollPolicy="off">
    <mx:Canvas width="100%" height="100%" id="PictureBox" horizontalScrollPolicy="off"
         verticalScrollPolicy="off" />
    <mx:Label id="NameLabel" height="20%" width="100%"/>
    <mx:Script>
        <![CDATA[
        private function onLoad():void
        {
            var image:SmoothImage = data.thumbnail;

            image.percentHeight = 100;
            image.percentWidth = 100;
            this.PictureBox.addChild(image);

            var sizeString:String = new String();

            if ((data.fr.size / 1024) >= 512)
                sizeString = "" + int((data.fr.size / 1024 / 1024) * 100)/100 + " MB";
            else
                sizeString = "" + int((data.fr.size / 1024) * 100)/100 + " KB";

            this.NameLabel.text = data.name + " \n" + sizeString;

        }
        ]]>
        </mx:Script>
</mx:VBox>

I am trying to get the image:SmoothImage into PictureBox and scaling it down.
Note SmoothImage derives from Image.

A: you need to make sure you have set
image.scaleContent = true;
image.maintainAspectRatio = false;

That should scale the content to the size of the swf loader and distortin it so it fills the entire area of the Image component.
Here's a quick version of it working
     <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
         horizontalAlign="center"
         width="100" height="100"
         verticalGap="0" borderStyle="solid"
         initialize="onLoad()"
         horizontalScrollPolicy="off"
         verticalScrollPolicy="off">
    <mx:Canvas width="100%" height="100%" id="PictureBox" horizontalScrollPolicy="off"
         verticalScrollPolicy="off" />
    <mx:Label id="NameLabel" height="20%" width="100%"/>
    <mx:Script>
        <![CDATA[
            import mx.controls.Image;

        private function onLoad():void
        {
            var image : Image = new Image()
            image.source = "http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png";
            image.scaleContent = true;
            image.maintainAspectRatio =false;
            image.percentWidth = 100;
            image.percentHeight = 100;

            PictureBox.addChild(image);

        }
        ]]>
    </mx:Script>
</mx:VBox>


text:
Q: Should an AngularJS controller handle the business logic or the presentation logic? In the AngularJS documentation: https://docs.angularjs.org/guide/controller it says:

*

*Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.

Now, in the book I'm reading (AngularJS Up and Running O'Reily), which is a highly recommended book for learning AngularJS, it says (on page 17):

*

*Some of the more common responsibilities of a controller in an AngularJS application include:

*

*Presentation logic, such as how to display elements, which parts of the UI to show, how to style them, etc.

Isn't this exactly what the documentation not to use controllers for? What's recommended? (is it recommended that the controller handles the business or the presentation logic?).

A: Both can be handled using Angular JS, presentation layer and business logic layer. Suppose you have to point any action to UI with respect to run time changes that would be checked - business logic layer.
Suppose I have to upload a image/file now using angular's module I'll take the image/file and then it'll be sent for upload to server - let's say node js server- now angular can receive timely updates about upload progress and that would be shown on the presentation layer.
If you need more clarification please let me know.


text:
Q: Add variable into dictionary using loop condition I have created a dictionary like below;

*

*I want to use loop add 'Honors': 'No' if GPA is less than 3.5, otherwise 'Honors': 'Yes' into existing dictionary.
Student = {'A1': {'Student_Name': 'Jason','Class_Year': 1,'CGPA': 3.15},'A2': {'Student_Name': 'Henry','Class_Year': 2,'CGPA': 3.65}}
So the expected result will be like below;
Student = {'A1': {'Student_Name': 'Jason','Class_Year': 1,'CGPA': 3.15,'Honors': 'No'},'A2': {'Student_Name': 'Henry','Class_Year': 2,'CGPA': 3.65,'Honors': 'Yes'}}

*How i can use loop to calculate average GPA for my dictionary?

Thanks for your help.

A: PART1:
So for your example:
Student = {'A1': {'Student_Name': 'Jason','Class_Year': 1,'CGPA': 3.15},'A2': {'Student_Name': 'Henry','Class_Year': 2,'CGPA': 3.65}}

It boils down to just understand how to run through a dictionary:
for st, stuff in Student.items():
    if float(stuff['CGPA'])<3.5:
        Student[st]['Honors']='No'

    else:
        Student[st]['Honors']='Yes'

The final result would be:
{'A1': {'Student_Name': 'Jason', 'Class_Year': 1, 'CGPA': 3.15, 'Honors': 'No'}, 'A2': {'Student_Name': 'Henry', 'Class_Year': 2, 'CGPA': 3.65, 'Honors': 'Yes'}}

PART2:
Just small addition and that's all you need:
gpa_sum = 0
for st, stuff in Student.items():
    gpa_sum+=float(stuff['CGPA'])
    if float(stuff['CGPA'])<3.5:
        Student[st]['Honors']='No'

    else:
        Student[st]['Honors']='Yes'

print(f'The average GPA is :{gpa_sum/len(Student)}')

Output:
The average GPA is :3.4

A: In [26]: Student
Out[26]:
{'A1': {'Student_Name': 'Jason', 'Class_Year': 1, 'CGPA': 3.15},
 'A2': {'Student_Name': 'Henry', 'Class_Year': 2, 'CGPA': 3.65}}

In [27]: for s in Student:
    ...:     if Student[s]['CGPA'] >= 3.5:
    ...:         Student[s]['Honors'] = 'Yes'
    ...:     else:
    ...:         Student[s]['Honors'] = 'No'
    ...:

In [28]: Student
Out[28]:
{'A1': {'Student_Name': 'Jason',
  'Class_Year': 1,
  'CGPA': 3.15,
  'Honors': 'No'},
 'A2': {'Student_Name': 'Henry',
  'Class_Year': 2,
  'CGPA': 3.65,
  'Honors': 'Yes'}}

Average GPA
In [29]: sum([Student[s]['CGPA'] for s in Student]) / len([Student[s]['CGPA'] for s in Student])
Out[29]: 3.4

A: You need to iterate over the outer dictionary and then evaluate the inner dictionary Grade:

students = {
    'A1': {'Student_Name': 'Jason','Class_Year': 1,'CGPA': 3.15},
    'A2': {'Student_Name': 'Henry','Class_Year': 2,'CGPA': 3.65}
}

for student, info in students.items():
    if info["CGPA"] < 3.5:
        info["Honors"] = "No"
    else:
        info["Honors"] = "Yes"

By convention try to avoid Capital string in your variable.


text:
Q: Running Single TestFixtures from C# Code I know how to run complete NUnit assemblies from C# Code
TestPackage testPackage = new TestPackage(assemblyName);
RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
remoteTestRunner.Load(testPackage);
TestResult testResult = remoteTestRunner.Run(new NullListener(), TestFilter.Empty, false, LoggingThreshold.Error);

But how can I run single TestFixtures or even Single Tests?

A: Thanks to @Tony Hopkinson I found the solution.
I just had to create a class inheriting from TestFilter and overwrite the Match function in there.
public class SingleTestFilter : TestFilter
{
    private string testName;

    public SingleTestFilter(string TestName)
    {
        testName = TestName;
    }

    public override bool Match(ITest test)
    {
        return test.TestName.Name.Equals(testName);
    }
}

And then call the remoteTestRunner.Run with it as parameter.
remoteTestRunner.Run(new NullListener(), new SingleTestFilter("MyTest"), false, LoggingThreshold.Error);


text:
Q: Trouble creating SQL table? I learning how to use Oracle SQL and running into an error when I try to create a table. Here's the code:
CREATE TABLE Topic
(
     Topic_ID   NUMBER      NOT NULL,
     Topic_Name VARCHAR(20) NOT NULL,
     Topic_Desc VARCHAR(20) NOT NULL,

     CONSTRAINT Topic_PK PRIMARY KEY (Topic_ID)
);

The error is

ORA-00955: name is already used by an existing object.

I have reviewed my other tables several times and do not see any repeating names.


text:
Q: Why do C Sharp programs created in Visual Studio 2022 have no main method? I'm trying to create a program using OOP in C# with Visual Studio 2022. However normally when you create a class, for example in Java there is a main method that is used to run the program. But in C# and Visual Studio I don't have a main class all I see is:
When it's supposed to be this:

Is there a reason for this?

A: These are called top-level statements and is a relatively new language feature. The concept is explained well in the documentation: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/top-level-statements

A: You created your project with a top-level statement. If you want to view the Main() method, select "Do not use top-level statements" before creating the Visual Studio project.

A: "Starting in C# 9, you can omit the Main method, and write C# statements as if they were in the Main method"
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line


text:
Q: How to repeat an Asynchronous task periodically? I have an asynchronous task that i will like to repeat every 10 secs allowing focus to move back to the user interface in my Android application.
I have tried using java.util.Timer & TimerTask but the app crashes. It works within a for loop as you can see but i need to have this repeated every 10 secs.
do ...while loop also doesn't work even if i include a Thread.Sleep(10000), delay.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;
import android.os.AsyncTask;

public class MainActivity extends AppCompatActivity {

    TextView statusDisplay,display;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        display=(TextView)findViewById(R.id.display);
        display.setText("display");
        statusDisplay=(TextView)findViewById(R.id.statusDisplay);
        statusDisplay.setText("status");

        //I need to make this call every 10 secs

          new MyAsyncTask().execute("start");//Works fine as a single execution

    }

    //Our AsynTask
    // Specify your own types                              <params,progress,result>
    private class MyAsyncTask extends AsyncTask<String,Integer,Integer>
    {
        String status="Task being setup";
        int counter=0;

        //Step 1 that is executed for setting up our Asynchronous task
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            display.setText(status);
            statusDisplay.setText(String.valueOf(counter));
        }

        //Step 2 runs in the background and is only executed once
        //So put whatever computations including access to the Network inside this method
        //Do not make any calls to the UI from inside this method as its running in the background
        @Override
        protected Integer doInBackground(String[] params)
        {
            try{

                status=params[0];

                for(int i = 0;i<10;i++){
                    counter++;
                    status = "Task Running" + " " + String.valueOf(counter) + " " + "of" + " " + "10";
                    publishProgress(counter);//Calls onProgressUpdate
                    Thread.sleep(1000);
                }
            }
            catch(InterruptedException ex){

            }

            status = "Task completed";
            return counter;
        }

        //Step 3 called when we make a call to publishProgress in doInBackground
        @Override
        protected void onProgressUpdate(Integer[] values)
        {
            super.onProgressUpdate(values);

            display.setText(String.valueOf(values[0]));
            statusDisplay.setText(status);
        }

        //Step 4 Called after completion of doInBackground. Its return value is passed on to this method
        //Make final update changes to your UI at this step

        @Override
        protected void onPostExecute(Integer result)
        {
            super.onPostExecute(result);

            display.setText(String.valueOf(result));
            statusDisplay.setText(status);
        }
    }
}

A: You could use ScheduledExecutorService:
private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable yourTaskRunner = new Runnable() {
    public void run() { new MyAsyncTask().execute("start"); }
}
scheduler.scheduleAtFixedRate(yourTaskRunner, 0, 10, TimeUnits.SECONDS);

Which is one of the four ways described here.

A: This is what ive tried but not seeing the delay. It only reruns periodically

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;
import android.os.AsyncTask;
import android.os.Handler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    TextView statusDisplay,display;
    int x=0;
    Handler handler = new Handler();
    int stopcondition=0;
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        display=(TextView)findViewById(R.id.display);
        display.setText("display");
        statusDisplay=(TextView)findViewById(R.id.statusDisplay);
        statusDisplay.setText("status");

        //new MonitorSecurityStatus().execute("start");//This works fine

        //handler.post(rerunCode);//A)Runs periodically and terminates when stop-condition occurs but we don't see the 5 sec delay
        //handler.postDelayed(rerunCode,5000);//B) Executes rerunCode after 5 sec delay we don't need this

        scheduler.scheduleWithFixedDelay(rerunCode,0,5000, TimeUnit.MILLISECONDS);//C) Behaves same as A)
    }

private Runnable rerunCode = new Runnable() {
    @Override
    public void run()
    {
        //handler.postDelayed(this,5000);//A) We dont see the 5 secs delay behaves same as if this declaration was inside else-if
        stopcondition++;
        if(stopcondition==10){
            handler.removeCallbacks(this);
        }
        else if(stopcondition<10)
        {
            new MonitorSecurityStatus().execute("start");
            handler.postDelayed(this,5000);//A) We dont see the 5 secs delay
        }
    }
};


text:
Q: Cumulative count(*) in MySQL Imagine a SQL table votes, with two columns vote and time; vote is a string, time is a timestamp. I'd like to retrieve a "cumulative count" from the table. So, the table looks like this:
vote       | time
-----------+----------------
stuart     | 1443000000
stuart     | 1443000000
bryan      | 1443000000
stuart     | 1443000001
bryan      | 1443000001
bryan      | 1443000002
bryan      | 1443000002

so, "stuart" gets two votes in the first time interval and "bryan" gets one; they get one each in the second interval, and bryan gets two more in the third, and thus the output results I would like are these:
vote       | time         | cumulative total
-----------+--------------+-----------------
stuart     | 1443000000   | 2
bryan      | 1443000000   | 1
stuart     | 1443000001   | 3
bryan      | 1443000001   | 2
stuart     | 1443000002   | 3
bryan      | 1443000002   | 4

I'm not sure how to do this. Obviously, getting how many votes happened in each time interval is trivial (SELECT vote, time, COUNT(*) from table GROUP BY time, vote ORDER BY time, vote) but making a cumulative count seems harder. Is there a way to do so?
(I'm using MySQL, and am happy to use MySQL-specific functions here if useful.)

A: Using a correlated sub-query to do the counting:
select distinct vote, time, (select count(*) from table t2
                             where t2.vote = t1.vote
                               and t2.time <= t1.time)
from table t1

A: MySQL 8 introduced support for window functions, which are the perfect tool for cumulative sums. They will perform much better than the alternatives using correlated subqueries. Your desired query can be written as follows:
SELECT
  vote,
  time,
  sum(count(*)) OVER (PARTITION BY vote ORDER BY time)
FROM table
GROUP BY time, vote
ORDER BY time, vote

Note that the inner count(*) is an ordinary aggregate function, which is nested in the outer sum(...) OVER (...) window function. This is possible because aggregate functions are logically calculated before window functions.

A: Ok, if you really need that stuart | 1443000002 | 3 row then you can do this:
select distinct vote, time,
       (select count(*) from `table` t2
        where t2.vote = t1.vote
        and t2.time <= t1.time) `cumulative total`
from   (select distinct t3.vote vote, t4.time time
        from `table` t3, `table` t4) t1;

Here is the SQL Fiddle: http://sqlfiddle.com/#!9/960d6/11/0
What we need to do is make a table that contains EVERY combination of names and times (a join with no conditions) and then calculate the counts from the original table using all those combinations.
Thanks to @jarlh for the query in his answer - not having to start from scratch saved a bunch of time.


text:
Q: How should a typical .yml or .xml matrix look for OpenCV use I need to specify a matrix inside a file and then load it onto OpenCV as a Mat for further processing. How can the cols and lines be specified and where do elements go within the .xml or .yml file?, (for example element A(i,j) for i from 1 to m lines and for j from 1 to n cols.
In Matlab for example, this is done by loading a .dat file with just the numbers. What is confusing with OpenCV is that the .yml or .xml have some other scripts to them.

A: Read/Write any OpenCV data structure to or from .xml / .yaml file is very simple.
Before you write any content to such file you need to open it and at the end to close it. The XML/YAML data structure in OpenCV is FileStorage.
string filename = "I.xml";
FileStorage fs(filename, FileStorage::WRITE);

Mat R = Mat_<uchar >::eye (3, 3),

fs << "R" << R; // Write entire cv::Mat
fs["R"] >> R;   // Read entire cv::Mat

Check out this link File Input and Output using XML and YAML files


text:
Q: Combine multiple text files into one I'm trying to create a simple program that will combine multiple text files into one.  Basically, they are upgrade scripts.  So there's a "upgrade from" combo box and a "upgrade to" combo box.  I've managed to so far have the program read the directory to see what version scripts there are in the directory and sort them in ascending order.
What I'm having trouble with is combing the multiple files together.  I've managed to code it so it combines two scripts into one but it's hardcoded in.  I want the program to select the correct scripts without it being hardcoded.  Can anyone help?
This code is fine which populates the combo boxes based on the files listed in a directory and sorts them in ascending order:
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim counter As Integer
    Dim scriptcount As Integer
    counter = 0
    scriptcount = 0
    For Each file As String In System.IO.Directory.GetFiles(dir)
        counter = counter + 1
        version(counter) = System.IO.Path.GetFileNameWithoutExtension(file)
        versionfilepath(counter) = "C:\itcd\" + System.IO.Path.GetFileName(file)
    Next
    scriptcount = counter
    Do While counter >= 1
        cmbFrom.Items.Add(version(counter))
        cmbTo.Items.Add(version(counter))
        counter = counter - 1
    Loop
End Sub

This part I need help with.
Private Sub butGenerate_Click(sender As Object, e As EventArgs) Handles butGenerate.Click
    Dim counter As Integer
    Dim currentversionnumber As Integer
    Dim script1() As String
    Dim script2() as String
    Dim combinedLines As New List(Of String)

    script1 = System.IO.File.ReadAllLines("C:\itcd\scripts\519.sql")
    script2 = System.IO.File.ReadAllLines("C:\itcd\scripts\520.sql")

    For linePos As Integer = 0 To System.Math.Max(script1.Length, script2.Length) - 1
        If linePos < script1.Length Then combinedLines.Add(script1(linePos))
        If linePos < script2.Length Then combinedLines.Add(script2(linePos))
    Next
    System.IO.File.WriteAllLines("C:\itcd\scripts\new.sql", combinedLines.ToArray())
End Sub

I would like to create some sort of loop to if reads all the files that are selected then combine them into one file called new.sql without any hardcoding of the filepaths.  Any help is greatly appreciated.


text:
Q: Get courses from Garmin edge device and start navigation I am trying to achieve the functionality of getting the courses from the Garmin devices and whenever any course is clicked the navigation should start with a corresponding course
until now what I've done is, that the application always crashes, and menu items did not get inflated any help will be highly appreciated,
         var iterator = PersistedContent.getCourses;
         for (var i = 0; i < iterator.size(); i++) {
             var content = iterator.next(); // Get the next object in the iterator
             menu.addItem(
                 new MenuItem(
                     content.getName(),
                     "",
                     content.getId(), {}
                 )
             );
         }
     } catch (exception) {
         System.println("catch: " + exception);
     } finally {
         System.println("finally");
     }


text:
Q: Why i get NullPointerException here? This code used to work fine. I didnt change anything on it. And since ive made my class a fragment and insert swipe to another fragment it doesnt work.
i get the exception on this 'if':
    if (checkInput(tvWaybillDate.getText().toString(), etFlightNo.getText().toString(), etLitresObserved.getText().toString(), etTempObserved.getText().toString(), etDensity
                        .getText().toString(), strAirlinesId, strAirportsId, tvBouzer.getText().toString(), strLocationID, tvVCF.getText().toString(), tvLitres.getText().toString(), tvMT
                        .getText().toString(), tvA15.getText().toString()) == 13) {
.............
}

My fields here are indeed null or some "". But i check them in checkInput where the values are going.
checkInput:
private int checkInput(String waybillDate, String flightNo, String litresObserved, String tempObserved, String density, String airlineId, String airportId, String bouzer,
        String locationId, String vcf, String litres, String mt, String a15) {
    int count = 0;
    valueList = new ArrayList<String>();

    if (!waybillDate.equals("")) {
        count++;
    } else {
        valueList.add("Waybill Date");
    }

    if (!flightNo.equals("") && !flightNo.equals("0") && flightNo != null) {
        count++;
    } else {
        valueList.add("Flight No");
    }

    if (!litresObserved.equals("") && !litresObserved.equals("0") && litresObserved != null) {
        count++;
    } else {
        valueList.add("Litres Observed");
    }

    if (!tempObserved.equals("") && !tempObserved.equals("0") && tempObserved != null) {
        count++;
        } else {
            valueList.add("Temp Observed");
        }
    .
    .
    .
    .
    .
    .}

And here are the exceptions i get:
05-29 17:11:21.063: E/AndroidRuntime(10039): FATAL EXCEPTION: AsyncTask #3
05-29 17:11:21.063: E/AndroidRuntime(10039): java.lang.RuntimeException: An error occured while executing doInBackground()
05-29 17:11:21.063: E/AndroidRuntime(10039):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at java.lang.Thread.run(Thread.java:838)
05-29 17:11:21.063: E/AndroidRuntime(10039): Caused by: java.lang.NullPointerException
05-29 17:11:21.063: E/AndroidRuntime(10039):    at petrolina.pptaviation.NewWaybillPage1.sendWaybill(NewWaybillPage1.java:468)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at petrolina.pptaviation.NewWaybillPage1.access$28(NewWaybillPage1.java:465)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at petrolina.pptaviation.NewWaybillPage1$AsyncSend.doInBackground(NewWaybillPage1.java:1717)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at petrolina.pptaviation.NewWaybillPage1$AsyncSend.doInBackground(NewWaybillPage1.java:1)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-29 17:11:21.063: E/AndroidRuntime(10039):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-29 17:11:21.063: E/AndroidRuntime(10039):    ... 4 more

Any ideas whats wrong?

A: Are those views like tvWaybillDate initialized before if statement?
something like:
TextView tvWaybillDate = (TextView) findViewById(R.id.xxx);

where xxx is id from layout.
Also, in your function checkInput you should check if Strings are null before checking if they are empty. So, instead of:
if (!waybillDate.equals(""))

you should write
if (waybillDate != null && !waybillDate.equals(""))
for every string.

A: As far as why a TextView might be null if you "set" them in onCreate(), you may be trying to set them before the view itself is actually visible. You need to work with views when you are certain they are drawn in your view. For that, move your view sets to onStart, that is:
@Override
public void onStart(){
     super.onStart();
     tvWaybillDate.setText("some text");
     ...
}

This is based on the lifecycle of your activity http://developer.android.com/training/basics/activity-lifecycle/starting.html or fragment http://developer.android.com/guide/components/fragments.html
It is fine to try to pass a null as a parameter, but to try to convert a null to an object or a primitive is where the error is coming from. You need pass your views themselves, or the text character sequences they contain, to your method. For example:
 tvWaybillDate.getText().toString();

will throw a NPE if tvWaybillDate is null; you can't convert a null to a string. But passing
 checkInput(tvWaybillDate, ...

 ...

 public void checkInput(TextView tvWaybillDate, ...){
     int count = 0;
     if(tvWaybillDate != null) count++;
     ...
     return count;
 }

Do that, or something similar like passing the CharacterSequence tvWaybillDate.getText() for all of your views and you should be fine.


text:
Q: How to add a border on 1 or 2 sides, top, bottom, left, right of a rectangle Good day.
I'm not new in javascript and CSS, but I'm also not to good with SVG.
I've been battling with this issue.
I would like to know can you add borders to only one side of a rectangle.
e.g. Just the bottom or just the left.
I've been to these links while searching but not helping much.
Stroke left and right side of rect svg
How to set a stroke-width:1 on only certain sides of SVG shapes?
Thank you advance.
(",)
EDIT:
I hope this will be more clear to your understanding.
<g id="fdtElem307Group" fdtUngroupable="fdtUngroupable" fdtSelectable="fdtSelectable" fdtType="cursiveNotes" fdtTypeFormat="Converted" fdtFormatOptions="1" fdtFormat="Cursive" fdtTabIndex="24" fdtFieldName="Notes18" fdtResizable="fdtResizable" fdtfont-size="12" fdtRows="4">
<rect id="fdtElem303" fill="#ffffff" stroke="#000000" stroke-dasharray="5,2" stroke-width="1" x="114" y="968" width="240" height="24" vector-effect="non-scaling-stroke" fdtSelectable="fdtSelectable" fdtActualHeight="25" fdtActualWidth="241" fdtActualY="967" fdtActualX="113"></rect>
<rect id="fdtElem304" fill="#ffffff" stroke="#000000" stroke-dasharray="5,2" stroke-width="1" x="114" y="992" width="240" height="24" vector-effect="non-scaling-stroke" fdtSelectable="fdtSelectable" fdtActualHeight="25" fdtActualWidth="241" fdtActualY="991" fdtActualX="113"></rect>
<rect id="fdtElem305" fill="#ffffff" stroke="#000000" stroke-dasharray="5,2" stroke-width="1" x="114" y="1016" width="240" height="24" vector-effect="non-scaling-stroke" fdtSelectable="fdtSelectable" fdtActualHeight="25" fdtActualWidth="241" fdtActualY="1015" fdtActualX="113"></rect>
<rect id="fdtElem306" fill="#ffffff" stroke="#000000" stroke-dasharray="5,2" stroke-width="1" x="114" y="1040" width="240" height="24" vector-effect="non-scaling-stroke" fdtSelectable="fdtSelectable" fdtActualHeight="25" fdtActualWidth="241" fdtActualY="1039" fdtActualX="113"></rect>
</g>

A: You can use stroke-dasharray it's a bit of hack but it will work
Stroke on left -

<svg width="500" height="500">
<rect x="10" y="10" fill="orange" width="200" height="100" stroke-dasharray = "100 1000" stroke = "black" stroke-width="5" stroke-dashoffset ="-500"/></svg>
</svg>

Stroke on bottom

<svg width="500" height="500">
<rect x="10" y="10" fill="orange" width="200" height="100" stroke-dasharray = "200 1000" stroke = "black" stroke-width="5" stroke-dashoffset ="-300"/></svg>
</svg>


text:
Q: How to select records if all of the conditions satisfies in sql I have two tables stage and hier table
stage table:
POL_NO  AGENT   COMPANY_CODE
100      001        01
101      002        01
102      003        01
103      004        01

hier table:
PAY_REASON  PAY_CODE    AGENCY_CODE FINANCIAL_AGENT COMPANY_CODE    AGENT
S               BO           -             -            01           001
P               -            H                          01           001
-               -            B             -            01           001
S               BO           B            420           01           002
S               BO           -             -            01           002
S               BO           -             -            01           003
P               DD           U             -            01           003
-               -            B             -            01           003
-               -            B             -            01           004
-               -            B             -            01           004
-               -            -            420           01           004

the stage table will compare with the hier table based on (company_code and agent) to look if the below criteria is met in the hier table:
1.(pay_reason='S'and pay_code='BO') or agency_code in ('B','H','U')
2.Financial agent!=420

If any of the records in hier table does not match the criteria,then the company_code and agent won't show up in the expected result
expected result:
POL_NO  AGENT   COMPANY_CODE
100      001        01
102      003        01

A: You're almost there:
Select *
From stage s
where not exists (
select *
from hier h
where s.AGENT = h.AGENT
And s.COMPANY_CODE = h.COMPANY_CODE
and not(((pay_reason='S'and pay_code='BO') or agency_code in ('B','H','U'))
and Financial_agent!=420))

A: If I understand the conditions correctly, you seem to want:
select *
from stage s
where not exists (select 1
                  from hier h
                  where s.agent = h.agent and
                        s.company_code = h.company_code and
                        h.Financial_agent = 420 and
                        not ( (h.pay_reason = 'S' and pay_code = 'BO') or
                               h.agency_code in ('B', 'H', 'U')
                            )
                 );


text:
Q: Scroll to first selected Item in ASP.NET ListBox is there an easy way to scroll an ASP.Net ListBox automatically to the first selected Item?
The ListBox has SelectioMode="Multiple".
<asp:ListBox ID="LbSymptomCodesEdit" CausesValidation="true" ValidationGroup="VG_SAVE" Height="100%" Width="100%" runat="server"  SelectionMode="Multiple"></asp:ListBox>

The ListBox is in the EditItemTemplate of a FormView inside of an UpdatePanel.
jQuery is possible but it would be great if there would be an asp.net serverside(or Ajax) way to achieve this because i don't want to use more client scripts than really needed(and this is only a nice to have).

A: I don't believe there is any server side method to achieve what you want to. For example, the ASP.Net Page option "MaintainScrollPositionOnPostback" and the validator's "SetFocusOnError" properties all inject a small amount of javascript into a page to manage this.
If you really want to be able to scroll to the first selected item, I suggest you inherit from ListBox and add code that will inject javascript (or jQuery) to control this for you.


text:
Q: How to define rule in Stylelint which requires comma before newline in selectors? I'm setting up a .stylint file for my VS Code editor. Here is the example:
#main > div // there is no comma so stylint should throw an error here
div {
     ...
}

#main > div, // this is ok, no error here
div {
     ...
}

A: It is not possible to do this with the built-in rules in stylelint because the following is a valid selector:
#main > div
div {}

It's the equivalent of:
#main > div div {}

As the descendant combinator is any whitespace, including a newline.
However, you could write your own plugin for stylelint that enforces a comma at the end of each line of a selector, but the consequences of the plugin may be problematic unless you can guarantee that each selector within a selector list will occupy a single line.


text:
Q: (Swift) how to use Segue pass textField to TableViewCell under another ViewController? I wonder how to pass the textField to my customTableViweCell. Please, someone help me! enter image description here
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue" {
    let nextVC = segue.destination as! UINavigationController
    let dest = nextVC.topViewController as! ViewController
    let ind = sender as! customTableViewCell

    let nTxt = nameTxt.text?.description
    let pTxt = phoneTxt.text?.description
    let eTxt = emailTxt.text?.description
    let dTxt = dobTxt.text?.description
    ind.lb1 = "\(nTxt!)"
    ind.lb2 = "\(pTxt!)"
    ind.lb3 = "\(eTxt!)"
    ind.lb4 = "\(dTxt!)"
    }
}

A: segue.destination will contain the destination view controller.  You should cast it to your custom view controller that will be presented.  That view controller, should have properties defined that will be used to build that view.  You should set those properties in prepare so that when the destination view controller loads the view, those properties can be used to update the view components.  Here's an example.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue" {
        let dest = segue.destination as? YourCustomViewController
        dest?.customProp = someValue
    }
}


text:
Q: Domain Model Design across layers with Entity Framework We are in the process of designing a domain model for a new application.  The application consists of three layers.  Some of the entities are common to all layers, where as some of the other entities are unique to a specific layer.  A unique entity may contain a reference or be referenced by a shared entity.  The code related to the unique entities will also be unique to the layer.  We will be using Entity Framework 4.0 for persistence, with POCO's.
What are our options here with regard to:

*

*Should we split the domain up? If so this would mean we would not be able to have references to non shared entities within a shared entities, and as such would have to externalise business logic associated to this entity.

*If we share the domain across all layers, will we be able to define separate Entity Framework models for each layer as each layer has its own storage?

Any thoughts on either approach and best practices to follow would be appreciated.
Many Thanks

A: I would have ONE model project - with your POCOs. That project can then be referenced by any layer.


text:
Q: Filter an object based on values in an array I have an object that contains people's names and ages
{"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18}

and an array that provides a list of employee names
['John', 'Bob', 'Kate', 'Bill', 'Fred']

I would like to create a new object which contains only those people and their ages that appear in both the object and array.  So in this example the new object would contain
{"John":44,"Bob":43,"Kate":65,"Bill":18}

"Sarah":23 and Fred don't appear because they appear in only one of the above.
Can anyone advise on how to do this please?

A: You can use reduce to create the result and operator in to check if the key exists:

const obj = {"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18};
const keys = ['John', 'Bob', 'Kate', 'Bill', 'Fred'];

const result = keys.reduce((acc, el) => {
  if (el in obj) acc[el] = obj[el];
  return acc;
}, {});

console.log(result);

Another approach is to convert the object to an array, use filter and convert the result back:

const obj = {"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18};
const keys = ['John', 'Bob', 'Kate', 'Bill', 'Fred'];

const result = Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)));

console.log(result);

A: simply

const
  jso = { John: 44, Sarah: 23, Bob: 43, Kate: 65, Bill: 18 }
, arr = [ 'John', 'Bob', 'Kate', 'Bill', 'Fred' ]
, res = arr.reduce((r,a)=>(!!jso[a]?r[a]=jso[a]:'',r),{})
  ;
console.log(res)


text:
Q: Django - TypeError: not enough arguments for format string I'm trying to make a raw query on Django, here is what i tried:
Summary = myTable.objects.raw("SELECT FROM_UNIXTIME (unixtime, '%Y/%m/%d') AS ndate, count(id) AS query_count FROM myTable GROUP BY ndate ORDER BY query_count DESC")

The problem is that i keep getting the following error: TypeError: not enough arguments for format string
What is the problem here? If i execute this query on MYSQL, it will work. Any advice is appreciated!

A: From my point of view, '%Y/%m/%d' waiting until values are provided like you do in string.format() function. From docs:

Note that if you want to include literal percent signs in the query,
you have to double them in the case you are passing parameters:
cursor.execute("SELECT foo FROM bar WHERE baz = '30%'") # error
cursor.execute("SELECT foo FROM bar WHERE baz = '30%%'")


text:
Q: How to use Django Proxy Model given a django model object or queryset I have 2 questions regarding proxy from model,

*

*How to create a proxy object from model object?

*How to create a proxy QuerySet from model QuerySet?

For example, assume we have defined:
from django.contrib.auth.models import User

class MyProxyUser(User):
    class Meta:
        proxy = True

    def say_hello(self):
        return "Hello, {}".format(self.get_full_name())

One way to convert successfully is by re-querying the object, which is unnecessary.
# Retrieve from model Object.
# Assume: request is HttpRequest from authenticated user.
my_user = MyProxyUser.objects.get(pk=request.user.pk) # Hit Database
my_user.say_hello()

# Retrieve from model QuerySet.
# Assume: users = User.objects.all()
MyProxyUser.objects.filter(pk__in=users)

A: You just need to assign the model attribute of your queryset
users = User.objects.all()
users.model = MyProxyUser
users.first().say_hello()

Edit: For assigning proxy class to a django model object, try
    user = User.objects.all()
    user.__class__ = MyProxyUser

A: Adding to Ramast's answer, you can also build a function on your proxy model class to consistently do this for you:
class MyProxyUser(User):
...
    @staticmethod
    def from_user(user: UserManager):
        """ Get a PAUser classed instance from a User object.

        Useful for Signals and other Django defaults that send base User objects.
        """
        user.model = PAUser
        return user
...


text:
Q: How do I pass function parameter value into curly bracket? or property accessors(not sure what its call)? function encryption(ciphers, value, key, var_iv){
        if(ciphers == 'aes'){
            alert(CryptoJS.AES.encrypt(value, key, {iv:var_iv}));
            //^The var_iv above is not the value given to the parameter "561564848945123132123145564", instead its just "var_iv".
        }
    encryption("aes", "foo", "passcrytp", "561564848945123132123145564", "CBC", "ZeroPadding");

Can't seem to pass the function parameter inside the curly bracket for mome reason. Help please. (:
Im not tring to access object property, I'm trying to pass the value given to the function parameter, to inside curly brackets mention above.


text:
Q: Symfony2: Could I use 2 mechanism authentication for one firewall? I explain. I have 2 kernel: AdminKernel and ApiKernel.
The session for api use the session of admin (in api/config/config.yml):
framework:
    session:
        save_path: %kernel.root_dir%/../admin/cache/%kernel.environment%/sessions

The security.yml is common:
security:

    ...
    firewalls:
        ...
        admin_login:
            pattern:  ^/admin/user/login$
            security: false

        api:
            pattern: ^/api
            http_basic: ~

        admin:
            pattern:    ^/admin
            form_login:
                check_path: /admin/user/login_check
                login_path: /admin/user/login
                default_target_path: /admin
            logout:
                path:   /admin/user/logout
                target: /admin
            remember_me:
                key:      G>n[,O+^@F)j2_0^yFR_(|q<X~YtGD2:PV3zuktP0+/u*We]Ix$An X:m!#eeYEx
                lifetime: 3600
                path:     /
                domain:   ~ # Defaults to the current domain from $_SERVER
        ...

When I am on http://localhost/admin/list, a session is created.
And I want to use an ajax call to do some action with the URL https://localhost/api/update/page. The browser display the authentication box (http_basic) and it does not use the admin session.
My question is : How tell to API if the admin session exists, use it otherwise display the authentication box ?

A: From the Symfony2 Docs:
http://symfony.com/doc/current/book/security.html

*

*Multiple firewalls don't share security context If you're using multiple firewalls and you authenticate against one firewall, you will
  not be authenticated against any other firewalls automatically.
  Different firewalls are like different security systems. To do this
  you have to explicitly specify the same Firewall Context for different
  firewalls. But usually for most applications, having one main firewall
  is enough.


text:
Q: How to enable spell check in Notes? I want to enable the option Check spelling while typing in macOS Notes app.
This is usually done in:
Notes > Edit > Spelling and Grammar > Check spelling while typing.
But, I cannot. For some reason, this just does not work for Notes (for other applications it does).
Does anyone know how to force this setup in Notes via command line (Terminal)? or any other workaround?