问:
Best practice to query large number of ndb entities from datastore
I have run into an interesting limit with the App Engine datastore.  I am creating a handler to help us analyze some usage data on one of our production servers.  To perform the analysis I need to query and summarize 10,000+ entities pulled from the datastore.  The calculation isn't hard, it is just a histogram of items that pass a specific filter of the usage samples.  The problem I hit is that I can't get the data back from the datastore fast enough to do any processing before hitting the query deadline.

I have tried everything I can think of to chunk the query into parallel RPC calls to improve performance, but according to appstats I can't seem to get the queries to actually execute in parallel. No matter what method I try (see below) it always seems that the RPC's fall back to a waterfall of sequential next queries.

Note: the query and analysis code does work, it just runs to slowly because I can't get data quickly enough from the datastore.

Background

I don't have a live version I can share, but here is the basic model for the part of the system I am talking about:

```<code>class Session(ndb.Model):
   """ A tracked user session. (customer account (company), version, OS, etc) """
   data = ndb.JsonProperty(required = False, indexed = False)

class Sample(ndb.Model):
   name      = ndb.StringProperty  (required = True,  indexed = True)
   session   = ndb.KeyProperty     (required = True,  kind = Session)
   timestamp = ndb.DateTimeProperty(required = True,  indexed = True)
   tags      = ndb.StringProperty  (repeated = True,  indexed = True)
</code>```

You can think of the samples as times when a user makes use of a capability of a given name.  (ex: 'systemA.feature_x').  The tags are based upon customer details, system information, and the feature.  ex: ['winxp', '2.5.1', 'systemA', 'feature_x', 'premium_account']).  So the tags form a denormalized set of tokens that could be used to find samples of interest.

The analysis I am trying to do consists of taking a date range and asking how many times was a feature of set of features (perhaps all features) used per day (or per hour) per customer account (company, not per user).

So the input to the handler be something like:

Start Date

End Date

Tag(s)

Output would be:

```<code>[{
   'company_account': <string>,
   'counts': [
      {'timeperiod': <iso8601 date>, 'count': <int>}, ...
   ]
 }, ...
]
</code>```

Common Code for Queries

Here is some code in common for all queries.  The general structure of the handler is a simple get handler using webapp2 that sets up the query parameters, runs the query, processes the results, creates data to return.

```<code># -- Build Query Object --- #
query_opts = {}
query_opts['batch_size'] = 500   # Bring in large groups of entities

q = Sample.query()
q = q.order(Sample.timestamp)

# Tags
tag_args = [(Sample.tags == t) for t in tags]
q = q.filter(ndb.query.AND(*tag_args))

def handle_sample(sample):
   session_obj = sample.session.get()    # Usually found in local or memcache thanks to ndb
   count_key   = session_obj.data['customer']
   addCountForPeriod(count_key, sample.timestamp)
</code>```

Methods Tried

I have tried a variety of methods to try to pull data from the datastore as quickly as possible and in parallel.  The methods I have tried so far include:

A. Single Iteration

This is more of a simple base case to compare against the other methods.  I just build the query and iterate over all the items letting ndb do what it does to pull them one after the other.

```<code>q = q.filter(Sample.timestamp >= start_time)
q = q.filter(Sample.timestamp <= end_time)
q_iter = q.iter(**query_opts)

for sample in q_iter:
   handle_sample(sample)
</code>```

B. Large Fetch

The idea here was to see if I could do a single very large fetch.

```<code>q = q.filter(Sample.timestamp >= start_time)
q = q.filter(Sample.timestamp <= end_time)
samples = q.fetch(20000, **query_opts)

for sample in samples:
   handle_sample(sample)
</code>```

C. Async fetches across time range

The idea here is to recognize that the samples are fairly well spaced across time so I can create a set of independent queries that split the overall time region into chunks and try to run each of these in parallel using async:

```<code># split up timestamp space into 20 equal parts and async query each of them
ts_delta       = (end_time - start_time) / 20
cur_start_time = start_time
q_futures = []

for x in range(ts_intervals):
   cur_end_time = (cur_start_time + ts_delta)
   if x == (ts_intervals-1):    # Last one has to cover full range
      cur_end_time = end_time

   f = q.filter(Sample.timestamp >= cur_start_time,
                Sample.timestamp < cur_end_time).fetch_async(limit=None, **query_opts)
   q_futures.append(f)
   cur_start_time = cur_end_time

# Now loop through and collect results
for f in q_futures:
   samples = f.get_result()
   for sample in samples:
      handle_sample(sample)
</code>```

D. Async mapping

I tried this method because the documentation made it sound like ndb may exploit some parallelism automatically when using the Query.map_async method.

```<code>q = q.filter(Sample.timestamp >= start_time)
q = q.filter(Sample.timestamp <= end_time)

@ndb.tasklet
def process_sample(sample):
   period_ts   = getPeriodTimestamp(sample.timestamp)
   session_obj = yield sample.session.get_async()    # Lookup the session object from cache
   count_key   = session_obj.data['customer']
   addCountForPeriod(count_key, sample.timestamp)
   raise ndb.Return(None)

q_future = q.map_async(process_sample, **query_opts)
res = q_future.get_result()
</code>```

Outcome

I tested out one example query to collect overall response time and appstats traces.  The results are:

A. Single Iteration

real: 15.645s

This one goes sequentially through fetching batches one after the other and then retrieves every session from memcache.

B. Large Fetch

real: 12.12s

Effectively the same as option A but a bit faster for some reason.

C. Async fetches across time range

real: 15.251s

Appears to provide more parallelism at the start but seems to get slowed down by a sequence of calls to next during iteration of the results.  Also doesn't seem to be able to overlap the session memcache lookups with the pending queries.

D. Async mapping

real: 13.752s

This one is the hardest for me to understand.  It looks like it has q good deal of overlapping, but everything seems to stretch out in a waterfall instead of in parallel.

Recommendations

Based upon all this, what am I missing?  Am I just hitting a limit on App Engine or is there a better way to pull down large number of entities in parallel?

I am at a loss as to what to try next.  I thought about rewriting the client to make multiple requests to app engine in parallel but this seems pretty brute force.  I would really expect that app engine should be able to handle this use case so I am guessing there is something I am missing.

Update

In the end I found that option C was the best for my case. I was able to optimize it to complete in 6.1 seconds.  Still not perfect, but much better.

After getting advice from several people, I found that the following items were key to understand and keep in mind:

Multiple queries can run in parallel

Only 10 RPC's can be in flight at once

Try to denormalize to the point that there are no secondary queries

This type of task is better left to map reduce and task queues, not real-time queries

So what I did to make it faster:

I partitioned the query space from the beginning based upon time.  (note: the more equal the partitions are in terms of entities returned, the better)

I denormalized the data further to remove the need for the secondary session query

I made use of ndb async operations and wait_any() to overlap the queries with the processing

I am still not getting the performance I would expect or like, but it is workable for now.  I just wish their was a better way to pull large numbers of sequential entities into memory quickly in handlers.

答:
I have a similar problem and after working with Google support for few weeks I can confirm there is no magic solution at least as of December 2017.

tl;dr: One can expect throughput from 220 entities/second for standard SDK running on B1 instance up to 900 entities/second for a patched SDK running on a B8 instance.

The limitation is CPU related and changing the instanced type directly impacts performance. This is confirmed by similar results obtained on B4 and B4_1G instances

The best throughput I got for an Expando entity with about 30 fields is:

Standard GAE SDK

B1 instance: ~220 entities/second

B2 instance: ~250 entities/second

B4 instance: ~560 entities/second

B4_1G instance: ~560 entities/second

B8 instance: ~650 entities/second

Patched GAE SDK

B1 instance: ~420 entities/second

B8 instance: ~900 entities/second

For standard GAE SDK I tried various approaches including multi-threading but the best proved to be fetch_async with wait_any. Current NDB library already does a great job of using async and futures under the hood so any attempt to push that using threads only make it worse.

I found two interesting approaches to optimize this:

Matt Faus - Speeding up GAE Datastore Reads with Protobuf Projection

Evan Jones - Tracing a Python performance bug on App Engine

Matt Faus explains the problem very well:

GAE SDK provides an API for reading and writing objects derived from
  your classes to the datastore. This saves you the boring work of
  validating raw data returned from the datastore and repackaging it
  into an easy-to-use object. In particular, GAE uses protocol buffers
  to transmit raw data from the store to the frontend machine that needs
  it. The SDK is then responsible for decoding this format and returning
  a clean object to your code. This utility is great, but sometimes it
  does a bit more work than you would like. [...] Using our profiling
  tool, I discovered that fully 50% of the time spent fetching these
  entities was during the protobuf-to-python-object decoding phase. This
  means that the CPU on the frontend server was a bottleneck in these
  datastore reads!

Both approaches try to reduce the time spent doing protobuf to Python decoding by reducing the number of fields decoded.

I tried both approaches but I only succeed with Matt's. SDK internals changed since Evan published his solution. I had to change a bit the code published by Matt here, but is was pretty easy - if there is interest I can publish the final code.

For a regular Expando entity with about 30 fields I used Matt's solution to decode only couple fields and obtained a significant improvement.

In conclusion one need to plan accordingly and don't expect to be able to process much more than few hundreds entities in a "real-time" GAE request.

Body:
I have run into an interesting limit with the App Engine datastore.  I am creating a handler to help us analyze some usage data on one of our production servers.  To perform the analysis I need to query and summarize 10,000+ entities pulled from the datastore.  The calculation isn't hard, it is just a histogram of items that pass a specific filter of the usage samples.  The problem I hit is that I can't get the data back from the datastore fast enough to do any processing before hitting the query deadline.

I have tried everything I can think of to chunk the query into parallel RPC calls to improve performance, but according to appstats I can't seem to get the queries to actually execute in parallel. No matter what method I try (see below) it always seems that the RPC's fall back to a waterfall of sequential next queries.

Note: the query and analysis code does work, it just runs to slowly because I can't get data quickly enough from the datastore.

Background

I don't have a live version I can share, but here is the basic model for the part of the system I am talking about:

class Session(ndb.Model):
   """ A tracked user session. (customer account (company), version, OS, etc) """
   data = ndb.JsonProperty(required = False, indexed = False)

class Sample(ndb.Model):
   name      = ndb.StringProperty  (required = True,  indexed = True)
   session   = ndb.KeyProperty     (required = True,  kind = Session)
   timestamp = ndb.DateTimeProperty(required = True,  indexed = True)
   tags      = ndb.StringProperty  (repeated = True,  indexed = True)

You can think of the samples as times when a user makes use of a capability of a given name.  (ex: 'systemA.feature_x').  The tags are based upon customer details, system information, and the feature.  ex: ['winxp', '2.5.1', 'systemA', 'feature_x', 'premium_account']).  So the tags form a denormalized set of tokens that could be used to find samples of interest.

The analysis I am trying to do consists of taking a date range and asking how many times was a feature of set of features (perhaps all features) used per day (or per hour) per customer account (company, not per user).

So the input to the handler be something like:

Start Date

End Date

Tag(s)

Output would be:

[{
   'company_account': <string>,
   'counts': [
      {'timeperiod': <iso8601 date>, 'count': <int>}, ...
   ]
 }, ...
]

Common Code for Queries

Here is some code in common for all queries.  The general structure of the handler is a simple get handler using webapp2 that sets up the query parameters, runs the query, processes the results, creates data to return.

# -- Build Query Object --- #
query_opts = {}
query_opts['batch_size'] = 500   # Bring in large groups of entities

q = Sample.query()
q = q.order(Sample.timestamp)

# Tags
tag_args = [(Sample.tags == t) for t in tags]
q = q.filter(ndb.query.AND(*tag_args))

def handle_sample(sample):
   session_obj = sample.session.get()    # Usually found in local or memcache thanks to ndb
   count_key   = session_obj.data['customer']
   addCountForPeriod(count_key, sample.timestamp)

Methods Tried

I have tried a variety of methods to try to pull data from the datastore as quickly as possible and in parallel.  The methods I have tried so far include:

A. Single Iteration

This is more of a simple base case to compare against the other methods.  I just build the query and iterate over all the items letting ndb do what it does to pull them one after the other.

q = q.filter(Sample.timestamp >= start_time)
q = q.filter(Sample.timestamp <= end_time)
q_iter = q.iter(**query_opts)

for sample in q_iter:
   handle_sample(sample)

B. Large Fetch

The idea here was to see if I could do a single very large fetch.

q = q.filter(Sample.timestamp >= start_time)
q = q.filter(Sample.timestamp <= end_time)
samples = q.fetch(20000, **query_opts)

for sample in samples:
   handle_sample(sample)

C. Async fetches across time range

The idea here is to recognize that the samples are fairly well spaced across time so I can create a set of independent queries that split the overall time region into chunks and try to run each of these in parallel using async:

# split up timestamp space into 20 equal parts and async query each of them
ts_delta       = (end_time - start_time) / 20
cur_start_time = start_time
q_futures = []

for x in range(ts_intervals):
   cur_end_time = (cur_start_time + ts_delta)
   if x == (ts_intervals-1):    # Last one has to cover full range
      cur_end_time = end_time

   f = q.filter(Sample.timestamp >= cur_start_time,
                Sample.timestamp < cur_end_time).fetch_async(limit=None, **query_opts)
   q_futures.append(f)
   cur_start_time = cur_end_time

# Now loop through and collect results
for f in q_futures:
   samples = f.get_result()
   for sample in samples:
      handle_sample(sample)

D. Async mapping

I tried this method because the documentation made it sound like ndb may exploit some parallelism automatically when using the Query.map_async method.

q = q.filter(Sample.timestamp >= start_time)
q = q.filter(Sample.timestamp <= end_time)

@ndb.tasklet
def process_sample(sample):
   period_ts   = getPeriodTimestamp(sample.timestamp)
   session_obj = yield sample.session.get_async()    # Lookup the session object from cache
   count_key   = session_obj.data['customer']
   addCountForPeriod(count_key, sample.timestamp)
   raise ndb.Return(None)

q_future = q.map_async(process_sample, **query_opts)
res = q_future.get_result()

Outcome

I tested out one example query to collect overall response time and appstats traces.  The results are:

A. Single Iteration

real: 15.645s

This one goes sequentially through fetching batches one after the other and then retrieves every session from memcache.

B. Large Fetch

real: 12.12s

Effectively the same as option A but a bit faster for some reason.

C. Async fetches across time range

real: 15.251s

Appears to provide more parallelism at the start but seems to get slowed down by a sequence of calls to next during iteration of the results.  Also doesn't seem to be able to overlap the session memcache lookups with the pending queries.

D. Async mapping

real: 13.752s

This one is the hardest for me to understand.  It looks like it has q good deal of overlapping, but everything seems to stretch out in a waterfall instead of in parallel.

Recommendations

Based upon all this, what am I missing?  Am I just hitting a limit on App Engine or is there a better way to pull down large number of entities in parallel?

I am at a loss as to what to try next.  I thought about rewriting the client to make multiple requests to app engine in parallel but this seems pretty brute force.  I would really expect that app engine should be able to handle this use case so I am guessing there is something I am missing.

Update

In the end I found that option C was the best for my case. I was able to optimize it to complete in 6.1 seconds.  Still not perfect, but much better.

After getting advice from several people, I found that the following items were key to understand and keep in mind:

Multiple queries can run in parallel

Only 10 RPC's can be in flight at once

Try to denormalize to the point that there are no secondary queries

This type of task is better left to map reduce and task queues, not real-time queries

So what I did to make it faster:

I partitioned the query space from the beginning based upon time.  (note: the more equal the partitions are in terms of entities returned, the better)

I denormalized the data further to remove the need for the secondary session query

I made use of ndb async operations and wait_any() to overlap the queries with the processing

I am still not getting the performance I would expect or like, but it is workable for now.  I just wish their was a better way to pull large numbers of sequential entities into memory quickly in handlers.


来源: stackexchange

问:
What's underneath Array.new(10, &:next) in ruby
I was looking that in Ruby there are a lot of ways to declare arrays objects like:

```<code>[1,2,3]
Array.new(3){|i| i+1}
</code>```

Even with more trickier ways like:

```<code>Array.new(3, &1.method(:+))
</code>```

Where the &1.method(:+) means that the object 1 (reference by value) is responding to the method + directly referenced, so every time (3 times in this case) the array is executing the block, the object increments by 1. I would appreciate any correction if I'm wrong on my analysis here.

So, passing that, there is this case that I'm not completely following:

```<code>Array.new(3, &:next)
</code>```

The question is:

What's the & doing in this case? I can guess that is a reference to some value directly but I don't know which one exactly. And after the &, how the :next is acting in this case.

Beforehand, I really appreciate your help. I'm getting the grasp of Ruby and I'm liking it even more!

答:
& is a shortcut for Symbol#to_proc in this case. A corresponding full version is:

```<code>Array.new(3) { |i| i.next }
#=> [1, 2, 3]
</code>```

The instance below can help you understanding how does it work:

```<code>Array.new(3, &(:next.to_proc))
#=> [1, 2, 3]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was looking that in Ruby there are a lot of ways to declare arrays objects like:

[1,2,3]
Array.new(3){|i| i+1}

Even with more trickier ways like:

Array.new(3, &1.method(:+))

Where the &1.method(:+) means that the object 1 (reference by value) is responding to the method + directly referenced, so every time (3 times in this case) the array is executing the block, the object increments by 1. I would appreciate any correction if I'm wrong on my analysis here.

So, passing that, there is this case that I'm not completely following:

Array.new(3, &:next)

The question is:

What's the & doing in this case? I can guess that is a reference to some value directly but I don't know which one exactly. And after the &, how the :next is acting in this case.

Beforehand, I really appreciate your help. I'm getting the grasp of Ruby and I'm liking it even more!

Body:
& is a shortcut for Symbol#to_proc in this case. A corresponding full version is:

Array.new(3) { |i| i.next }
#=> [1, 2, 3]

The instance below can help you understanding how does it work:

Array.new(3, &(:next.to_proc))
#=> [1, 2, 3]


问:
jquery colorbox looks wrong the first time opened and then fine after that
I'm trying to dynamically (using ajax) get some content and create a modal (using the colorbox plugin) with it. The problem is that the content has some images in it. I think that the modal doesn't count them in it's height or width calculation or something. So if you close the modal and then open it it looks fine. (The first time you open it, it has the scroll bars to access the rest of the modal).

Ideas?

答:
you can resize the box on complete action:</p>

```<code>jQuery('.colorbox').colorbox({
        onComplete: function () {
            $(this).colorbox.resize();
        }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
you can resize the box on complete action:

jQuery('.colorbox').colorbox({
        onComplete: function () {
            $(this).colorbox.resize();
        }
});


问:
How to execute function over each element in RDD and join outputs?
I'm very new to Spark and I am using Spark 1.6.0.

I have an RDD which is: RDD[Array[Array[String], Long]]

I would like to run each element in the RDD through a function which takes Array[Array[String], Long] as input and returns a ListBuffer[Array[Int]] as output.

The computations of each element in the RDD can be done in parallel, they are not dependent on each other. However, once all of the elements of the RDD have been run through the function I would like to join all of the ListBuffer[Array[Int]] outputs together, into one single ListBuffer[Array[Int]] (order here is not relevant either, but they should all be in the same datastructure).

What would be the best way to do so? I could foreach the RDD and run them through the function, however then I'm not sure how to handle the output and thereafter perform this merge at the driver.

This seems to be possible with Accumulators. The function as mentioned earlier is not just a single line of code, it is something like 20+ lines. So if we have this function:

```<code>def func(data: Array[Array[String], Long]): ListBuffer[Array[Int]] {
    // create ListBuffer
    // iterate over data
        // do some operations on an element in data
        // add some entry to the ListBuffer
    // add the ListBuffer to the Accumulator or return ListBuffer?
}
</code>```

How could I wrap this all up together? Can I do something like:

```<code>// create Accumulator
// RDD.foreach() // call the func and pass Accumulator as argument?
</code>```

Or:

```<code>val accum = // a ListBuffer[Array[Int]] accumulator
RDD.foreach(x => accum.add(func(x)))
</code>```

答:
TL;DR Use map followed by collect if you need the results on the driver.

map applies a function to every element in an RDD.

map[U](f: (T) ⇒ U)(implicit arg0: ClassTag[U]): RDD[U] Return a new RDD by applying a function to all elements of this RDD.

In your case, T is Array[Array[String], Long] with U being ListBuffer[Array[Int]]. If you have a function f that does the transformation of elements of type T, map is your friend.

Body:
I'm very new to Spark and I am using Spark 1.6.0.

I have an RDD which is: RDD[Array[Array[String], Long]]

I would like to run each element in the RDD through a function which takes Array[Array[String], Long] as input and returns a ListBuffer[Array[Int]] as output.

The computations of each element in the RDD can be done in parallel, they are not dependent on each other. However, once all of the elements of the RDD have been run through the function I would like to join all of the ListBuffer[Array[Int]] outputs together, into one single ListBuffer[Array[Int]] (order here is not relevant either, but they should all be in the same datastructure).

What would be the best way to do so? I could foreach the RDD and run them through the function, however then I'm not sure how to handle the output and thereafter perform this merge at the driver.

This seems to be possible with Accumulators. The function as mentioned earlier is not just a single line of code, it is something like 20+ lines. So if we have this function:

def func(data: Array[Array[String], Long]): ListBuffer[Array[Int]] {
    // create ListBuffer
    // iterate over data
        // do some operations on an element in data
        // add some entry to the ListBuffer
    // add the ListBuffer to the Accumulator or return ListBuffer?
}

How could I wrap this all up together? Can I do something like:

// create Accumulator
// RDD.foreach() // call the func and pass Accumulator as argument?

Or:

val accum = // a ListBuffer[Array[Int]] accumulator
RDD.foreach(x => accum.add(func(x)))


问:
how to set prefix to GeneratedDatabaseHolder.java class in dbflow in android studio 3
in android studio 2.3.3 when useing dbflow in a module you can add a prefix to GeneratedDatabaseHolder class like this

```<code>apt {
     arguments {
          targetModuleName 'PreFixTitle'
     }
}
</code>```

but in android studio 3 we cannot use apt right so how can I add prefix to that class ?

答:
I have this problem today!
I solve this problem in this way:

```<code>android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
        // ...
        android.compileOptions.sourceCompatibility 1.8
        android.compileOptions.targetCompatibility 1.8
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [ targetModuleName : 'Ship' ]
            }
        }

    }
}
</code>```

my project Build.gradle:

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
    allprojects {
        repositories {
            google()
            jcenter()
            maven { url "https://jitpack.io" }
        }
    }
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
}
</code>```

my demo

Body:
in android studio 2.3.3 when useing dbflow in a module you can add a prefix to GeneratedDatabaseHolder class like this

apt {
     arguments {
          targetModuleName 'PreFixTitle'
     }
}

but in android studio 3 we cannot use apt right so how can I add prefix to that class ?

Body:
I have this problem today!
I solve this problem in this way:

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
        // ...
        android.compileOptions.sourceCompatibility 1.8
        android.compileOptions.targetCompatibility 1.8
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [ targetModuleName : 'Ship' ]
            }
        }

    }
}

my project Build.gradle:

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
    allprojects {
        repositories {
            google()
            jcenter()
            maven { url "https://jitpack.io" }
        }
    }
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
}

my demo


问:
cannot call the function in child from the parent
I am developing a game using C++ in Qt creator.

I can call the fuctions of the child class in main without an issue, but when I try to call a function in child class from my parent class, the program unexpectedly closes.

I have declared all the public attributes in the .h file of the parent class. T tried removing those attributes and placing them inside the .h file of the child class, then it works fine. But W want to keep them in the parent class and access those from the child class.

Please help get this to work, I tried several times but I could not figure it out.

.h file of parent class:

```<code>class Game:public QGraphicsView,public home{

Q_OBJECT

public:

Game(QWidget* parent=0);

virtual ~Game(){}

void createBlockCol(double x);
void creatBlockGrid();
virtual void setbackground();

QPushButton *btn2;
QPushButton *btn3;
QPushButton *btn4;
QGraphicsScene* scene;
QGraphicsScene *scene2;
QGraphicsView* view;
QPushButton *btn;
QPushButton *btn1;
QGraphicsProxyWidget *pr;
QGraphicsProxyWidget *pr1;

QGraphicsProxyWidget *pr2;
QGraphicsProxyWidget *pr3;
QGraphicsProxyWidget *pr4;
QGraphicsPixmapItem* item1;
QGraphicsPixmapItem* item;

private slots:
void start();
</code>```

This is .cpp class of parent

```<code>Game::Game(QWidget *parent): QGraphicsView(parent){
scene = new QGraphicsScene(0,0,466,600);
setScene(scene);

}

void Game::setbackground(){

scene2 = new QGraphicsScene(0,0,400,600);
QGraphicsView* view = new QGraphicsView(scene2);
item = new QGraphicsPixmapItem(QPixmap(":/Ies/uu.jpg"));
scene2->addItem(item);
view->show();
game_function *gm; //call a function in child class
gm->set_buttons();
}
</code>```

child class .h file

```<code>class game_function:public Game
{
Q_OBJECT

public:

void set_background();
void mainwindow();
void set_buttons();

private slots:
void button_help();
};
</code>```

.cpp file

```<code>void game_function::set_buttons(){

btn = new QPushButton;
QObject::connect(btn,SIGNAL(clicked()),this,SLOT(startgame()));
btn->setStyleSheet("background-color: white");
pr = this->scene2->addWidget(button);
btn->setAutoFillBackground(true);
btn->setIcon(QIcon(":/Ies/main.png"));
btn->setIconSize(QSize(131,41));
pr->setPos(130,430);

btn1 = new QPushButton;
QObject::connect(btn1,SIGNAL(clicked()),this,SLOT(stopgame()));
btn1->setStyleSheet("background-color: white");
pro = this->scene2->addWidget(button1);
btn1->setAutoFillBackground(true);
btn1->setIcon(QIcon(":/Images/exit.png"));
btn1->setIconSize(QSize(131,41));
pr->setPos(130,500);
</code>```

答:
is there ay way i can call this function

You might not be too far from trying a polymorphic invocation ...

perhaps if you

A) add "Game::set_buttons()", and make it virtual, perhaps pure virtual, somewhere in class header:

```<code>class Game:public QGraphicsView,public home{
// ... perhaps after

virtual ~Game(){}

virtual void setbuttons() = 0;

// ...
} // end of class Game
</code>```

then, in method "Game::setbackground()" you can use it ... replace this

```<code>// undefined behavior - gm not initialized
//game_function *gm; //call a function in child class
//gm->set_buttons();
</code>```

with

```<code>this->set_buttons();
</code>```

Body:
I am developing a game using C++ in Qt creator.

I can call the fuctions of the child class in main without an issue, but when I try to call a function in child class from my parent class, the program unexpectedly closes.

I have declared all the public attributes in the .h file of the parent class. T tried removing those attributes and placing them inside the .h file of the child class, then it works fine. But W want to keep them in the parent class and access those from the child class.

Please help get this to work, I tried several times but I could not figure it out.

.h file of parent class:

class Game:public QGraphicsView,public home{

Q_OBJECT

public:

Game(QWidget* parent=0);

virtual ~Game(){}

void createBlockCol(double x);
void creatBlockGrid();
virtual void setbackground();

QPushButton *btn2;
QPushButton *btn3;
QPushButton *btn4;
QGraphicsScene* scene;
QGraphicsScene *scene2;
QGraphicsView* view;
QPushButton *btn;
QPushButton *btn1;
QGraphicsProxyWidget *pr;
QGraphicsProxyWidget *pr1;

QGraphicsProxyWidget *pr2;
QGraphicsProxyWidget *pr3;
QGraphicsProxyWidget *pr4;
QGraphicsPixmapItem* item1;
QGraphicsPixmapItem* item;

private slots:
void start();

This is .cpp class of parent

Game::Game(QWidget *parent): QGraphicsView(parent){
scene = new QGraphicsScene(0,0,466,600);
setScene(scene);

}

void Game::setbackground(){

scene2 = new QGraphicsScene(0,0,400,600);
QGraphicsView* view = new QGraphicsView(scene2);
item = new QGraphicsPixmapItem(QPixmap(":/Ies/uu.jpg"));
scene2->addItem(item);
view->show();
game_function *gm; //call a function in child class
gm->set_buttons();
}

child class .h file

class game_function:public Game
{
Q_OBJECT

public:

void set_background();
void mainwindow();
void set_buttons();

private slots:
void button_help();
};

.cpp file

void game_function::set_buttons(){

btn = new QPushButton;
QObject::connect(btn,SIGNAL(clicked()),this,SLOT(startgame()));
btn->setStyleSheet("background-color: white");
pr = this->scene2->addWidget(button);
btn->setAutoFillBackground(true);
btn->setIcon(QIcon(":/Ies/main.png"));
btn->setIconSize(QSize(131,41));
pr->setPos(130,430);

btn1 = new QPushButton;
QObject::connect(btn1,SIGNAL(clicked()),this,SLOT(stopgame()));
btn1->setStyleSheet("background-color: white");
pro = this->scene2->addWidget(button1);
btn1->setAutoFillBackground(true);
btn1->setIcon(QIcon(":/Images/exit.png"));
btn1->setIconSize(QSize(131,41));
pr->setPos(130,500);

Body:
is there ay way i can call this function

You might not be too far from trying a polymorphic invocation ...

perhaps if you

A) add "Game::set_buttons()", and make it virtual, perhaps pure virtual, somewhere in class header:

class Game:public QGraphicsView,public home{
// ... perhaps after

virtual ~Game(){}

virtual void setbuttons() = 0;

// ...
} // end of class Game

then, in method "Game::setbackground()" you can use it ... replace this

// undefined behavior - gm not initialized
//game_function *gm; //call a function in child class
//gm->set_buttons();

with

this->set_buttons();


问:
Automatic type Conversion in C#
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

```<code>public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}
</code>```

so that I could just call them like this:

```<code>eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();
</code>```

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

```<code>eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];
</code>```

The row is a DataRow if that matters.

答:
I know that you could override an
  object's ToString() Method, so that
  everytime you call an object or pass
  it to a function that requires a
  String type it will be converted to a
  String.

No, you are wrong. The following code won't compile:

```<code>class MyClass
{
    public override string ToString()
    {
        return "MyClass";
    }
}

static void MyMethod(string s) { }

static void Main(string[] args)
{
    MyMethod(new MyClass());   //compile error
}
</code>```

The compiler will not get the type of MyMethod parameter(which is string) first and try to convert the argument you passed(whose type is MyClass) to it. I guess you are probably mislead by something like Console.WriteLine. Base on the code above,
Console.WriteLine(new MyClass()) prints "MyClass" to the console, it seems that the compiler knows you should pass a string to Console.WriteLine and try to convert MyClass to string. But the essential is Console.WriteLine has several overloads, one of them is for object:

```<code>//from Console.cs
public static void WriteLine(object value)
{
    //in this method there is something like
    //Console.WriteLine(value.ToString());
}
</code>```

Title: Automatic type Conversion in C#

Body:
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}

so that I could just call them like this:

eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];

The row is a DataRow if that matters.

Body:
I know that you could override an
  object's ToString() Method, so that
  everytime you call an object or pass
  it to a function that requires a
  String type it will be converted to a
  String.

No, you are wrong. The following code won't compile:

class MyClass
{
    public override string ToString()
    {
        return "MyClass";
    }
}

static void MyMethod(string s) { }

static void Main(string[] args)
{
    MyMethod(new MyClass());   //compile error
}

The compiler will not get the type of MyMethod parameter(which is string) first and try to convert the argument you passed(whose type is MyClass) to it. I guess you are probably mislead by something like Console.WriteLine. Base on the code above,
Console.WriteLine(new MyClass()) prints "MyClass" to the console, it seems that the compiler knows you should pass a string to Console.WriteLine and try to convert MyClass to string. But the essential is Console.WriteLine has several overloads, one of them is for object:

//from Console.cs
public static void WriteLine(object value)
{
    //in this method there is something like
    //Console.WriteLine(value.ToString());
}


问:
Common_Model.php exists, but doesn't declare class Common_Model
I tried checking all the names. It is working fine in php 5.3 but not working in php 5.5

An uncaught Exception was encountered

Type: RuntimeException

Message: C:\xampp\htdocs\project\application\models/Common_Model.php
  exists, but doesn't declare class Common_Model

Filename: C:\xampp\htdocs\project\system\core\Loader.php

Line Number: 306

Backtrace:

File: C:\xampp\htdocs\project\application\controllers\Auth.php Line: 7
  Function: __construct

File: C:\xampp\htdocs\project\index.php Line: 292 Function:
  require_once

In the message, I can see an unexpected backslash in front of Common_Model.php. Message: C:\xampp\htdocs\project\application\models/Common_Model.php exists, but doesn't declare class Common_Model

Common_Model.php contains:

```<code><? if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Common_Model extends CI_Model {

        public function __construct()
        {
                // Call the CI_Model constructor
                parent::__construct();
        }
        .
        .
        .
        .
</code>```

EDIT

I just changed Common_Model.php to Common_model.php and still getting the same error

An uncaught Exception was encountered

Type: RuntimeException

Message: C:\xampp\htdocs\project\application\models/Common_model.php
  exists, but doesn't declare class Common_model

Filename: C:\xampp\htdocs\project\system\core\Loader.php

Line Number: 306

Backtrace:

File: C:\xampp\htdocs\project\application\controllers\Auth.php Line:
  7 Function: __construct

File: C:\xampp\htdocs\project\index.php Line: 292 Function:
  require_once

答: I think your model file name and controller files name is same. please make it differ and check. It is working fine for me. </p>

Body:
I tried checking all the names. It is working fine in php 5.3 but not working in php 5.5

An uncaught Exception was encountered

Type: RuntimeException

Message: C:\xampp\htdocs\project\application\models/Common_Model.php
  exists, but doesn't declare class Common_Model

Filename: C:\xampp\htdocs\project\system\core\Loader.php

Line Number: 306

Backtrace:

File: C:\xampp\htdocs\project\application\controllers\Auth.php Line: 7
  Function: __construct

File: C:\xampp\htdocs\project\index.php Line: 292 Function:
  require_once

In the message, I can see an unexpected backslash in front of Common_Model.php. Message: C:\xampp\htdocs\project\application\models/Common_Model.php exists, but doesn't declare class Common_Model

Common_Model.php contains:

<? if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Common_Model extends CI_Model {

        public function __construct()
        {
                // Call the CI_Model constructor
                parent::__construct();
        }
        .
        .
        .
        .

EDIT

I just changed Common_Model.php to Common_model.php and still getting the same error

An uncaught Exception was encountered

Type: RuntimeException

Message: C:\xampp\htdocs\project\application\models/Common_model.php
  exists, but doesn't declare class Common_model

Filename: C:\xampp\htdocs\project\system\core\Loader.php

Line Number: 306

Backtrace:

File: C:\xampp\htdocs\project\application\controllers\Auth.php Line:
  7 Function: __construct

File: C:\xampp\htdocs\project\index.php Line: 292 Function:
  require_once


问:
Not able to start Apache
Not able to start apache. Giving the below error.
Could some one please help me on this?

Error message:

ip-10-128-9-27 httpd-scl-wrapper: httpd: Syntax error on line 56 of /opt/rh/httpd24/root/etc/httpd/conf/httpd.conf: Syntax error on line 1 of /opt/rh/httpd24/root/etc/httpd/conf.modules.d/00-ssl.conf: Cannot load modules/mod_ssl.so into server: /lib64/libcrypto.so.10: version `OPENSSL_1.0.2' not found (required by /opt/rh/httpd24/root/etc/httpd/modules/mod_ssl.so)

答:
Below is the detailed error message.</p>

```<code>[root@ip-10-128-9-27 centos]# systemctl status httpd24-httpd.service
● httpd24-httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd24-httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Thu 2017-12-07 12:34:05 UTC; 12s ago
  Process: 29020 ExecStop=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -k graceful-stop (code=exited, status=1/FAILURE)
  Process: 29018 ExecStart=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 29018 (code=exited, status=1/FAILURE)

Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: Starting The Apache HTTP Server...
Dec 07 12:34:05 ip-10-128-9-27 httpd-scl-wrapper[29018]: httpd: Syntax error on line 56 of /opt/rh/httpd24/root/etc/httpd/conf/httpd.conf: Syntax error on line 1 of /opt/rh/httpd24/root/etc/httpd/conf.modules.d/00-ssl.conf...
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: httpd24-httpd.service: main process exited, code=exited, status=1/FAILURE
Dec 07 12:34:05 ip-10-128-9-27 httpd-scl-wrapper[29020]: httpd: Syntax error on line 56 of /opt/rh/httpd24/root/etc/httpd/conf/httpd.conf: Syntax error on line 1 of /opt/rh/httpd24/root/etc/httpd/conf.modules.d/00-ssl.conf...
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: httpd24-httpd.service: control process exited, code=exited status=1
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: Failed to start The Apache HTTP Server.
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: Unit httpd24-httpd.service entered failed state.
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: httpd24-httpd.service failed.
</code>```

Title: Not able to start Apache

Body:
Below is the detailed error message.

[root@ip-10-128-9-27 centos]# systemctl status httpd24-httpd.service
● httpd24-httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd24-httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Thu 2017-12-07 12:34:05 UTC; 12s ago
  Process: 29020 ExecStop=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -k graceful-stop (code=exited, status=1/FAILURE)
  Process: 29018 ExecStart=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 29018 (code=exited, status=1/FAILURE)

Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: Starting The Apache HTTP Server...
Dec 07 12:34:05 ip-10-128-9-27 httpd-scl-wrapper[29018]: httpd: Syntax error on line 56 of /opt/rh/httpd24/root/etc/httpd/conf/httpd.conf: Syntax error on line 1 of /opt/rh/httpd24/root/etc/httpd/conf.modules.d/00-ssl.conf...
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: httpd24-httpd.service: main process exited, code=exited, status=1/FAILURE
Dec 07 12:34:05 ip-10-128-9-27 httpd-scl-wrapper[29020]: httpd: Syntax error on line 56 of /opt/rh/httpd24/root/etc/httpd/conf/httpd.conf: Syntax error on line 1 of /opt/rh/httpd24/root/etc/httpd/conf.modules.d/00-ssl.conf...
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: httpd24-httpd.service: control process exited, code=exited status=1
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: Failed to start The Apache HTTP Server.
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: Unit httpd24-httpd.service entered failed state.
Dec 07 12:34:05 ip-10-128-9-27 systemd[1]: httpd24-httpd.service failed.


问:
Associating DB3 with Xamarin Forms app
I'm having some difficulty associating a .db3 file with my iOS project of my Xamarin Forms app. Ideally I would like the user to click on a file type of .db3 and for it to open my app.
I've edited the Info.plist to contain:

```<code><key>CFBundleDocumentTypes</key>
  <array>
    <dict>
      <key>CFBundleTypeIconFiles</key>
      <array>
        <string>**********.png</string>
      </array>
      <key>CFBundleTypeName</key>
      <string>*******</string>
      <key>CFBundleTypeRole</key>
      <string>Viewer</string>
      <key>LSHandlerRank</key>
      <string>Alternate</string>
      <key>LSItemContentTypes</key>
      <array>
        <string>public.db3</string>
      </array>
    </dict>
  </array>
</code>```

Not sure where I'm going wrong in my code, any help would be appreciated.

答:
Turns out this worked as a solution:</p>

```<code><key>CFBundleDocumentTypes</key>
  <array>
    <dict>
      <key>CFBundleTypeIconFile</key>
      <string>any.png</string>
      <key>LSItemContentTypes</key>
      <array>
        <string>com.proj.name.db3</string>
      </array>
      <key>CFBundleTypeName</key>
      <string>DB3 Custom data type</string>
      <key>LSHandlerRank</key>
      <string>Owner</string>
    </dict>
  </array>

  <key>UTExportedTypeDeclarations</key>
  <array>
    <dict>
      <key>UTTypeDescription</key>
      <string>Database file import and export</string>
      <key>UTTypeConformsTo</key>
      <array>
        <string>public.text</string>
      </array>
      <key>UTTypeIdentifier</key>
      <string>com.proj.name.db3</string>
      <key>UTTypeTagSpecification</key>
      <dict>
        <key>public.filename-extension</key>
        <string>db3</string>
      </dict>
    </dict>
  </array>
</code>```

Title: Associating DB3 with Xamarin Forms app

Body:
I'm having some difficulty associating a .db3 file with my iOS project of my Xamarin Forms app. Ideally I would like the user to click on a file type of .db3 and for it to open my app.
I've edited the Info.plist to contain:

<key>CFBundleDocumentTypes</key>
  <array>
    <dict>
      <key>CFBundleTypeIconFiles</key>
      <array>
        <string>**********.png</string>
      </array>
      <key>CFBundleTypeName</key>
      <string>*******</string>
      <key>CFBundleTypeRole</key>
      <string>Viewer</string>
      <key>LSHandlerRank</key>
      <string>Alternate</string>
      <key>LSItemContentTypes</key>
      <array>
        <string>public.db3</string>
      </array>
    </dict>
  </array>

Not sure where I'm going wrong in my code, any help would be appreciated.

Body:
Turns out this worked as a solution:

<key>CFBundleDocumentTypes</key>
  <array>
    <dict>
      <key>CFBundleTypeIconFile</key>
      <string>any.png</string>
      <key>LSItemContentTypes</key>
      <array>
        <string>com.proj.name.db3</string>
      </array>
      <key>CFBundleTypeName</key>
      <string>DB3 Custom data type</string>
      <key>LSHandlerRank</key>
      <string>Owner</string>
    </dict>
  </array>

  <key>UTExportedTypeDeclarations</key>
  <array>
    <dict>
      <key>UTTypeDescription</key>
      <string>Database file import and export</string>
      <key>UTTypeConformsTo</key>
      <array>
        <string>public.text</string>
      </array>
      <key>UTTypeIdentifier</key>
      <string>com.proj.name.db3</string>
      <key>UTTypeTagSpecification</key>
      <dict>
        <key>public.filename-extension</key>
        <string>db3</string>
      </dict>
    </dict>
  </array>


问:
Non-static method calling inside a class is not Deprecated in PHP?
As PHP manual stated

As of PHP 7.0.0 calling a non-static method statically has been
  generally deprecated (even if called from a compatible context).

To check this statement-

I am calling a Non-static method outside a class then its generating error

```<code>class A{
    public function foo(){
        echo "testing<br/>";
    }
}
A::foo();
</code>```

Deprecated: Non-static method A::foo() should not be called statically

But when I am calling a Non-static method inside a class then its not generating Deprecated error

```<code>class A{
    public function foo(){
        echo "testing<br/>";
    }

    public function Display(){
        A::foo();    //calling a Non-static method inside statically
        self::foo(); //calling a Non-static method inside statically
    }
}
$obj=new A();
$obj->Display();
</code>```

Does it deprecated only when calling statically from outside the class?

答:
Using A:: or self:: inside class methods, refers as $this->. From Docs

Warning In PHP 7, calling non-static methods statically is deprecated,
  and will generate an E_DEPRECATED warning. Support for calling
  non-static methods statically may be removed in the future.

Body:
As PHP manual stated

As of PHP 7.0.0 calling a non-static method statically has been
  generally deprecated (even if called from a compatible context).

To check this statement-

I am calling a Non-static method outside a class then its generating error

class A{
    public function foo(){
        echo "testing
";
    }
}
A::foo();

Deprecated: Non-static method A::foo() should not be called statically

But when I am calling a Non-static method inside a class then its not generating Deprecated error

class A{
    public function foo(){
        echo "testing
";
    }

    public function Display(){
        A::foo();    //calling a Non-static method inside statically
        self::foo(); //calling a Non-static method inside statically
    }
}
$obj=new A();
$obj->Display();

Does it deprecated only when calling statically from outside the class?


问:
iPhone popup menu like iPad popover?
How can i implement this popup menu in iphone app like a popover in ipad?

EDIT: This is the best at moment: https://github.com/runway20/PopoverView

答: The screenshot above is not a UIActionSheet. It looks like a simple UIView subclass with custom UIButtons on top of it. So go ahead and create the subclass according to your needs and then add it as a subview to your view every time you need it.</p>

Title: iPhone popup menu like iPad popover?


问:
Angular 4 Unit Tests (TestBed) extremely slow
I have some unit tests using Angular TestBed. Even if the tests are very simple, they run extremely slow (on avarage 1 test assetion per second).

Even after re-reading Angular documentation, I could not find the reason of such a bad perfomance.

Isolated tests, not using TestBed, run in a fraction of second.

UnitTest

```<code>import { Component } from "@angular/core";
import { ComponentFixture, TestBed, async } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { DebugElement } from "@angular/core";
import { DynamicFormDropdownComponent } from "./dynamicFormDropdown.component";
import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
import { FormsModule } from "@angular/forms";
import { DropdownQuestion } from "../../element/question/questionDropdown";
import { TranslateService } from "@ngx-translate/core";
import { TranslatePipeMock } from "../../../../tests-container/translate-pipe-mock";

describe("Component: dynamic drop down", () => {

    let component: DynamicFormDropdownComponent;
    let fixture: ComponentFixture<DynamicFormDropdownComponent>;
    let expectedInputQuestion: DropdownQuestion;
    const emptySelectedObj = { key: "", value: ""};

    const expectedOptions = {
        key: "testDropDown",
        value: "",
        label: "testLabel",
        disabled: false,
        selectedObj: { key: "", value: ""},
        options: [
            { key: "key_1", value: "value_1" },
            { key: "key_2", value: "value_2" },
            { key: "key_3", value: "value_3" },
        ],
    };

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [NgbModule.forRoot(), FormsModule],
            declarations: [DynamicFormDropdownComponent, TranslatePipeMock],
            providers: [TranslateService],
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(DynamicFormDropdownComponent);

        component = fixture.componentInstance;

        expectedInputQuestion = new DropdownQuestion(expectedOptions);
        component.question = expectedInputQuestion;
    });

    it("should have a defined component", () => {
        expect(component).toBeDefined();
    });

    it("Must have options collapsed by default", () => {
        expect(component.optionsOpen).toBeFalsy();
    });

    it("Must toggle the optionsOpen variable calling openChange() method", () => {
        component.optionsOpen = false;
        expect(component.optionsOpen).toBeFalsy();
        component.openChange();
        expect(component.optionsOpen).toBeTruthy();
    });

    it("Must have options available once initialized", () => {
        expect(component.question.options.length).toEqual(expectedInputQuestion.options.length);
    });

    it("On option button click, the relative value must be set", () => {
        spyOn(component, "propagateChange");

        const expectedItem = expectedInputQuestion.options[0];
        fixture.detectChanges();
        const actionButtons = fixture.debugElement.queryAll(By.css(".dropdown-item"));
        actionButtons[0].nativeElement.click();
        expect(component.question.selectedObj).toEqual(expectedItem);
        expect(component.propagateChange).toHaveBeenCalledWith(expectedItem.key);
    });

    it("writeValue should set the selectedObj once called (pass string)", () => {
        expect(component.question.selectedObj).toEqual(emptySelectedObj);
        const expectedItem = component.question.options[0];
        component.writeValue(expectedItem.key);
        expect(component.question.selectedObj).toEqual(expectedItem);
    });

    it("writeValue should set the selectedObj once called (pass object)", () => {
        expect(component.question.selectedObj).toEqual(emptySelectedObj);
        const expectedItem = component.question.options[0];
        component.writeValue(expectedItem);
        expect(component.question.selectedObj).toEqual(expectedItem);
    });
});
</code>```

Target Component (with template)

```<code>import { Component, Input, OnInit, ViewChild, ElementRef, forwardRef } from "@angular/core";
import { FormGroup, ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { DropdownQuestion } from "../../element/question/questionDropdown";

@Component({
    selector: "df-dropdown",
    templateUrl: "./dynamicFormDropdown.component.html",
    styleUrls: ["./dynamicFormDropdown.styles.scss"],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => DynamicFormDropdownComponent),
            multi: true,
        },
    ],
})
export class DynamicFormDropdownComponent implements ControlValueAccessor {
    @Input()
    public question: DropdownQuestion;

    public optionsOpen: boolean = false;

    public selectItem(key: string, value: string): void {
        this.question.selectedObj = { key, value };
        this.propagateChange(this.question.selectedObj.key);
    }

    public writeValue(object: any): void {
        if (object) {
            if (typeof object === "string") {
                this.question.selectedObj = this.question.options.find((item) => item.key === object) || { key: "", value: "" };
            } else {
                this.question.selectedObj = object;
            }
        }
    }

    public registerOnChange(fn: any) {
        this.propagateChange = fn;
    }

    public propagateChange = (_: any) => { };

    public registerOnTouched() {
    }

    public openChange() {
        if (!this.question.disabled) {
            this.optionsOpen = !this.optionsOpen;
        }
    }

    private toggle(dd: any) {
        if (!this.question.disabled) {
            dd.toggle();
        }
    }
}

-----------------------------------------------------------------------

<div>
    <div (openChange)="openChange();" #dropDown="ngbDropdown" ngbDropdown class="wrapper" [ngClass]="{'disabled-item': question.disabled}">
        <input type="text"
                [disabled]="question.disabled"
                [name]="controlName"
                class="select btn btn-outline-primary"
                [ngModel]="question.selectedObj.value | translate"
                [title]="question.selectedObj.value"
                readonly ngbDropdownToggle #selectDiv/>
        <i (click)="toggle(dropDown);" [ngClass]="optionsOpen ? 'arrow-down' : 'arrow-up'" class="rchicons rch-003-button-icon-referenzen-pfeil-akkordon"></i>
        <div ngbDropdownMenu aria-labelledby="dropdownBasic1" class="option-wrapper">
            <button *ngFor="let opt of question.options; trackBy: opt?.key" (click)="selectItem(opt.key, opt.value); dropDown.close();"
                class="dropdown-item option" [disabled]="question.disabled">{{opt.value | translate}}</button>
        </div>
    </div>
</div>
</code>```

Karma config

```<code>var webpackConfig = require('./webpack/webpack.dev.js');

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    plugins: [
      require('karma-webpack'),
      require('karma-jasmine'),
      require('karma-phantomjs-launcher'),
      require('karma-sourcemap-loader'),
      require('karma-tfs-reporter'),
      require('karma-junit-reporter'),
    ],

    files: [
      './app/polyfills.ts',
      './tests-container/test-bundle.spec.ts',
    ],
    exclude: [],
    preprocessors: {
      './app/polyfills.ts': ['webpack', 'sourcemap'],
      './tests-container/test-bundle.spec.ts': ['webpack', 'sourcemap'],
      './app/**/!(*.spec.*).(ts|js)': ['sourcemap'],
    },
    webpack: {
      entry: './tests-container/test-bundle.spec.ts',
      devtool: 'inline-source-map',
      module: webpackConfig.module,
      resolve: webpackConfig.resolve
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },

    reporters: ['progress', 'junit', 'tfs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false,
    concurrency: Infinity
  })
}
</code>```

答:
It turned out the problem is with Angular, as addressed on Github

Below a workaround from the Github discussion that dropped the time for running the tests from more than 40 seconds to just 1 second (!) in our project.

```<code>const oldResetTestingModule = TestBed.resetTestingModule;

beforeAll((done) => (async () => {
  TestBed.resetTestingModule();
  TestBed.configureTestingModule({
    // ...
  });

  function HttpLoaderFactory(http: Http) {
    return new TranslateHttpLoader(http, "/api/translations/", "");
  }

  await TestBed.compileComponents();

  // prevent Angular from resetting testing module
  TestBed.resetTestingModule = () => TestBed;
})()
  .then(done)
  .catch(done.fail));
</code>```

Body:
I have some unit tests using Angular TestBed. Even if the tests are very simple, they run extremely slow (on avarage 1 test assetion per second).

Even after re-reading Angular documentation, I could not find the reason of such a bad perfomance.

Isolated tests, not using TestBed, run in a fraction of second.

UnitTest

import { Component } from "@angular/core";
import { ComponentFixture, TestBed, async } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { DebugElement } from "@angular/core";
import { DynamicFormDropdownComponent } from "./dynamicFormDropdown.component";
import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
import { FormsModule } from "@angular/forms";
import { DropdownQuestion } from "../../element/question/questionDropdown";
import { TranslateService } from "@ngx-translate/core";
import { TranslatePipeMock } from "../../../../tests-container/translate-pipe-mock";

describe("Component: dynamic drop down", () => {

    let component: DynamicFormDropdownComponent;
    let fixture: ComponentFixture<DynamicFormDropdownComponent>;
    let expectedInputQuestion: DropdownQuestion;
    const emptySelectedObj = { key: "", value: ""};

    const expectedOptions = {
        key: "testDropDown",
        value: "",
        label: "testLabel",
        disabled: false,
        selectedObj: { key: "", value: ""},
        options: [
            { key: "key_1", value: "value_1" },
            { key: "key_2", value: "value_2" },
            { key: "key_3", value: "value_3" },
        ],
    };

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [NgbModule.forRoot(), FormsModule],
            declarations: [DynamicFormDropdownComponent, TranslatePipeMock],
            providers: [TranslateService],
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(DynamicFormDropdownComponent);

        component = fixture.componentInstance;

        expectedInputQuestion = new DropdownQuestion(expectedOptions);
        component.question = expectedInputQuestion;
    });

    it("should have a defined component", () => {
        expect(component).toBeDefined();
    });

    it("Must have options collapsed by default", () => {
        expect(component.optionsOpen).toBeFalsy();
    });

    it("Must toggle the optionsOpen variable calling openChange() method", () => {
        component.optionsOpen = false;
        expect(component.optionsOpen).toBeFalsy();
        component.openChange();
        expect(component.optionsOpen).toBeTruthy();
    });

    it("Must have options available once initialized", () => {
        expect(component.question.options.length).toEqual(expectedInputQuestion.options.length);
    });

    it("On option button click, the relative value must be set", () => {
        spyOn(component, "propagateChange");

        const expectedItem = expectedInputQuestion.options[0];
        fixture.detectChanges();
        const actionButtons = fixture.debugElement.queryAll(By.css(".dropdown-item"));
        actionButtons[0].nativeElement.click();
        expect(component.question.selectedObj).toEqual(expectedItem);
        expect(component.propagateChange).toHaveBeenCalledWith(expectedItem.key);
    });

    it("writeValue should set the selectedObj once called (pass string)", () => {
        expect(component.question.selectedObj).toEqual(emptySelectedObj);
        const expectedItem = component.question.options[0];
        component.writeValue(expectedItem.key);
        expect(component.question.selectedObj).toEqual(expectedItem);
    });

    it("writeValue should set the selectedObj once called (pass object)", () => {
        expect(component.question.selectedObj).toEqual(emptySelectedObj);
        const expectedItem = component.question.options[0];
        component.writeValue(expectedItem);
        expect(component.question.selectedObj).toEqual(expectedItem);
    });
});

Target Component (with template)

import { Component, Input, OnInit, ViewChild, ElementRef, forwardRef } from "@angular/core";
import { FormGroup, ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { DropdownQuestion } from "../../element/question/questionDropdown";

@Component({
    selector: "df-dropdown",
    templateUrl: "./dynamicFormDropdown.component.html",
    styleUrls: ["./dynamicFormDropdown.styles.scss"],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => DynamicFormDropdownComponent),
            multi: true,
        },
    ],
})
export class DynamicFormDropdownComponent implements ControlValueAccessor {
    @Input()
    public question: DropdownQuestion;

    public optionsOpen: boolean = false;

    public selectItem(key: string, value: string): void {
        this.question.selectedObj = { key, value };
        this.propagateChange(this.question.selectedObj.key);
    }

    public writeValue(object: any): void {
        if (object) {
            if (typeof object === "string") {
                this.question.selectedObj = this.question.options.find((item) => item.key === object) || { key: "", value: "" };
            } else {
                this.question.selectedObj = object;
            }
        }
    }

    public registerOnChange(fn: any) {
        this.propagateChange = fn;
    }

    public propagateChange = (_: any) => { };

    public registerOnTouched() {
    }

    public openChange() {
        if (!this.question.disabled) {
            this.optionsOpen = !this.optionsOpen;
        }
    }

    private toggle(dd: any) {
        if (!this.question.disabled) {
            dd.toggle();
        }
    }
}

-----------------------------------------------------------------------

        <input type="text"
                [disabled]="question.disabled"
                [name]="controlName"
                class="select btn btn-outline-primary"
                [ngModel]="question.selectedObj.value | translate"
                [title]="question.selectedObj.value"
                readonly ngbDropdownToggle #selectDiv/>

            <button *ngFor="let opt of question.options; trackBy: opt?.key" (click)="selectItem(opt.key, opt.value); dropDown.close();"
                class="dropdown-item option" [disabled]="question.disabled">{{opt.value | translate}}</button>

Karma config

var webpackConfig = require('./webpack/webpack.dev.js');

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    plugins: [
      require('karma-webpack'),
      require('karma-jasmine'),
      require('karma-phantomjs-launcher'),
      require('karma-sourcemap-loader'),
      require('karma-tfs-reporter'),
      require('karma-junit-reporter'),
    ],

    files: [
      './app/polyfills.ts',
      './tests-container/test-bundle.spec.ts',
    ],
    exclude: [],
    preprocessors: {
      './app/polyfills.ts': ['webpack', 'sourcemap'],
      './tests-container/test-bundle.spec.ts': ['webpack', 'sourcemap'],
      './app/**/!(*.spec.*).(ts|js)': ['sourcemap'],
    },
    webpack: {
      entry: './tests-container/test-bundle.spec.ts',
      devtool: 'inline-source-map',
      module: webpackConfig.module,
      resolve: webpackConfig.resolve
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },

    reporters: ['progress', 'junit', 'tfs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false,
    concurrency: Infinity
  })
}

Body:
It turned out the problem is with Angular, as addressed on Github

Below a workaround from the Github discussion that dropped the time for running the tests from more than 40 seconds to just 1 second (!) in our project.

const oldResetTestingModule = TestBed.resetTestingModule;

beforeAll((done) => (async () => {
  TestBed.resetTestingModule();
  TestBed.configureTestingModule({
    // ...
  });

  function HttpLoaderFactory(http: Http) {
    return new TranslateHttpLoader(http, "/api/translations/", "");
  }

  await TestBed.compileComponents();

  // prevent Angular from resetting testing module
  TestBed.resetTestingModule = () => TestBed;
})()
  .then(done)
  .catch(done.fail));

ContentLicense: CC BY-SA 4.0


问:
Sockets not working for React native and Node.js server using ws
I am trying to connect my backend(node.js server) to frontend (react native app) using sockets.
But the problem is the code never goes into io.on('connection', ...).
i.e. socket connection is not being established.

Any help is appreciated.

This is client-side code:

```<code>import React, { Component } from 'react';
import {
    Alert,
    Button,
    Text,
    View
} from 'react-native';

export default class App extends Component {

    constructor(props) {
        super(props);
        const ws = new WebSocket('ws://localhost:3000');
        console.log("This is client side Web socket.")
        ws.onopen = () => {
            console.log("Its connected")
            ws.send('something'); // send a message
        };

    }
}
</code>```

This is server-side code:

```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
      console.log('a user connected');
});

http.listen(3000, function(){
      console.log('listening on *:3000');
});
</code>```

答:
install npm module socket.io-client then try

```<code>  import React, {
  Component
} from 'react';
import {
  Alert,
  Button,
  Text,
  View
} from 'react-native';
import SocketIOClient from 'socket.io-client';

export default class App extends Component {

  constructor(props) {
    super(props);
    var ws = SocketIOClient('ws://localhost:3000'); // replace localhost with ip
    ws.on('connect', function() {
      console.log("hello");
    });
  }
}
</code>```

Body:
I am trying to connect my backend(node.js server) to frontend (react native app) using sockets.
But the problem is the code never goes into io.on('connection', ...).
i.e. socket connection is not being established.

Any help is appreciated.

This is client-side code:

import React, { Component } from 'react';
import {
    Alert,
    Button,
    Text,
    View
} from 'react-native';

export default class App extends Component {

    constructor(props) {
        super(props);
        const ws = new WebSocket('ws://localhost:3000');
        console.log("This is client side Web socket.")
        ws.onopen = () => {
            console.log("Its connected")
            ws.send('something'); // send a message
        };

    }
}

This is server-side code:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
      console.log('a user connected');
});

http.listen(3000, function(){
      console.log('listening on *:3000');
});

Body:
install npm module socket.io-client then try

  import React, {
  Component
} from 'react';
import {
  Alert,
  Button,
  Text,
  View
} from 'react-native';
import SocketIOClient from 'socket.io-client';

export default class App extends Component {

  constructor(props) {
    super(props);
    var ws = SocketIOClient('ws://localhost:3000'); // replace localhost with ip
    ws.on('connect', function() {
      console.log("hello");
    });
  }
}


问:
AJAX Submit Form and Time Without Refresh
I have a simple form that submits some data to a Google Sheet via AJAX, this is working successfully.

I need to send the current time. The time value does send, but unless the page is refreshed, it remains the same.

Presumably because I am using PHP in order to store the time and date in hidden inputs, and these values won't update until I refresh the page.

I'm unable to refresh the page, it must remain static.

How can I store the date and time values as real-time and send with the AJAX?

My code is below;

HTML / PHP

```<code><form id="feedbackFormGood" name="feedbackFormGood">
    <input hidden="true" name="Feedback" type="text" value="GOOD">
    <input hidden="true" name="Date" type="text" value="<?php echo date('j/n/Y'); ?>">
    <input hidden="true" name="Time" type="text" value="<?php echo date('H:i:s'); ?>">
    <input src="images/feedback/happy.png" type="image">
</form>
</code>```

AJAX

```<code>$(document).ready(function() {
    var request;
    $("#feedbackFormGood").submit(function(event)
    {
        event.preventDefault();
        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        request = $.ajax(
        {
            url: "MyURL", // this is a Google Sheet
            type: "post",
            data: serializedData
        });
    });
});
</code>```

Any advice is appreciated.

答:
You can use php inbuilt function "now()" to insert the date time in database...
Use this in insert query while inserting the data in database, don't try to pass the date time from form or ajax.
you can write code at server side to store date and time regular intervals.</p>

Body:
I have a simple form that submits some data to a Google Sheet via AJAX, this is working successfully.

I need to send the current time. The time value does send, but unless the page is refreshed, it remains the same.

Presumably because I am using PHP in order to store the time and date in hidden inputs, and these values won't update until I refresh the page.

I'm unable to refresh the page, it must remain static.

How can I store the date and time values as real-time and send with the AJAX?

My code is below;

HTML / PHP

<form id="feedbackFormGood" name="feedbackFormGood">
    <input hidden="true" name="Feedback" type="text" value="GOOD">
    <input hidden="true" name="Date" type="text" value="<?php echo date('j/n/Y'); ?>">
    <input hidden="true" name="Time" type="text" value="<?php echo date('H:i:s'); ?>">
    <input src="images/feedback/happy.png" type="image">
</form>

AJAX

$(document).ready(function() {
    var request;
    $("#feedbackFormGood").submit(function(event)
    {
        event.preventDefault();
        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        request = $.ajax(
        {
            url: "MyURL", // this is a Google Sheet
            type: "post",
            data: serializedData
        });
    });
});

Any advice is appreciated.


问:
Windows Phone Regional Issues
I have a text file that needs parsing in the app and this was tested on my UK device and a US device.  This same text file is used by Android and iPhone apps that work fine.  It has been reported to me that some people on Windows Phones this does not work!

It turns out if the device is set to a region like Germany that uses the comma "," as the decimal point then the following code does not work properly!

```<code>GeoCoordinate tempCoord = new GeoCoordinate();
tempCoord.Latitude = Convert.ToDouble(words[0]);
tempCoord.Longitude = Convert.ToDouble(words[1]);
</code>```

As words comes in as a string I'm not sure how else I can get this into a double from a string?

EDIT:
On a slightly related note the following is also causing me grief!

```<code>geoWatcher.Position.Location.Latitude.ToString()
</code>```

This will return 56,888 for European and 56.888 for US/UK!

Arrrgh!

答:
Instead of using Convert.ToDouble, use double.parse(...):

```<code>double d = double.Parse("3.500,02", CultureInfo.GetCultureInfo("de-DE").NumberFormat);
</code>```

There is also an overload of double.ToString() that takes a formatter, and you can use this overload to produce string representations of a double in whatever manner you wish.

Title: Windows Phone Regional Issues

Body:
I have a text file that needs parsing in the app and this was tested on my UK device and a US device.  This same text file is used by Android and iPhone apps that work fine.  It has been reported to me that some people on Windows Phones this does not work!

It turns out if the device is set to a region like Germany that uses the comma "," as the decimal point then the following code does not work properly!

GeoCoordinate tempCoord = new GeoCoordinate();
tempCoord.Latitude = Convert.ToDouble(words[0]);
tempCoord.Longitude = Convert.ToDouble(words[1]);

As words comes in as a string I'm not sure how else I can get this into a double from a string?

EDIT:
On a slightly related note the following is also causing me grief!

geoWatcher.Position.Location.Latitude.ToString()

This will return 56,888 for European and 56.888 for US/UK!

Arrrgh!

Body:
Instead of using Convert.ToDouble, use double.parse(...):

double d = double.Parse("3.500,02", CultureInfo.GetCultureInfo("de-DE").NumberFormat);

There is also an overload of double.ToString() that takes a formatter, and you can use this overload to produce string representations of a double in whatever manner you wish.


问:
Remove table frames in pdf output
I'm using python sphinx to generate our user manuals. For this I have to format a pretty large amount of tables.

In some cases we are using tables in order to neatly align pictures and texts. In the mentioned use case we are trying to find a nice solution to suppress the display of the table frames.

I already tried to use the following:

```<code>.. tabularcolumns:: lll

+----+-----+-----+
| A  | B   | C   |
+----+-----+-----+
</code>```

Unfortunately there are still two lines on the top and on the bottom. What might be the easiest way to achieve the desired behavior of a table without displaying the frames?

答:
After trying different kind of approaches I stumbled over the following clumsy solution, which is seemingly not the best so far. Imagine that one might have 20 or more tables without frames in a document.

```<code>.. raw:: latex

   \begingroup
   \setlength{\arrayrulewidth}{0pt}

+----+-----+-----+
| A  | B   | C   |
+----+-----+-----+

.. raw:: latex

   \endgroup
</code>```

Unfortunately, it was the solution I can imagine.

** Revised solution **

It is possible to reduce the pain by defining some substitutions. Just add the following lines to your conf.py.

```<code>rst_epilog = r"""
.. |noFrameStart| raw:: latex

   \begingroup
   \setlength{\arrayrulewidth}{0pt}

.. |noFrameEnd| raw:: latex

   \endgroup
"""
</code>```

No one can easily remove the frame of the table with:

```<code>|noFrameStart|

    +----+-----+-----+
    | A  | B   | C   |
    +----+-----+-----+

|noFrameEnd|
</code>```

This is probably the shortest solution one might achieve.

Title: Remove table frames in pdf output

Body:
I'm using python sphinx to generate our user manuals. For this I have to format a pretty large amount of tables.

In some cases we are using tables in order to neatly align pictures and texts. In the mentioned use case we are trying to find a nice solution to suppress the display of the table frames.

I already tried to use the following:

.. tabularcolumns:: lll

+----+-----+-----+
| A  | B   | C   |
+----+-----+-----+

Unfortunately there are still two lines on the top and on the bottom. What might be the easiest way to achieve the desired behavior of a table without displaying the frames?

Body:
After trying different kind of approaches I stumbled over the following clumsy solution, which is seemingly not the best so far. Imagine that one might have 20 or more tables without frames in a document.

.. raw:: latex

   \begingroup
   \setlength{\arrayrulewidth}{0pt}

+----+-----+-----+
| A  | B   | C   |
+----+-----+-----+

.. raw:: latex

   \endgroup

Unfortunately, it was the solution I can imagine.

** Revised solution **

It is possible to reduce the pain by defining some substitutions. Just add the following lines to your conf.py.

rst_epilog = r"""
.. |noFrameStart| raw:: latex

   \begingroup
   \setlength{\arrayrulewidth}{0pt}

.. |noFrameEnd| raw:: latex

   \endgroup
"""

No one can easily remove the frame of the table with:

|noFrameStart|

    +----+-----+-----+
    | A  | B   | C   |
    +----+-----+-----+

|noFrameEnd|

This is probably the shortest solution one might achieve.


问:
PHP array: count or sizeof?
To find the number of elements in a PHP $array, which is faster/better/stronger?

count($array) or sizeof($array) ?

Edit

Thanks to Andy Lester, I have refined my question to mean from a multilingual perspective.  The manual commenters say

"[sizeof] does not mean the same in
  many other languages based on C"

Is this true?

答:
Please use count function, Here is a example how to count array in a element

```<code>$cars = array("Volvo","BMW","Toyota");
echo count($cars);
</code>```

The count() function returns the number of elements in an array.

The sizeof() function returns the number of elements in an array.

The sizeof() function is an alias of the count() function.

Title: PHP array: count or sizeof?

Body:
Please use count function, Here is a example how to count array in a element

$cars = array("Volvo","BMW","Toyota");
echo count($cars);

The count() function returns the number of elements in an array.

The sizeof() function returns the number of elements in an array.

The sizeof() function is an alias of the count() function.


问:
ASP.Net Identity Change Password account lockout does not work
I am using ASP.Net identity.  In the changepasswordasync function an invalid old password does not trigger an account lockout, is there anyway to get this to happen?  This was raised as low issue by Pen test.

Regards

Mike

答:
You can do this by calling lockout function if user provides wrong old password</p>

```<code>int userId = User.Identity.GetUserId();
IdentityResult result = await UserManager.ChangePasswordAsync(userId , model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
    userManager.ResetAccessFailedCount(userId);
}
else
{
    //you can add logic if the call didn't succeeded because of incorrect old
    password and then execute the following line
    userManager.AccessFailed(userId);
}
</code>```

Body:
You can do this by calling lockout function if user provides wrong old password

int userId = User.Identity.GetUserId();
IdentityResult result = await UserManager.ChangePasswordAsync(userId , model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
    userManager.ResetAccessFailedCount(userId);
}
else
{
    //you can add logic if the call didn't succeeded because of incorrect old
    password and then execute the following line
    userManager.AccessFailed(userId);
}


问:
No tab bar in one child view since Xcode 9.2 update
Since I updated to Xcode 9.2, the tab bar isn't displayed anymore in one of my child views and I'm struggling to get it back.

I did everything using the storyboard.
Here is a screenshot of it:

As you can see, the same segue is used in both views but the result is not the same...

答:
I ended up using a small workaround. Maybe it is the right way to do it and my first implementation was wrong.

So instead of embedding the tab bar controller in a nav bar controller I ended up putting each tab in a nav bar controller.
Like this:
screenshot

And now everything is working correctly.


问:
SQL Server, trying to add constraint while creating table, wherein there is a field 'ssn_nr' for ssn's
I have created a table with a column ssn_nr. I have inserted ssn's with 9 digits. However, there are ssn's starting from '0' have removed itself, which resultant few ssn's showing with only 8 digits.

Example: I tried to insert ssn's like: 089562715,985624851...(having 9 digits), data type was used 'int' not null. Execution was successful, but ssn's start's with '0' automatically got removed.

Desired result: I want all ssn's should be in 9 digits, no matter if any ssn start's with having single or multiple '0' (exm for ssn: 002154698, 025489635, 000548965).

答:
Numeric Datatypes does not allow preceding zero's. So I recommend you change the data type as Varchar for this column.

```<code>alter table yourtable
alter column SSN varchar(10)
</code>```

Then update the column to add preceding zero to the existing records

```<code>update yourtable set ssn = right('000000000'+SSN,9)
</code>```

If altering the field is not possible, then you can try casting the column as varchar and add preceding zero's while selecting the records. Like this

```<code>select SSN =right('000000000'+SSN,9) from yourtable
</code>```

But I prefer altering the column.

Body:
Numeric Datatypes does not allow preceding zero's. So I recommend you change the data type as Varchar for this column.

alter table yourtable
alter column SSN varchar(10)

Then update the column to add preceding zero to the existing records

update yourtable set ssn = right('000000000'+SSN,9)

If altering the field is not possible, then you can try casting the column as varchar and add preceding zero's while selecting the records. Like this

select SSN =right('000000000'+SSN,9) from yourtable

But I prefer altering the column.


问:
Intellij Idea - can't run a simple java class even though the main method is declared
I'm a self-taught coder who is new to both Java & Intellij Idea. I wanted to run a simple Java class called payroll in Intellij Idea Ultimate 2017.3

```<code>public class payroll {
  public static void main(String[] args) {
    int hours = 50;
    double grossPay, payRate = 25.0;

    grossPay = hours * payRate;
    System.out.println("your gross pay is $" + grossPay);}
  }
</code>```

Unfortunately IDEA detects some errors indicating that it can't resolve symbols "String" and "System". And when I tried Run/Edit Configuration, the IDE stated that the main method isn't found in the class, but obviously it is declared already

I've used Eclipse & Netbeans before and things just went smoothly then. Can anyone please point out the main cause of this nuisance for me and how to work it out?

答:
According to the screenshot you have the payroll.java file in src directory.

Try moving that file under src/main/java

Body:
I'm a self-taught coder who is new to both Java & Intellij Idea. I wanted to run a simple Java class called payroll in Intellij Idea Ultimate 2017.3

public class payroll {
  public static void main(String[] args) {
    int hours = 50;
    double grossPay, payRate = 25.0;

    grossPay = hours * payRate;
    System.out.println("your gross pay is $" + grossPay);}
  }

Unfortunately IDEA detects some errors indicating that it can't resolve symbols "String" and "System". And when I tried Run/Edit Configuration, the IDE stated that the main method isn't found in the class, but obviously it is declared already

I've used Eclipse & Netbeans before and things just went smoothly then. Can anyone please point out the main cause of this nuisance for me and how to work it out?


问:
Log NullReferenceException whenever it's being thrown somewhere in code
When running application in Visual Studio there is a setting which allow debugger to break anytime some specified exception is being thrown (even if it's properly caught by the application).

This is a very useful feature because in my application some exceptions (e.g. null reference) should never occur and the programmer should write a code in a way to avoid them (e.g. always perform null-check where null could appear). Thanks to the above mentioned feature my debugger will always break directly at the place of bug when this unwanted exception occur.

Now I would like to inject the similar logic to the release code. I would like every instance of some exception be logged with a stacktrace whenever it occurs even if this exception is caught and handled in the code. Is there such a mechanism in C#?

I could obviously add (catch NullReferenceException) clause to all try/catch blocks, but this would be very tedious.

答: You want the FirstChanceException event on the AppDomain class</p>


问:
Send back response one by one in one request?
Is there a way to do 1 request and write every time an response comes? I want to make 1 request and inside to do 10 requests to the db and when an query responses to write on the html? How can i achieve that?

my api

```<code>routeHandlers = () => {
    let data: Array<any> = [];
    this._router.get('/api/countdetails/:uid', (req, res) => {
        let uid = req.params.uid;
        console.log(req);
        for (let i = 0; i < 10; i++) {
            data.push({
                id: 'request' + i,
                startTime: performance().toFixed(3)
            });

            let query = `SELECT ${i} AS ID, * FROM CountDetails WHERE UID='${uid}'`;
            this._db.execQuery(query, (err, row) => {
                if (err) throw err;

                for (let i = 0; i < data.length; i++) {
                    Object.keys(data[i]).forEach((val, idx) => {
                        if (val === 'id') {
                            if (data[i][val] === 'request' + row[0]['ID']) {
                                data[i].endTime = performance().toFixed(3);
                                data[i].ellapsed = (performance() - data[i]['startTime']).toFixed(3);
                                res.write('<tr><td>' + data[i]['ellapsed'] + '</td></tr>');

                            }
                        }
                    });
                }

            });

        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.end();
        }

    });
}
</code>```

and my html

```<code><div>
    <input type="text" id="iterations" />
    <button type="button" id="btn">send</button>
</div>
<div>
    <table id="tbl">
        <tbody>

        </tbody>
    </table>
</div>

<script>
    var inputValue = document.getElementById('iterations');
    var btn = document.getElementById('btn');
    var array = [];

    btn.addEventListener('click', function () {
        sendRequest(function (xhttp) {
            console.log(xhttp.responseText);
        })
    });

    function sendRequest(callback) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
               callback(xhttp);
            }
        };
        xhttp.open("GET", "http://localhost:3000/api/countdetails/EAACCDF4-EBC3-4B11-8654-98878BFC4B7B", true);
        xhttp.send({ times: 10});
    }
</script>
</code>```

答:
First don't use i for nested for.

So you want to call res.end() once all the database calls are finished. This can be done in a variety of ways, but I will give you a quick one with a little tweak of your code. This is the code snippet and the explanations come after: (also read comments in code)

```<code>routeHandlers = () => {

    /* 1) we can use the indicator to determine when all the async requests are finished */
    let indicator = 0;
    let data = [];

    this._router.get('/api/countdetails/:uid', (req, res) => {

        /* 2) always set the indicator to 0 on a new request */
        indicator = 0;
        let uid = req.params.uid;

        for (let i = 0; i < 10; i++) {
            data.push({
                id: 'request' + i,
                startTime: performance().toFixed(3)
            });

            let query = `SELECT ${i} AS ID, * FROM CountDetails WHERE UID='${uid}'`;
            this._db.execQuery(query, (err, row) => {
                if (err)
                    throw err;

                for (let j = 0; j < data.length; j++) {
                    Object.keys(data[j]).forEach((val, idx) => {
                        if (val === 'id') {
                            if (data[j][val] === 'request' + row[0]['ID']) {
                                data[j].endTime = performance().toFixed(3);
                                data[j].ellapsed = (performance() - data[j]['startTime']).toFixed(3);
                                res.write('<tr><td>' + data[j]['ellapsed'] + '</td></tr>');
                            }
                        }
                    });
                }

                /* 3) here check if indicator is 10 and if yes then all the database calls should be finished */
                indicator++;
                if (indicator === 10) {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                    res.end();
                }
            });
        }
    });
}
</code>```

In short words I will use integer variable as an indicator how many database calls are finished and once number 10 is reached I consider all are done and end the response.

1) Declare indicator variable which will help us to determine when the job is ready;

2) Reset indicator on each coming request (you might also think resetting data)

3) Once database call is finished increment indicator and check its value -> if it is 10 then we are done and end the response.

That's it, short and simple. Let me know if something is unclear.

Body:
Is there a way to do 1 request and write every time an response comes? I want to make 1 request and inside to do 10 requests to the db and when an query responses to write on the html? How can i achieve that?

my api

routeHandlers = () => {
    let data: Array<any> = [];
    this._router.get('/api/countdetails/:uid', (req, res) => {
        let uid = req.params.uid;
        console.log(req);
        for (let i = 0; i < 10; i++) {
            data.push({
                id: 'request' + i,
                startTime: performance().toFixed(3)
            });

            let query = `SELECT ${i} AS ID, * FROM CountDetails WHERE UID='${uid}'`;
            this._db.execQuery(query, (err, row) => {
                if (err) throw err;

                for (let i = 0; i < data.length; i++) {
                    Object.keys(data[i]).forEach((val, idx) => {
                        if (val === 'id') {
                            if (data[i][val] === 'request' + row[0]['ID']) {
                                data[i].endTime = performance().toFixed(3);
                                data[i].ellapsed = (performance() - data[i]['startTime']).toFixed(3);
                                res.write('
' + data[i]['ellapsed'] + '
');

                            }
                        }
                    });
                }

            });

        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.end();
        }

    });
}

and my html

    <input type="text" id="iterations" />
    <button type="button" id="btn">send</button>

Body:
First don't use i for nested for.

So you want to call res.end() once all the database calls are finished. This can be done in a variety of ways, but I will give you a quick one with a little tweak of your code. This is the code snippet and the explanations come after: (also read comments in code)

routeHandlers = () => {

    /* 1) we can use the indicator to determine when all the async requests are finished */
    let indicator = 0;
    let data = [];

    this._router.get('/api/countdetails/:uid', (req, res) => {

        /* 2) always set the indicator to 0 on a new request */
        indicator = 0;
        let uid = req.params.uid;

        for (let i = 0; i < 10; i++) {
            data.push({
                id: 'request' + i,
                startTime: performance().toFixed(3)
            });

            let query = `SELECT ${i} AS ID, * FROM CountDetails WHERE UID='${uid}'`;
            this._db.execQuery(query, (err, row) => {
                if (err)
                    throw err;

                for (let j = 0; j < data.length; j++) {
                    Object.keys(data[j]).forEach((val, idx) => {
                        if (val === 'id') {
                            if (data[j][val] === 'request' + row[0]['ID']) {
                                data[j].endTime = performance().toFixed(3);
                                data[j].ellapsed = (performance() - data[j]['startTime']).toFixed(3);
                                res.write('<tr><td>' + data[j]['ellapsed'] + '</td></tr>');
                            }
                        }
                    });
                }

                /* 3) here check if indicator is 10 and if yes then all the database calls should be finished */
                indicator++;
                if (indicator === 10) {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                    res.end();
                }
            });
        }
    });
}

In short words I will use integer variable as an indicator how many database calls are finished and once number 10 is reached I consider all are done and end the response.

1) Declare indicator variable which will help us to determine when the job is ready;

2) Reset indicator on each coming request (you might also think resetting data)

3) Once database call is finished increment indicator and check its value -> if it is 10 then we are done and end the response.

That's it, short and simple. Let me know if something is unclear.