问:
foreach statement within ACF repeater
I'm not sure if I'm doing this correctly? I have a nested ACF repeater, which is working fine, but the section are all displaying as one lone block.  I want to be able to break the blocks into columns. So I though to do this I would need a "foreach" statement so I could assign an id or class to each section, allowing me to be able to style each section individually - float and add margins etc.

I can't quite get it to work!

```<code><div class="col-xl-12 food-section">

<?php
$rows = get_field('section_container');
if($rows) {
foreach($rows as $row):
?>

<div class="col-xl-6 section-test"> <?php
    if( have_rows('section_container') ) :
    while( have_rows('section_container') ): the_row(); ?>

<h1><?php the_sub_field('section_heading'); ?></h1>
        <div class="section-image"><?php
            $image = get_sub_field('section_image');
            if( !empty($image) ): ?>
                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
        </div>

        <?php endif;

            if( have_rows('sub_section_container') ):
            while( have_rows('sub_section_container') ): the_row();
            ?>
                <h2><?php the_sub_field('sub_section_heading'); ?></h2>
                <?php
                    if( have_rows('food_item') ):
                    while( have_rows('food_item') ): the_row();
                ?>

<div id="menu-table">
    <h3 id="leftside"><?php the_sub_field('item_name'); ?></h3>
    <h4 id="rightside"><?php the_sub_field('price'); ?></h4>
    <div id="menu-description"><p><?php the_sub_field('item_description'); ?></p></div>
    <div class="stroke"></div>
</div>

                <?php   endwhile; //food_item
                    endif;  //food_item

            endwhile; //section_h1_container
            endif;  //section_h1_container

    endwhile; //section_container
    endif;  //section_container

    wp_reset_postdata();

    endforeach; }
?></div>

    </div><!-- food-section -->
</code>```

答:
I've cleaned up your code, and I'm hoping I'm understanding your request. You had an unnecessary if and foreach at the top of the snippet, and a wp_reset_postdata() that is not needed at the end of a repeater call in ACF.

You can read more on nested repeaters here:

https://www.advancedcustomfields.com/resources/working-with-nested-repeaters/

```<code><?php if( have_rows('section_container') ) : ?>
 <div class="col-xl-12 food-section">
      <?php while( have_rows('section_container') ): the_row(); ?>
           <div class="col-xl-6 section-test">
                <h1><?php the_sub_field('section_heading'); ?></h1>
                <div class="section-image">
                     <?php $image = get_sub_field('section_image');
                     if( !empty($image) ): ?>
                          <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
                     <?php endif; ?>
                </div>
                <?php if( have_rows('sub_section_container') ):
                     while( have_rows('sub_section_container') ): the_row(); ?>
                          <h2><?php the_sub_field('sub_section_heading'); ?></h2>
                          <?php if( have_rows('food_item') ):
                               while( have_rows('food_item') ): the_row(); ?>
                                    <div id="menu-table">
                                        <h3 id="leftside"><?php the_sub_field('item_name'); ?></h3>
                                        <h4 id="rightside"><?php the_sub_field('price'); ?></h4>
                                        <div id="menu-description"><p><?php the_sub_field('item_description'); ?></p></div>
                                        <div class="stroke"></div>
                                    </div>
                               <?php   endwhile; //food_item
                          endif;  //food_item
                     endwhile; //section_h1_container
                endif;  //section_h1_container ?>
           </div>
      <?php endwhile; //section_container ?>
 </div>
<?php endif;  //section_container ?>
</code>```

This snippet checks if any rows are set for "section_container" if so, it creates the "food-section" div. It then loops through each row of "section_container". For each row, it creates a "section-test" div, and begins to populate it with the subfield data for that row. It then checks for the "sub_section_container" repeater inside your current row, and loops through the rows inside that nested repeater, and outputs the data.

Title: foreach statement within ACF repeater

Body:
I'm not sure if I'm doing this correctly? I have a nested ACF repeater, which is working fine, but the section are all displaying as one lone block.  I want to be able to break the blocks into columns. So I though to do this I would need a "foreach" statement so I could assign an id or class to each section, allowing me to be able to style each section individually - float and add margins etc.

I can't quite get it to work!

<?php
$rows = get_field('section_container');
if($rows) {
foreach($rows as $row):
?>

 <?php
    if( have_rows('section_container') ) :
    while( have_rows('section_container') ): the_row(); ?>

<?php the_sub_field('section_heading'); ?>

<?php
            $image = get_sub_field('section_image');
            if( !empty($image) ): ?>
                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

        <?php endif;

            if( have_rows('sub_section_container') ):
            while( have_rows('sub_section_container') ): the_row();
            ?>

<?php the_sub_field('sub_section_heading'); ?>

                <?php
                    if( have_rows('food_item') ):
                    while( have_rows('food_item') ): the_row();
                ?>

<?php the_sub_field('item_name'); ?>

<?php the_sub_field('price'); ?>

<?php the_sub_field('item_description'); ?>

                <?php   endwhile; //food_item
                    endif;  //food_item

            endwhile; //section_h1_container
            endif;  //section_h1_container

    endwhile; //section_container
    endif;  //section_container

    wp_reset_postdata();

    endforeach; }
?>

Body:
I've cleaned up your code, and I'm hoping I'm understanding your request. You had an unnecessary if and foreach at the top of the snippet, and a wp_reset_postdata() that is not needed at the end of a repeater call in ACF.

You can read more on nested repeaters here:

https://www.advancedcustomfields.com/resources/working-with-nested-repeaters/

<?php if( have_rows('section_container') ) : ?>
 <div class="col-xl-12 food-section">
      <?php while( have_rows('section_container') ): the_row(); ?>
           <div class="col-xl-6 section-test">
                <h1><?php the_sub_field('section_heading'); ?></h1>
                <div class="section-image">
                     <?php $image = get_sub_field('section_image');
                     if( !empty($image) ): ?>
                          <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
                     <?php endif; ?>
                </div>
                <?php if( have_rows('sub_section_container') ):
                     while( have_rows('sub_section_container') ): the_row(); ?>
                          <h2><?php the_sub_field('sub_section_heading'); ?></h2>
                          <?php if( have_rows('food_item') ):
                               while( have_rows('food_item') ): the_row(); ?>
                                    <div id="menu-table">
                                        <h3 id="leftside"><?php the_sub_field('item_name'); ?></h3>
                                        <h4 id="rightside"><?php the_sub_field('price'); ?></h4>
                                        <div id="menu-description"><p><?php the_sub_field('item_description'); ?></p></div>
                                        <div class="stroke"></div>
                                    </div>
                               <?php   endwhile; //food_item
                          endif;  //food_item
                     endwhile; //section_h1_container
                endif;  //section_h1_container ?>
           </div>
      <?php endwhile; //section_container ?>
 </div>
<?php endif;  //section_container ?>

This snippet checks if any rows are set for "section_container" if so, it creates the "food-section" div. It then loops through each row of "section_container". For each row, it creates a "section-test" div, and begins to populate it with the subfield data for that row. It then checks for the "sub_section_container" repeater inside your current row, and loops through the rows inside that nested repeater, and outputs the data.


来源: stackexchange

问:
Elasticsearch bulk upload error with PHP - Limit of total fields [1000] in index has been exceeded
We are planning use ElasticSearch in one of our projects. Currently, we are testing ElasticSearch 5.0.1 with our data. One issue we are facing is when we are doing a bulk upload from our MySQL tables to elasticsearch following error we are getting...

```<code>java.lang.IllegalArgumentException: Limit of total fields [1000] in index [shopfront] has been exceeded
at org.elasticsearch.index.mapper.MapperService.checkTotalFieldsLimit(MapperService.java:482) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.index.mapper.MapperService.merge(MapperService.java:343) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.index.mapper.MapperService.merge(MapperService.java:277) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.metadata.MetaDataMappingService$PutMappingExecutor.applyRequest(MetaDataMappingService.java:323) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.metadata.MetaDataMappingService$PutMappingExecutor.execute(MetaDataMappingService.java:241) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.service.ClusterService.runTasksForExecutor(ClusterService.java:555) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.service.ClusterService$UpdateTask.run(ClusterService.java:896) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:451) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:238) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:201) ~[elasticsearch-5.0.1.jar:5.0.1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_111]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]
</code>```

We are using PHP as elasticsearch client to doing the bulk upload from MySQL to Elastic. After doing some googling I got this piece of info - https://discuss.elastic.co/t/es-2-3-5-x-metricbeat-index-field-limit/66821

Somewhere also I read that using of "index.mapping.total_fields.limit" will fix the thing. But, can't able to understand how to using that in my PHP code. Here is my PHP code.

```<code>$params = ['body' => []];

$i = 1;
foreach ($productsList as $key => $value) {

    $params['body'][] = [
        'index' => [
            '_index' => 'shopfront',
            '_type' => 'products'
        ],
        'settings' => ['index.mapping.total_fields.limit' => 3000]
    ];

    $params['body'][] = [
        'product_displayname' => $value['product_displayname'],
        'product_price' => $value['product_price'],
        'popularity' => $value['popularity'],
        'lowestcomp_price' => $value['lowestcomp_price']
    ];

    // Every 1000 documents stop and send the bulk request
    if ($i % 1000 == 0) {
        $responses = $client->bulk($params);

        // erase the old bulk request
        $params = ['body' => []];

        // unset the bulk response when you are done to save memory
        unset($responses);
    }

    $i++;
}

// Send the last batch if it exists
if (!empty($params['body'])) {
    $responses = $client->bulk($params);
}
</code>```

NOTE - I've used same code with Elasticsearch 2.4.1 & it's working fine with that.

答:
This feature was decided in this github issue. Two ways to solve this problem:

You can specify a greater value when creating the index:

```<code>PUT test
{
  "shopfront": {
    "index.mapping.total_fields.limit": 2000,
    "number_of_shards": 5,
    "number_of_replicas": 2
  },
  "mappings": {
    ...
  }
}
</code>```

Or if you would like to increase the limit for an existing index:

```<code>PUT shopfront/_settings
{
  "index.mapping.total_fields.limit": 2000
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We are planning use ElasticSearch in one of our projects. Currently, we are testing ElasticSearch 5.0.1 with our data. One issue we are facing is when we are doing a bulk upload from our MySQL tables to elasticsearch following error we are getting...

java.lang.IllegalArgumentException: Limit of total fields [1000] in index [shopfront] has been exceeded
at org.elasticsearch.index.mapper.MapperService.checkTotalFieldsLimit(MapperService.java:482) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.index.mapper.MapperService.merge(MapperService.java:343) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.index.mapper.MapperService.merge(MapperService.java:277) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.metadata.MetaDataMappingService$PutMappingExecutor.applyRequest(MetaDataMappingService.java:323) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.metadata.MetaDataMappingService$PutMappingExecutor.execute(MetaDataMappingService.java:241) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.service.ClusterService.runTasksForExecutor(ClusterService.java:555) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.cluster.service.ClusterService$UpdateTask.run(ClusterService.java:896) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:451) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:238) ~[elasticsearch-5.0.1.jar:5.0.1]
at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:201) ~[elasticsearch-5.0.1.jar:5.0.1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_111]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]

We are using PHP as elasticsearch client to doing the bulk upload from MySQL to Elastic. After doing some googling I got this piece of info - https://discuss.elastic.co/t/es-2-3-5-x-metricbeat-index-field-limit/66821

Somewhere also I read that using of "index.mapping.total_fields.limit" will fix the thing. But, can't able to understand how to using that in my PHP code. Here is my PHP code.

$params = ['body' => []];

$i = 1;
foreach ($productsList as $key => $value) {

    $params['body'][] = [
        'index' => [
            '_index' => 'shopfront',
            '_type' => 'products'
        ],
        'settings' => ['index.mapping.total_fields.limit' => 3000]
    ];

    $params['body'][] = [
        'product_displayname' => $value['product_displayname'],
        'product_price' => $value['product_price'],
        'popularity' => $value['popularity'],
        'lowestcomp_price' => $value['lowestcomp_price']
    ];

    // Every 1000 documents stop and send the bulk request
    if ($i % 1000 == 0) {
        $responses = $client->bulk($params);

        // erase the old bulk request
        $params = ['body' => []];

        // unset the bulk response when you are done to save memory
        unset($responses);
    }

    $i++;
}

// Send the last batch if it exists
if (!empty($params['body'])) {
    $responses = $client->bulk($params);
}

NOTE - I've used same code with Elasticsearch 2.4.1 & it's working fine with that.

Body:
This feature was decided in this github issue. Two ways to solve this problem:

You can specify a greater value when creating the index:

PUT test
{
  "shopfront": {
    "index.mapping.total_fields.limit": 2000,
    "number_of_shards": 5,
    "number_of_replicas": 2
  },
  "mappings": {
    ...
  }
}

Or if you would like to increase the limit for an existing index:

PUT shopfront/_settings
{
  "index.mapping.total_fields.limit": 2000
}


问:
Pulling data from CRM System with Inputrange - mismatched lines
I have built a CRM System on Google Sheets and I am currently facing an issue with the mastersheet. The mastersheet is pulling data from other spreadsheets within the same document. The issue I am facing is that I would like the data to go on to the next available line at the bottom of the mastersheet page, instead of being put underneath the last entry from that particular sheet.

You can find the code I have used below:

={FILTER(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'Customer Data'!B:B"),LEN(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'Customer Data'!B:B")));FILTER(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'17 June 2017 M&G Bookings'!B2:B"),LEN(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'17 June 2017 M&G Bookings'!B2:B")));FILTER(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'Talent Agency - General Details Request form'!Q2:Q"),LEN(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'Talent Agency - General Details Request form'!Q2:Q")));FILTER(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'Performer Database'!P2:P"),LEN(IMPORTRANGE("1c47hRszG3jZf7SPj5pxtabmsw3tmR11ETx3hcEKue2w","'Performer Database'!P2:P")))}

Can anyone please help me with this?
Timestamp goes to column A

答: QUERY and it's ORDER BY clause could be helpful but you should add the timestamp column to your formula in order to use it to sort.</p>


问:
Callback not working inside async.foreachof
I'm getting my callback from my dao and into my service and in my service i have iterated the list of object to be sent to my dao.

My service code

```<code>var dao = require('./dao');
var async = require('async');

exports.addUser = function(obj,callback) {
    async.forEachOf(obj,function(value,key,callback){
        dao.addUser(value,function(data){
            callback(data);
        })
    })
}
</code>```

this callback is not going to my control layer

Control layer

```<code>var express = require('express');
var app = express();
var service = require('./service');

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/addPerson',function(req,res){
    var obj = req.body;
    console.log(obj);
    console.log("......",obj.name);
    console.log("......",obj.age);
    service.addUser(obj,function(data) {
        console.log("---->",data);
        res.json(data);
    })
})

var server = app.listen(8080,function(){});
</code>```

i need to send the data back to the browser

答:
There are two problems with your existing code
1. By referring callback you are calling callback of the asyn.forEachOf
2. Trying to call ur original callback (which intern does res.json(data)). Here you are trying to send multiple response which is not possible.

Try using async.mapValues instead

```<code>exports.addUser = function(obj,callback) {
    async.mapValues(obj,function(value,key,cb){
        dao.addUser(value,function(data){
            cb(null, data);
        })
        }, function(err, result) {
            // result is now a map of results for each key
           callback(result);
      });
}
</code>```

Body:
I'm getting my callback from my dao and into my service and in my service i have iterated the list of object to be sent to my dao.

My service code

var dao = require('./dao');
var async = require('async');

exports.addUser = function(obj,callback) {
    async.forEachOf(obj,function(value,key,callback){
        dao.addUser(value,function(data){
            callback(data);
        })
    })
}

this callback is not going to my control layer

Control layer

var express = require('express');
var app = express();
var service = require('./service');

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/addPerson',function(req,res){
    var obj = req.body;
    console.log(obj);
    console.log("......",obj.name);
    console.log("......",obj.age);
    service.addUser(obj,function(data) {
        console.log("---->",data);
        res.json(data);
    })
})

var server = app.listen(8080,function(){});

i need to send the data back to the browser

Body:
There are two problems with your existing code
1. By referring callback you are calling callback of the asyn.forEachOf
2. Trying to call ur original callback (which intern does res.json(data)). Here you are trying to send multiple response which is not possible.

Try using async.mapValues instead

exports.addUser = function(obj,callback) {
    async.mapValues(obj,function(value,key,cb){
        dao.addUser(value,function(data){
            cb(null, data);
        })
        }, function(err, result) {
            // result is now a map of results for each key
           callback(result);
      });
}


问:
Need help setting up karma testing for poi project

package.json snippet

poi: 9.2.4

karma: ^1.7.1

karma-chai: ^0.1.0

karma-mocha: ^1.3.0

karma-webpack: ^2.0.6

mocha: ^4.0.1

poi-preset-karma: ^9.2.2

webpack: ^3.9.1

poi.config.json

```<code>module.exports = {
    presets: [
        require('poi-preset-karma')({
            port: '5050'
        })
    ],
    webpack(config) {
        config.devtool = 'source-map';
        config.watchOptions = {
            ignored: '/node_modules',
            poll: 1000,
        };
        config.stats = {
            depth: true,
            warnings: true,
        };
        return config;
    },
    define: {
        __VERSION__: require('./package.json').version
    },
    html: {
        title: 'Platform',
        template:'index.ejs'
    }
};
</code>```

When I run the command poi test I get the following output:

```<code>> Using main field in package.json as entry point
> Bundling with Webpack 3.9.1
04 12 2017 22:41:20.194:WARN [config]: "/" is proxied, you should probably change urlRoot to avoid conflicts
TypeError: Cannot read property 'type' of undefined
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:83:13)
    at formatInnerSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:78:54)
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:106:15)
    at getSchemaPartText (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:36:49)
    at Function.formatValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:188:49)
    at WebpackOptionsValidationError.message.Invalid configuration object. .Webpack has been initialised using a configuration object that does not match the API schema.
.validationErrors.map.err (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:77)
    at Array.map (<anonymous>)
    at new WebpackOptionsValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:21)
    at webpack (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/webpack.js:19:9)
    at Plugin (/home/rshighto/btg/peeprFrontend/node_modules/karma-webpack/lib/karma-webpack.js:67:16)
    at invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at Array.instantiate (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:59:20)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Injector.get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at instantiatePreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:55:20)
    at Array.forEach (<anonymous>)
    at createPreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:74:20)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Injector.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Server.start (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/server.js:103:18)
    at Ware.poi.run.webpackConfig (/home/rshighto/btg/peeprFrontend/node_modules/poi-preset-karma/index.js:133:14)
    at Ware.<anonymous> (/home/rshighto/btg/peeprFrontend/node_modules/wrap-fn/index.js:75:16)
04 12 2017 22:41:21.406:ERROR [preprocess]: Can not load "webpack"!
  TypeError: Cannot read property 'type' of undefined
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:83:13)
    at formatInnerSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:78:54)
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:106:15)
    at getSchemaPartText (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:36:49)
    at Function.formatValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:188:49)
    at WebpackOptionsValidationError.message.Invalid configuration object. .Webpack has been initialised using a configuration object that does not match the API schema.
.validationErrors.map.err (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:77)
    at Array.map (<anonymous>)
    at new WebpackOptionsValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:21)
    at webpack (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/webpack.js:19:9)
    at Plugin (/home/rshighto/btg/peeprFrontend/node_modules/karma-webpack/lib/karma-webpack.js:67:16)
    at invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at Array.instantiate (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:59:20)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Injector.get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at instantiatePreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:55:20)
    at Array.forEach (<anonymous>)
    at createPreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:74:20)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Injector.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Server.start (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/server.js:103:18)
    at Ware.poi.run.webpackConfig (/home/rshighto/btg/peeprFrontend/node_modules/poi-preset-karma/index.js:133:14)
    at Ware.<anonymous> (/home/rshighto/btg/peeprFrontend/node_modules/wrap-fn/index.js:75:16)

START:
04 12 2017 22:41:21.653:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:5050/
04 12 2017 22:41:21.654:INFO [launcher]: Launching browser Chrome with unlimited concurrency
04 12 2017 22:41:21.656:ERROR [karma]: Found 1 load error
</code>```

I tried looking through some of the webpack code to see what was missing but I wasn't sure. Seems like the problem is that webpack expects at least one schema option to be defined but it is not. I tried looking at examples on POI's dev's site https://poi.js.org/#/ but couldn't find anything.

Anyone have an idea of what is missing or ran into this problem before?

答: I finally was able to get past the problem. Figured I really didn't have a dependency on karma-webpack. So I removed it, removed node_modules/ and cleared my local cache. And just to be on the safe side I downgraded from node 9.0.0 to 8.9.1 (lts). </p>

Body:
package.json snippet

poi: 9.2.4

karma: ^1.7.1

karma-chai: ^0.1.0

karma-mocha: ^1.3.0

karma-webpack: ^2.0.6

mocha: ^4.0.1

poi-preset-karma: ^9.2.2

webpack: ^3.9.1

poi.config.json

module.exports = {
    presets: [
        require('poi-preset-karma')({
            port: '5050'
        })
    ],
    webpack(config) {
        config.devtool = 'source-map';
        config.watchOptions = {
            ignored: '/node_modules',
            poll: 1000,
        };
        config.stats = {
            depth: true,
            warnings: true,
        };
        return config;
    },
    define: {
        __VERSION__: require('./package.json').version
    },
    html: {
        title: 'Platform',
        template:'index.ejs'
    }
};

When I run the command poi test I get the following output:

> Using main field in package.json as entry point
> Bundling with Webpack 3.9.1
04 12 2017 22:41:20.194:WARN [config]: "/" is proxied, you should probably change urlRoot to avoid conflicts
TypeError: Cannot read property 'type' of undefined
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:83:13)
    at formatInnerSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:78:54)
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:106:15)
    at getSchemaPartText (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:36:49)
    at Function.formatValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:188:49)
    at WebpackOptionsValidationError.message.Invalid configuration object. .Webpack has been initialised using a configuration object that does not match the API schema.
.validationErrors.map.err (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:77)
    at Array.map (<anonymous>)
    at new WebpackOptionsValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:21)
    at webpack (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/webpack.js:19:9)
    at Plugin (/home/rshighto/btg/peeprFrontend/node_modules/karma-webpack/lib/karma-webpack.js:67:16)
    at invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at Array.instantiate (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:59:20)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Injector.get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at instantiatePreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:55:20)
    at Array.forEach (<anonymous>)
    at createPreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:74:20)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Injector.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Server.start (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/server.js:103:18)
    at Ware.poi.run.webpackConfig (/home/rshighto/btg/peeprFrontend/node_modules/poi-preset-karma/index.js:133:14)
    at Ware.<anonymous> (/home/rshighto/btg/peeprFrontend/node_modules/wrap-fn/index.js:75:16)
04 12 2017 22:41:21.406:ERROR [preprocess]: Can not load "webpack"!
  TypeError: Cannot read property 'type' of undefined
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:83:13)
    at formatInnerSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:78:54)
    at Function.formatSchema (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:106:15)
    at getSchemaPartText (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:36:49)
    at Function.formatValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:188:49)
    at WebpackOptionsValidationError.message.Invalid configuration object. .Webpack has been initialised using a configuration object that does not match the API schema.
.validationErrors.map.err (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:77)
    at Array.map (<anonymous>)
    at new WebpackOptionsValidationError (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/WebpackOptionsValidationError.js:68:21)
    at webpack (/home/rshighto/btg/peeprFrontend/node_modules/webpack/lib/webpack.js:19:9)
    at Plugin (/home/rshighto/btg/peeprFrontend/node_modules/karma-webpack/lib/karma-webpack.js:67:16)
    at invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at Array.instantiate (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:59:20)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Injector.get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at instantiatePreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:55:20)
    at Array.forEach (<anonymous>)
    at createPreprocessor (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/preprocessor.js:74:20)
    at Array.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:75:15)
    at get (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:48:43)
    at /home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:71:14
    at Array.map (<anonymous>)
    at Injector.invoke (/home/rshighto/btg/peeprFrontend/node_modules/di/lib/injector.js:70:31)
    at Server.start (/home/rshighto/btg/peeprFrontend/node_modules/karma/lib/server.js:103:18)
    at Ware.poi.run.webpackConfig (/home/rshighto/btg/peeprFrontend/node_modules/poi-preset-karma/index.js:133:14)
    at Ware.<anonymous> (/home/rshighto/btg/peeprFrontend/node_modules/wrap-fn/index.js:75:16)

START:
04 12 2017 22:41:21.653:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:5050/
04 12 2017 22:41:21.654:INFO [launcher]: Launching browser Chrome with unlimited concurrency
04 12 2017 22:41:21.656:ERROR [karma]: Found 1 load error

I tried looking through some of the webpack code to see what was missing but I wasn't sure. Seems like the problem is that webpack expects at least one schema option to be defined but it is not. I tried looking at examples on POI's dev's site https://poi.js.org/#/ but couldn't find anything.

Anyone have an idea of what is missing or ran into this problem before?


问:
Mapping different states with geom_sf using facet wrap and scales free
First, I am aware of this answer : Mapping different states in R using facet wrap

But I work with object of library sf.

It seems that facet_wrap(scales = "free") is not available for objects plotted with geom_sf in ggplot2. I get this message:

Erreur : Free scales are only supported with coord_cartesian() and
  coord_flip()

Is there any option I have missed ?

Anyone has solve the problem without being forced to use cowplot (or any other gridarrange)?

Indeed, here is an example. I would like to show the different French regions separately in facets but with their own x/y limits.

The result without scales = "free"

Scales are calculated with the extent of the entire map.

```<code>FRA <- raster::getData(name = "GADM", country = "FRA", level = 1)
FRA_sf <- st_as_sf(FRA)

g <- ggplot(FRA_sf) +
  geom_sf() +
  facet_wrap(~NAME_1)
</code>```

The result using cowplot

I need to use a list of ggplots and can then combine them.
This is the targeted output. It is cleaner. But I also want a clean way to add a legend. (I know may have a common legend like in this other SO question :
facet wrap distorts state maps in R)

```<code>g <- purrr::map(FRA_sf$NAME_1,
           function(x) {
             ggplot() +
               geom_sf(data = filter(FRA_sf, NAME_1 == x)) +
               guides(fill = FALSE) +
               ggtitle(x)
           })

g2 <- cowplot::plot_grid(plotlist = g)
</code>```

答:
I know you are looking for a solution using ggplot2, but I found the tmap package could be a choice depends on your need. The syntax of tmap is similar to ggplot2, it can also take sf object. Take your FRA_sf as an example, we can do something like this.

```<code>library(tmap)

tm_shape(FRA_sf) +
  tm_borders() +
  tm_facets(by = "NAME_1")
</code>```

Or we can use geom_spatial from the ggspatial package, but geom_spatial only takes Spatial* object.

```<code>library(ggplot2)
library(ggspatial)

ggplot() +
  geom_spatial(FRA) + # FRA is a SpatialPolygonsDataFrame object
  facet_wrap(~NAME_1, scales = "free")
</code>```

Body:
First, I am aware of this answer : Mapping different states in R using facet wrap

But I work with object of library sf.

It seems that facet_wrap(scales = "free") is not available for objects plotted with geom_sf in ggplot2. I get this message:

Erreur : Free scales are only supported with coord_cartesian() and
  coord_flip()

Is there any option I have missed ?

Anyone has solve the problem without being forced to use cowplot (or any other gridarrange)?

Indeed, here is an example. I would like to show the different French regions separately in facets but with their own x/y limits.

The result without scales = "free"

Scales are calculated with the extent of the entire map.

FRA <- raster::getData(name = "GADM", country = "FRA", level = 1)
FRA_sf <- st_as_sf(FRA)

g <- ggplot(FRA_sf) +
  geom_sf() +
  facet_wrap(~NAME_1)

The result using cowplot

I need to use a list of ggplots and can then combine them.
This is the targeted output. It is cleaner. But I also want a clean way to add a legend. (I know may have a common legend like in this other SO question :
facet wrap distorts state maps in R)

g <- purrr::map(FRA_sf$NAME_1,
           function(x) {
             ggplot() +
               geom_sf(data = filter(FRA_sf, NAME_1 == x)) +
               guides(fill = FALSE) +
               ggtitle(x)
           })

g2 <- cowplot::plot_grid(plotlist = g)

Body:
I know you are looking for a solution using ggplot2, but I found the tmap package could be a choice depends on your need. The syntax of tmap is similar to ggplot2, it can also take sf object. Take your FRA_sf as an example, we can do something like this.

library(tmap)

tm_shape(FRA_sf) +
  tm_borders() +
  tm_facets(by = "NAME_1")

Or we can use geom_spatial from the ggspatial package, but geom_spatial only takes Spatial* object.

library(ggplot2)
library(ggspatial)

ggplot() +
  geom_spatial(FRA) + # FRA is a SpatialPolygonsDataFrame object
  facet_wrap(~NAME_1, scales = "free")


问:
How to group mysql data by unique data range
I want to create a sql query for this right side output from left side data, as shown in the image below:

This is the query I have so far, but it isn't getting the correct results:

```<code>SELECT CONCAT(MONTH(Date),?Last day of month,YEAR(date)) AS Date,
       SUM(Amount1) AS rslt1,
       SUM(Amount2) AS rslt2
FROM table
GROUP BY MONTH(date), YEAR(date)
</code>```

答:
For example...</p>

```<code>SELECT ym
     , @a1 := @a1 + a1 amount1
     , @a2 := @a2 + a2 amount2
  FROM
     ( SELECT DATE_FORMAT(date,'%Y-%m') ym
            , SUM(amount1) a1
            , SUM(amount2) a2
         FROM my_table
        GROUP
           BY ym
     ) x
     , (SELECT @a1:=0,@a2:=0) vars
 ORDER
    BY ym;
</code>```

Body:
I want to create a sql query for this right side output from left side data, as shown in the image below:

This is the query I have so far, but it isn't getting the correct results:

SELECT CONCAT(MONTH(Date),?Last day of month,YEAR(date)) AS Date,
       SUM(Amount1) AS rslt1,
       SUM(Amount2) AS rslt2
FROM table
GROUP BY MONTH(date), YEAR(date)

Body:
For example...

SELECT ym
     , @a1 := @a1 + a1 amount1
     , @a2 := @a2 + a2 amount2
  FROM
     ( SELECT DATE_FORMAT(date,'%Y-%m') ym
            , SUM(amount1) a1
            , SUM(amount2) a2
         FROM my_table
        GROUP
           BY ym
     ) x
     , (SELECT @a1:=0,@a2:=0) vars
 ORDER
    BY ym;


问:
Dummy partition for grand total
fellow developers and analysts

I have a seemingly simple question where I would like to sum with a group by but ALSO a column which displays the grand total, i.e. same numerical value for each row. The caveat is that I do not want to use any join.

I am thinking some sort of dummy partition:

```<code>SELECT     Region
          ,sum(sales)
          ,sum(sales) OVER (partition by)
FROM      table
GROUP BY  1
</code>```

but, of course, this did not work. I am using Impala. I hope you can help me with this. Look forward to your replies.

答:
Just Increase the scope of the summary function (don't partition)</p>

```<code>SELECT *
        ,SUM([EXAMPLE]) OVER(PARTITION BY FOO ORDER BY BAR DESC) AS [TOTAL]
        ,SUM([EXAMPLE]) OVER() AS [Grand_Total]
            FROM ...
</code>```

Title: Dummy partition for grand total

Body:
fellow developers and analysts

I have a seemingly simple question where I would like to sum with a group by but ALSO a column which displays the grand total, i.e. same numerical value for each row. The caveat is that I do not want to use any join.

I am thinking some sort of dummy partition:

SELECT     Region
          ,sum(sales)
          ,sum(sales) OVER (partition by)
FROM      table
GROUP BY  1

but, of course, this did not work. I am using Impala. I hope you can help me with this. Look forward to your replies.

Body:
Just Increase the scope of the summary function (don't partition)

SELECT *
        ,SUM([EXAMPLE]) OVER(PARTITION BY FOO ORDER BY BAR DESC) AS [TOTAL]
        ,SUM([EXAMPLE]) OVER() AS [Grand_Total]
            FROM ...


问:
Native mongodb connection for node.js with promises
I am running node.js express app on IIS with iisnode and i am having the following problem,

i got a file for the mongo repository

```<code>var MongoClient = require('mongodb').MongoClient;
var url = MY_URL;
var db = null;

MongoClient.connect(url, function(err, database) {
    db = database
})

var repository = {};

repository.getAll = getAll;

module.exports = repository;

function getAll(collectionName)
{
    return new Promise(
        function(resolve, reject){
            db.collection(collectionName).find().toArray(function(err, res) {
                if (err) reject(err);
                resolve(res);
            });
    });
}
</code>```

Sometimes when i am trying to access the getAll function from a http get request i am getting an error

```<code>"Cannot read property 'collection' of null"
</code>```

It happens because db is null.

But when i call it again it always returns the values.

Is it possible that the getAll function is being activated before the connection is being setup?
Or maybe the first call awakes the connection in some way?

It is hard for me to work on the problem since i cant reproduce it in a controlled manner. It usually happens after not using the app for a while ( it seems that sometimes restarting the IIS also triggers it ).

答:
MongoClient.connect returns promise. So does getAll.

To ensure db always exists by the time you try to find something there you need to chain the promises. With few other bits fixed it could be:

```<code>const MongoClient = require('mongodb').MongoClient;
const url = MY_URL;
const dbConnected = MongoClient.connect(url); // it is a promise, db is not connected yet

function getAll(collectionName)
{
    return dbConnected.then(db => // the connection promise resolved, we are good to use db
        db.collection(collectionName).find().toArray() // it returns promise, no need to wrap it with another one
    );
}

module.exports = {getAll};
</code>```

Body:
I am running node.js express app on IIS with iisnode and i am having the following problem,

i got a file for the mongo repository

var MongoClient = require('mongodb').MongoClient;
var url = MY_URL;
var db = null;

MongoClient.connect(url, function(err, database) {
    db = database
})

var repository = {};

repository.getAll = getAll;

module.exports = repository;

function getAll(collectionName)
{
    return new Promise(
        function(resolve, reject){
            db.collection(collectionName).find().toArray(function(err, res) {
                if (err) reject(err);
                resolve(res);
            });
    });
}

Sometimes when i am trying to access the getAll function from a http get request i am getting an error

"Cannot read property 'collection' of null"

It happens because db is null.

But when i call it again it always returns the values.

Is it possible that the getAll function is being activated before the connection is being setup?
Or maybe the first call awakes the connection in some way?

It is hard for me to work on the problem since i cant reproduce it in a controlled manner. It usually happens after not using the app for a while ( it seems that sometimes restarting the IIS also triggers it ).

Body:
MongoClient.connect returns promise. So does getAll.

To ensure db always exists by the time you try to find something there you need to chain the promises. With few other bits fixed it could be:

const MongoClient = require('mongodb').MongoClient;
const url = MY_URL;
const dbConnected = MongoClient.connect(url); // it is a promise, db is not connected yet

function getAll(collectionName)
{
    return dbConnected.then(db => // the connection promise resolved, we are good to use db
        db.collection(collectionName).find().toArray() // it returns promise, no need to wrap it with another one
    );
}

module.exports = {getAll};


问:
post BOOL to JSON using AFNetworking 3.X ObjectiveC
AFNetworking don't want to represent BOOL value as true/false in JSON request. Tried @YES, NSNumber but no chance, it converts to 0 or 1.

```<code>NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setValue:@YES forKey:@"favorite"];

NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:data forKey:@"data"];
</code>```

then giving this param dictionary to AfNetworking 3

```<code>AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

manager.requestSerializer = serializer;

[manager POST:@"HTTPS://JSON URL" parameters:params progress:^(NSProgress *uploadProgress) {
} success:^(NSURLSessionDataTask * task, id responseObject) {
//SUCCESS
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//FAILED REQUEST
}];
</code>```

答:
This is how I've been toggling booleans, then sending them as JSON booleans using AFNetworking:

```<code>    self.petActive = ! self.petActive;
    NSNumber* newFMPstate = self.petActive ? @YES : @NO;
    NSDictionary *fmpDict = @{ @"petActive": newFMPstate };
    /// ... assemble endpoint for put and pass it fmpDict
</code>```

@YES and @NO respectively generate this JSON

```<code>{"petActive":true}
{"petActive":false}
</code>```

(I know the ternary operator is redundant, but it seems to add readability)

Body:
AFNetworking don't want to represent BOOL value as true/false in JSON request. Tried @YES, NSNumber but no chance, it converts to 0 or 1.

NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setValue:@YES forKey:@"favorite"];

NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:data forKey:@"data"];

then giving this param dictionary to AfNetworking 3

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

manager.requestSerializer = serializer;

[manager POST:@"HTTPS://JSON URL" parameters:params progress:^(NSProgress *uploadProgress) {
} success:^(NSURLSessionDataTask * task, id responseObject) {
//SUCCESS
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//FAILED REQUEST
}];

Body:
This is how I've been toggling booleans, then sending them as JSON booleans using AFNetworking:

    self.petActive = ! self.petActive;
    NSNumber* newFMPstate = self.petActive ? @YES : @NO;
    NSDictionary *fmpDict = @{ @"petActive": newFMPstate };
    /// ... assemble endpoint for put and pass it fmpDict

@YES and @NO respectively generate this JSON

{"petActive":true}
{"petActive":false}

(I know the ternary operator is redundant, but it seems to add readability)


问:
How to read integers elegantly using C++ stream?
I have a file full of lines in this format:

```<code>1 - 2: 3
</code>```

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

答:
Simply,</p>

```<code>ifstream file("file.txt");
int n1, n2, n3;
char tmp;
while (file.good()) {
  file >> n1 >> tmp >> n2 >> tmp >> n3;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a file full of lines in this format:

1 - 2: 3

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

Body:
Simply,

ifstream file("file.txt");
int n1, n2, n3;
char tmp;
while (file.good()) {
  file >> n1 >> tmp >> n2 >> tmp >> n3;
}


问:
Spring Controller double validation for @ModelAttribute object
I have implemented controller with method:

```<code>public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria criteria){...}
</code>```

It works. EventsCriteria did not have special separate validator for itself, because it has inner annotation checkers like @NotNull @NotEmpty. Right now situation is changed and it's not enough to have only this validators. so I've added and registered correspond service to verify some sates.

I want service to verify additional composite cases and single validation like before. But my single inner annotation checkers like @NotNull @NotEmpty do not work any more.

Am I configured something incorrectly or it can't work in in same time(specified service and inner checkers)?

My validator example (as it was asked in comments)

There are nothing special, if you know spring, so I missed this part like unimportant to concentrate your attention on my question.

```<code>@Component
public class EventsCriteriaValidator implements Validator {

    public static final String INVALID_RAGE_PARAMETERS_SPECIFIED = "Invalid rage parameters: please specify " +
            "'from' and 'to' or page 'size";

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(EventsCriteria.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria toValidate = (EventsCriteria) target;
        validateComplexRestriction(toValidate, errors);
    }

    private void validateComplexRestriction(EventsCriteria toValidate, Errors errors) {
        if (toValidate.isRangeEmpty() && toValidate.getSize() == 0) {
            errors.rejectValue(SIZE_FIELD, null, INVALID_RAGE_PARAMETERS_SPECIFIED);
        }
    }

}
</code>```

答:
Let assume that your EventsCriteria contains two fields so inside your validate method you can validate those field using : ValidationUtils (org.springframework.validation.ValidationUtils)

```<code> @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria eventsCriteria= (EventsCriteria) target;
        ValidationUtils.rejectIfEmpty(errors, "field1", "eventsCriteria.field1.empty");
        ValidationUtils.rejectIfEmpty(errors, "field2", "eventsCriteria.field2.empty");
    }
</code>```

and in your messages.properties

```<code>eventsCriteria.field1.empty = Enter a valid value for field 1.
eventsCriteria.field2.empty = Enter a valid value for field 2.
</code>```

and in your configuration class add this bean:

```<code> @Bean
   public MessageSource messageSource() {
      ResourceBundleMessageSource source = new ResourceBundleMessageSource();
      source.setBasename("messages");
      return source;
   }
</code>```

Body:
I have implemented controller with method:

public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria criteria){...}

It works. EventsCriteria did not have special separate validator for itself, because it has inner annotation checkers like @NotNull @NotEmpty. Right now situation is changed and it's not enough to have only this validators. so I've added and registered correspond service to verify some sates.

I want service to verify additional composite cases and single validation like before. But my single inner annotation checkers like @NotNull @NotEmpty do not work any more.

Am I configured something incorrectly or it can't work in in same time(specified service and inner checkers)?

My validator example (as it was asked in comments)

There are nothing special, if you know spring, so I missed this part like unimportant to concentrate your attention on my question.

@Component
public class EventsCriteriaValidator implements Validator {

    public static final String INVALID_RAGE_PARAMETERS_SPECIFIED = "Invalid rage parameters: please specify " +
            "'from' and 'to' or page 'size";

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(EventsCriteria.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria toValidate = (EventsCriteria) target;
        validateComplexRestriction(toValidate, errors);
    }

    private void validateComplexRestriction(EventsCriteria toValidate, Errors errors) {
        if (toValidate.isRangeEmpty() && toValidate.getSize() == 0) {
            errors.rejectValue(SIZE_FIELD, null, INVALID_RAGE_PARAMETERS_SPECIFIED);
        }
    }

}

Body:
Let assume that your EventsCriteria contains two fields so inside your validate method you can validate those field using : ValidationUtils (org.springframework.validation.ValidationUtils)

 @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria eventsCriteria= (EventsCriteria) target;
        ValidationUtils.rejectIfEmpty(errors, "field1", "eventsCriteria.field1.empty");
        ValidationUtils.rejectIfEmpty(errors, "field2", "eventsCriteria.field2.empty");
    }

and in your messages.properties

eventsCriteria.field1.empty = Enter a valid value for field 1.
eventsCriteria.field2.empty = Enter a valid value for field 2.

and in your configuration class add this bean:

 @Bean
   public MessageSource messageSource() {
      ResourceBundleMessageSource source = new ResourceBundleMessageSource();
      source.setBasename("messages");
      return source;
   }


问:
Policy has invalid action - AWS S3
I'm trying to set up a policy on my S3 bucket, but I'm recieving an error. The error also does not tell me where to look for issues. I saw a similar post here, but since I'm not using IAM roles, I don't believe it's pertinent.

I generated my bucket's policy directly from Amazon's Policy Generator. Here is my policy:

```<code>{
  "Id": "Policy1512577467217",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1512577462905",
      "Action": [
        "s3:GetObject",
        "s3:ListAllMyBuckets",
        "s3:ListBucket",
        "s3:ListObjects"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::please-work-god/*",
      "Principal": "*"
    }
  ]
}
</code>```

When I try to save the policy, I see the following message:

Error: Policy has invalid action

Any help would be greatly appreciated.

答:
S3 bucket policy Actions are different from IAM policy actions. Following actions are not allowed in Bucket policy, which is the reason for the error.

s3:ListAllMyBuckets

s3:ListObjects

For the  s3:ListBucket action it requires the arn to have the bucket name as suffix but not /*

You can go through Specifying Permissions in a Policy actions for bucket policies.

Title: Policy has invalid action - AWS S3

Body:
I'm trying to set up a policy on my S3 bucket, but I'm recieving an error. The error also does not tell me where to look for issues. I saw a similar post here, but since I'm not using IAM roles, I don't believe it's pertinent.

I generated my bucket's policy directly from Amazon's Policy Generator. Here is my policy:

{
  "Id": "Policy1512577467217",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1512577462905",
      "Action": [
        "s3:GetObject",
        "s3:ListAllMyBuckets",
        "s3:ListBucket",
        "s3:ListObjects"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::please-work-god/*",
      "Principal": "*"
    }
  ]
}

When I try to save the policy, I see the following message:

Error: Policy has invalid action

Any help would be greatly appreciated.


问:
PHP Pthreads - Threads not running parallel
When I run the following code, the individual Threads seems to be executed in sequence, one at the time. I was expecting them to run in parallel. Is there something wrong with my code, or shall I start to look at my environment? I am running Apache, PHP 7 on a Windows machine.

```<code><?php
class Searcher extends Worker
{
    public $data = [];

    public function addData($data)
    {
        $this->data[] = $data;
    }
}

class MyThread extends Threaded
{
    public function __construct($param)
    {
        $this->param = $param;
    }

    public function run()
    {
        sleep(3);
        $this->worker->addData(
            $this->param." - TIME: ".microtime(true)
        );
    }
}

$worker   = new Searcher();
$params = ['thread1', 'thread2', 'thread3', 'thread4', 'thread5', 'thread6', 'thread7'];

foreach ($params as &$param) {
    $worker->stack(new MyThread($param));
}

$worker->start();
$worker->join();

foreach ($worker->data as $data) {
    echo $data."<br/>";
}

?>
</code>```

The output of the code above always becomes something like this:

```<code>thread1 - TIME: 1512249412.3757
thread2 - TIME: 1512249415.7776
thread3 - TIME: 1512249419.1792
thread4 - TIME: 1512249422.5813
thread5 - TIME: 1512249425.9825
thread6 - TIME: 1512249429.384
thread7 - TIME: 1512249432.7859
</code>```

答:
OK, I got it now.

A Worker does not run all stacked threads in parallel, they are executed one at the time.

To run all the jobs at the same time, one must use a Pool.

Body:
When I run the following code, the individual Threads seems to be executed in sequence, one at the time. I was expecting them to run in parallel. Is there something wrong with my code, or shall I start to look at my environment? I am running Apache, PHP 7 on a Windows machine.

<?php
class Searcher extends Worker
{
    public $data = [];

    public function addData($data)
    {
        $this->data[] = $data;
    }
}

class MyThread extends Threaded
{
    public function __construct($param)
    {
        $this->param = $param;
    }

    public function run()
    {
        sleep(3);
        $this->worker->addData(
            $this->param." - TIME: ".microtime(true)
        );
    }
}

$worker   = new Searcher();
$params = ['thread1', 'thread2', 'thread3', 'thread4', 'thread5', 'thread6', 'thread7'];

foreach ($params as &$param) {
    $worker->stack(new MyThread($param));
}

$worker->start();
$worker->join();

foreach ($worker->data as $data) {
    echo $data."
";
}

?>

The output of the code above always becomes something like this:

thread1 - TIME: 1512249412.3757
thread2 - TIME: 1512249415.7776
thread3 - TIME: 1512249419.1792
thread4 - TIME: 1512249422.5813
thread5 - TIME: 1512249425.9825
thread6 - TIME: 1512249429.384
thread7 - TIME: 1512249432.7859


问:
Move git project from local to remote, how?
I'd like to move my current git porject from local machine to remote machine.
All development I will do at my local machine. So I have to have ability to checkout branches from remote machine to my local via git://

What shoud I do to make git:// protocol working on my remote machine? How can I protect it from being connected from third party?

Thank you

答:
You know Git runs over SSH by default? It would be much easier on you to use this secure functionality that's already there.

Set up a git ssh account on your remote machine and then store your repository where you like. Then set the origin in .git to be the location of your repo, eg. ssh://git@yourhost/var/git/repolocation

From here you can "git clone", "git push", "git pull" the repo as you wish.


问:
Sorted post-condition doesn't hold
What I want to do in the method is simply to overwrite the previous array and fill it with number that are sorted, however dafny says that the post-condition does not hold and I can't for the life of me figure out why.
I'm guessing I need to add some invariant to the loop but since they are checked before entering the loop I don't know how to put a valid invariant.

```<code>method sort2(a : array<int>)
modifies a;
requires a != null && a.Length >= 2;
ensures sorted2(a[..]);
{
  var i := a.Length - 1;
  while (i >= 0)
  decreases i
 {
     a[i] := i;
     i := i - 1;
 }
}

predicate sorted2(s: seq<int>)
{
    forall i :: 1 <= i < |s| ==> s[i] >= s[i-1]
}
</code>```

My previous attempt was just to reinitialize a but dafny apparently doesn't allow that inside methods.

答:
You do need a loop invariant in order to prove this program correct.

See Section 6 of the Dafny Tutorial for a general introduction to loop invariants and how to come up with them.

In this case, a good loop invariant will be something like sorted(a[i+1..]), which says that the part of the array after index i is sorted. That way, when the loop terminates and i is zero, you'll know that the whole array is sorted.

You will also need one or two more loop invariants describing bounds on i and the elements of the array itself.

Title: Sorted post-condition doesn't hold

Body:
What I want to do in the method is simply to overwrite the previous array and fill it with number that are sorted, however dafny says that the post-condition does not hold and I can't for the life of me figure out why.
I'm guessing I need to add some invariant to the loop but since they are checked before entering the loop I don't know how to put a valid invariant.

method sort2(a : array<int>)
modifies a;
requires a != null && a.Length >= 2;
ensures sorted2(a[..]);
{
  var i := a.Length - 1;
  while (i >= 0)
  decreases i
 {
     a[i] := i;
     i := i - 1;
 }
}

predicate sorted2(s: seq<int>)
{
    forall i :: 1 <= i < |s| ==> s[i] >= s[i-1]
}

My previous attempt was just to reinitialize a but dafny apparently doesn't allow that inside methods.


问:
Cordova Camera App not launching
i have been trying to find out why does camera not launching when the image is click which make it as a button. Even when tried to reinstall the cordova camera plugin, the error still remain. Please Help......

function onDeviceReady() { <<<------ JS File
        $("#photo1").click(Camera1);
        detection();
    }
    function Camera1() {
        navigator.camera.getPicture(onSuccess, onFail, {
            quality: 50,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.CAMERA,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 300,
            targetHeight: 300,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        });
        function onSuccess(imageData) {
            var image = document.getElementById('myImage');
            image.src = "data:image/jpeg;base64," + imageData;
        }
        function onFail(message) {
            $("#errormsg").text("ERROR");
        }
    };

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body> <<<----- HTML File
    <div data-role="page" id="page1">
        <input type="image" id="photo1" src="images/download.png" width="200" height="90" />
        <label for="photo2">Take a Photo</label>
        <img id="myImage" src="" />
        <div id="errormsg"></div>
        <div id="displayresults"></div>
        <input type="image" id="fall" src="images/piq96Mxi9-800x675.jpg" width="200" height="90" />
        <label for="photo3">Fall Detection</label>
    </div>

    <div data-role="page" id="page2">
     <p id="lastphoto"></p>
        <button class="ui-btn">Send</button>
    </div>

    <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="scripts/platformOverrides.js"></script>
    <script type="text/javascript" src="scripts/index.js"></script>
</body>
</html></code>```

答:
Possible solutions are,

Download you JQuery offline, instead of loading on CDN (due to loading time dealy, error may happen)

Make sure, you're validating both JQuery ready + device ready event

Check your app permission for camera access

Title: Cordova Camera App not launching

Body:
i have been trying to find out why does camera not launching when the image is click which make it as a button. Even when tried to reinstall the cordova camera plugin, the error still remain. Please Help......

function onDeviceReady() { <<<------ JS File
        $("#photo1").click(Camera1);
        detection();
    }
    function Camera1() {
        navigator.camera.getPicture(onSuccess, onFail, {
            quality: 50,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.CAMERA,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 300,
            targetHeight: 300,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        });
        function onSuccess(imageData) {
            var image = document.getElementById('myImage');
            image.src = "data:image/jpeg;base64," + imageData;
        }
        function onFail(message) {
            $("#errormsg").text("ERROR");
        }
    };

        });

 <<<----- HTML File

        <input type="image" id="photo1" src="images/download.png" width="200" height="90" />
        Take a Photo

        <input type="image" id="fall" src="images/piq96Mxi9-800x675.jpg" width="200" height="90" />
        Fall Detection

        <button class="ui-btn">Send</button>


问:
Does Spring MVC support versioning of static assets (css, js and images )
Does Spring MVC support versioning of static assets (css, js and images )
by appending the last-modified-date to the asset file names which effectively serves,
caches, and invalidates the assets automatically ?

Rails supports this by using the asset_tag helpers.

I want to add the last-modified-date attribute of a file as a query parameter to serve static assets from the server,
so that if I modify the static files (css, js, images) I do not have to modify my code and cache invalidation can happen automatically.

thank you

答: Yes, check the spring MVC documentation, section 17.15.6 Configuring Serving of Resources


问:
Unity/C# Adding two areas represented by two vectors
I have two areas, which are both given in there bounds.size. Now the z-axis doesnt matter for me, since im working in 2D. I want to add these vectors so i have a vector, which represents the jointed area. Simply adding these vectors the normal way does not work. The way the area looks in the end is not important, its just important that the size is the same as, both areas combined.

Edit: I have the bounds.size of two polygoncolliders and i want to get a value that represents the bounds.size of the two polygoncolliders combined

area 1 and area 2 combined

答:
The way the area looks in the end is not important, its just important that the size is the same as, both areas combined.

As there are nigh infinite possibilities otherwise, I'm going to limit myself to results where x = y, for the simple reason that you don't end up with silly vectors like (0.5,80000) but rather a more balanced (200,200).

This isn't all that hard when you look at it algebraically:

```<code>float result_area = first_area + second_area;
</code>```

Calculating the area is easy:

```<code>float area = myVector.X * myVector.Y;
</code>```

Thus rendering the sum of the areas also easy:

```<code>float result_area = myFirstVector.X * myFirstVector.Y + mySecondVector.X * mySecondVector.Y;
</code>```

For the sake of example, let's say first_area = 50 and second_area = 350, thus resulting in result_area = 400;

Since we are limited to results where x = y, the result is the square root of the area:

```<code>float theSquareRoot = Math.Sqrt(result_area);
myResultVector.X = theSquareRoot;
myResultVector.Y = theSquareRoot;
</code>```

As I said, there are many other possible result vectors. For other cases, you're either going to have to define a given ratio (e.g. a ratio of 1 : 4 would give you (10,40) for the same example), but the calculation is a bit harder and you mentioned that you don't care about the exact shape anyway.

You could also just make a vector where X = result_area and Y = 1 (or vice versa), without having to calculate a square root.

Note that you've overengineered it. The area of an object is a onedimensional value (a number); yet you're expressing it using a twodimensional value (a number pair) to represent them.

Since you don't care about particular X/Y values, only what their product is, I would suggest you avoid vectors where possible, so you don't make it unnecessarily complicated.

Body:
The way the area looks in the end is not important, its just important that the size is the same as, both areas combined.

As there are nigh infinite possibilities otherwise, I'm going to limit myself to results where x = y, for the simple reason that you don't end up with silly vectors like (0.5,80000) but rather a more balanced (200,200).

This isn't all that hard when you look at it algebraically:

float result_area = first_area + second_area;

Calculating the area is easy:

float area = myVector.X * myVector.Y;

Thus rendering the sum of the areas also easy:

float result_area = myFirstVector.X * myFirstVector.Y + mySecondVector.X * mySecondVector.Y;

For the sake of example, let's say first_area = 50 and second_area = 350, thus resulting in result_area = 400;

Since we are limited to results where x = y, the result is the square root of the area:

float theSquareRoot = Math.Sqrt(result_area);
myResultVector.X = theSquareRoot;
myResultVector.Y = theSquareRoot;

As I said, there are many other possible result vectors. For other cases, you're either going to have to define a given ratio (e.g. a ratio of 1 : 4 would give you (10,40) for the same example), but the calculation is a bit harder and you mentioned that you don't care about the exact shape anyway.

You could also just make a vector where X = result_area and Y = 1 (or vice versa), without having to calculate a square root.

Note that you've overengineered it. The area of an object is a onedimensional value (a number); yet you're expressing it using a twodimensional value (a number pair) to represent them.

Since you don't care about particular X/Y values, only what their product is, I would suggest you avoid vectors where possible, so you don't make it unnecessarily complicated.


问:
which is better to get rid of undefined
How to get ride of undefined in single condition?

```<code> var test;
 // the value of test may be null, undefined,0,1,true,false,or any other string
 if(!test){
  // it fails when test =true;
 }

 if(!!test){
 // it fails when test =0;
 }
</code>```

Is there any other way to satisfy all theses cases in single condition

答:
To check if the variable test is not defined and is not null the code should look like this:

```<code>var test;

if (typeof test !== 'undefined' && test !== null) {
   console.log('the variable *test* is not defined and is not null');
}
</code>```

Title: which is better to get rid of undefined

Body:
How to get ride of undefined in single condition?

 var test;
 // the value of test may be null, undefined,0,1,true,false,or any other string
 if(!test){
  // it fails when test =true;
 }

 if(!!test){
 // it fails when test =0;
 }

Is there any other way to satisfy all theses cases in single condition

Body:
To check if the variable test is not defined and is not null the code should look like this:

var test;

if (typeof test !== 'undefined' && test !== null) {
   console.log('the variable *test* is not defined and is not null');
}


问:
Maven3 plugin repository
Can anyone tell me why my Maven3 is not able to download the jetty plugin from http://repo.maven.apache.org/maven2/org/mortbay/jetty/jetty-maven-plugin/6.1.20/jetty-maven-plugin-6.1.20.pom ?

I have included the eviware and the jetty plugin also to automate the SOAP UI test cases.

It will be helpful if anyone can suggest me what I am doing wrong.

Thanks in advance.

答:
you can change the layout of the repository, some thing like this</p>

```<code><repository>
<id>CentralRepository</id>
<name>CentralRepository</name>
<url>http://repo.maven.apache.org/maven2/org/mortbay/jetty/</url>
<layout>version</layout>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</code>```

Title: Maven3 plugin repository

Body:
you can change the layout of the repository, some thing like this

<repository>
<id>CentralRepository</id>
<name>CentralRepository</name>
<url>http://repo.maven.apache.org/maven2/org/mortbay/jetty/</url>
<layout>version</layout>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>


问:
Check running status of a background process launched from same bash script
I have to write a bash script that launches a process in background in accordance to command line argument passed and returns if it were successfully able to run launch the program.

Here is a pseudo code of what I am trying to achieve

```<code>if [ "$1" = "PROG_1" ] ; then
    ./launchProg1 &
    if [ isLaunchSuccess ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
elif [ "$1" = "PROG_2" ] ; then
    ./launchProg2 &
    if [ isLaunchSuccess ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
fi
</code>```

Script cannot wait or sleep since it will be called by another mission critical c++ program and needs high throughput ( wrt no of processes started per second ) and moreover running time of processes are unknown.  Script neither needs to capture any input/output nor waits for launched process' completion.

I have unsuccessfully tried the following:

```<code>#Method 1
if [ "$1" = "KP1" ] ; then
    echo "The Arguement is KP1"
    ./kp 'this is text' &
    if [ $? = "0" ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
elif [ "$1" = "KP2" ] ; then
    echo "The Arguement is KP2"
    ./NoSuchCommand 'this is text' &
    if [ $? = "0" ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
#Method 2
elif [ "$1" = "CD5" ] ; then
    echo "The Arguement is CD5"
    cd "doesNotExist" &
    PROC_ID=$!
    echo "PID is $PROC_ID"
    if kill -0 "$PROC_ID" ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
#Method 3
elif [ "$1" = "CD6" ] ; then
    echo "The Arguement is CD6"
    cd .. &
    PROC_ID=$!
    echo "PID is $PROC_ID"
    ps -eo pid | grep "$PROC_ID" && { echo "Success"; exit 0; }
    ps -eo pid | grep  "$PROC_ID" || { echo "failed" ; exit 1; }
else
    echo "Unknown Argument"
    exit 1
fi
</code>```

Running the script gives unreliable output. Method 1, 2 always return Success while Method 3 returns failed when process execution finishes before the checks.

Here is sample tested on GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) and GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

```<code>[scripts]$ ./processStarted3.sh KP1
The Arguement is KP1
Success
[scripts]$ ./processStarted3.sh KP2
The Arguement is KP2
Success
./processStarted3.sh: line 13: ./NoSuchCommand: No such file or directory
[scripts]$ ./processStarted3.sh CD6
The Arguement is CD6
PID is 25050
failed
</code>```

As suggested in similar questions, I cannot use process names as one process may be executed several times and others can't be applied.

I have not tried screen and tmux, since getting permission to install them on production servers wont be easy ( but will do so if that is the only option left )

UPDATE

@ghoti

./kp is program which exists and launching the program returns Success. ./NoSuchCommand does not exist. Still as you can see from (edited) output, script incorrectly returns Success.

It does not matter when the process completes execution or program abnormally terminates. Programs launched via script are not tracked in any way ( hence we do not store pid in any table nor necessity arises to use deamontools ).

@Etan Reisner

Example of a program which fails to launch will be ./NoSuchCommand,which does not exist. Or maybe a corrupted program which fails to start.

@Vorsprung

Calling a script which launches a program in background does not take alot of time ( and is manageable as per our expectations). But sleep 1 will accumulate over time to cause issues.

Aforementioned #Method3 works fine barring processes which terminate before ps -eo pid | grep "$PROC_ID" && { echo "Success"; exit 0; } check can be performed.

答:
The accepted answer doesn't work as advertised.

The count in this check will always be at least 1 because "grep $pid" will find both the process with $pid if it exists and the grep.

```<code>count=$(ps -A| grep $pid |wc -l)
if [[ $count -eq 0 ]]
then
    ### We can never get here
else
    echo "success"  #process is still running
fi
</code>```

Changing the above to check for a count of 1 or excluding the grep from the count should make the original work.

Here is an alternate (maybe simpler) implementation of the original example.

```<code>#!/bin/bash
$1 & # executes a program in background which is provided as an argument
pid=$! # stores executed process id in pid

# check whether process is still running
# The "[^[]" excludes the grep from finding itself in the ps output
if ps | grep "$pid[^[]" >/dev/null
then
    echo "success (running)"  # process is still running
else
    # If the process is already terminated, then there are 2 cases:
    # 1) the process executed and stop successfully
    # 2) it is terminated abnormally

    if wait $pid # check if process executed successfully or not
    then
        echo "success (ran)"
    else
        echo "failed (returned $?)" # process terminated abnormally
    fi
fi

# Note: The above script will detect if a process started successfully or not. If process is running when we check, but later it terminates abnormally then this script will not detect this.
</code>```

Body:
I have to write a bash script that launches a process in background in accordance to command line argument passed and returns if it were successfully able to run launch the program.

Here is a pseudo code of what I am trying to achieve

if [ "$1" = "PROG_1" ] ; then
    ./launchProg1 &
    if [ isLaunchSuccess ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
elif [ "$1" = "PROG_2" ] ; then
    ./launchProg2 &
    if [ isLaunchSuccess ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
fi

Script cannot wait or sleep since it will be called by another mission critical c++ program and needs high throughput ( wrt no of processes started per second ) and moreover running time of processes are unknown.  Script neither needs to capture any input/output nor waits for launched process' completion.

I have unsuccessfully tried the following:

#Method 1
if [ "$1" = "KP1" ] ; then
    echo "The Arguement is KP1"
    ./kp 'this is text' &
    if [ $? = "0" ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
elif [ "$1" = "KP2" ] ; then
    echo "The Arguement is KP2"
    ./NoSuchCommand 'this is text' &
    if [ $? = "0" ] ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
#Method 2
elif [ "$1" = "CD5" ] ; then
    echo "The Arguement is CD5"
    cd "doesNotExist" &
    PROC_ID=$!
    echo "PID is $PROC_ID"
    if kill -0 "$PROC_ID" ; then
        echo "Success"
    else
        echo "failed"
        exit 1
    fi
#Method 3
elif [ "$1" = "CD6" ] ; then
    echo "The Arguement is CD6"
    cd .. &
    PROC_ID=$!
    echo "PID is $PROC_ID"
    ps -eo pid | grep "$PROC_ID" && { echo "Success"; exit 0; }
    ps -eo pid | grep  "$PROC_ID" || { echo "failed" ; exit 1; }
else
    echo "Unknown Argument"
    exit 1
fi

Running the script gives unreliable output. Method 1, 2 always return Success while Method 3 returns failed when process execution finishes before the checks.

Here is sample tested on GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) and GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

[scripts]$ ./processStarted3.sh KP1
The Arguement is KP1
Success
[scripts]$ ./processStarted3.sh KP2
The Arguement is KP2
Success
./processStarted3.sh: line 13: ./NoSuchCommand: No such file or directory
[scripts]$ ./processStarted3.sh CD6
The Arguement is CD6
PID is 25050
failed

As suggested in similar questions, I cannot use process names as one process may be executed several times and others can't be applied.

I have not tried screen and tmux, since getting permission to install them on production servers wont be easy ( but will do so if that is the only option left )

UPDATE

@ghoti

./kp is program which exists and launching the program returns Success. ./NoSuchCommand does not exist. Still as you can see from (edited) output, script incorrectly returns Success.

It does not matter when the process completes execution or program abnormally terminates. Programs launched via script are not tracked in any way ( hence we do not store pid in any table nor necessity arises to use deamontools ).

@Etan Reisner

Example of a program which fails to launch will be ./NoSuchCommand,which does not exist. Or maybe a corrupted program which fails to start.

@Vorsprung

Calling a script which launches a program in background does not take alot of time ( and is manageable as per our expectations). But sleep 1 will accumulate over time to cause issues.

Aforementioned #Method3 works fine barring processes which terminate before ps -eo pid | grep "$PROC_ID" && { echo "Success"; exit 0; } check can be performed.

Body:
The accepted answer doesn't work as advertised.

The count in this check will always be at least 1 because "grep $pid" will find both the process with $pid if it exists and the grep.

count=$(ps -A| grep $pid |wc -l)
if [[ $count -eq 0 ]]
then
    ### We can never get here
else
    echo "success"  #process is still running
fi

Changing the above to check for a count of 1 or excluding the grep from the count should make the original work.

Here is an alternate (maybe simpler) implementation of the original example.

#!/bin/bash
$1 & # executes a program in background which is provided as an argument
pid=$! # stores executed process id in pid

# check whether process is still running
# The "[^[]" excludes the grep from finding itself in the ps output
if ps | grep "$pid[^[]" >/dev/null
then
    echo "success (running)"  # process is still running
else
    # If the process is already terminated, then there are 2 cases:
    # 1) the process executed and stop successfully
    # 2) it is terminated abnormally

    if wait $pid # check if process executed successfully or not
    then
        echo "success (ran)"
    else
        echo "failed (returned $?)" # process terminated abnormally
    fi
fi

# Note: The above script will detect if a process started successfully or not. If process is running when we check, but later it terminates abnormally then this script will not detect this.


问:
TextView instead of icon in navigation drawer
Im trying to change the icon to TextView and color it's background.
Actually i have icon on the left side of item, and the text with colored background on the right, using android:actionLayout.

And i want to delete the icon on the left side, and place there a text with colored background which i have currently on right side.

Any possibility?

答:
I think you might need to create your own Navigation drawer adapter. Check answers in this thread to understand how to do it.

How to create a custom navigation drawer in android


问:
Properly getting Electron cookies (asynchronous)
I think I have a good understanding of what asynchronous means in JavaScript.

I am well aware that I can use something like callback functions to modify variables from asynchronous functions.

I am not, however, sure how to use this with the cookies in Electron.

What I mean is, I can get the cookie by doing:

```<code>function getCookie( name ) {

    // 'ses' refers to 'mainWindow.webContents.session'
    ses.cookies.get({name: name}, function(err, cookie) {
        if ( err ) throw err;
        console.log(cookie[0].value);
    });

}
</code>```

I can easily output the cookie to the console. However, since this is asynchronous, I don't know how to set any variables.

How can I achieve this? How do I set a variable form inside the 'cookies.get' method, since I can not use callbacks?

答:
You might try the use of a global variable:</p>

```<code>var cookieLoaded = false;
function getCookie( name ) {
    // 'ses' refers to 'mainWindow.webContents.session'
    ses.cookies.get({name: name}, function(err, cookie) {
        if ( err ) throw err;
        console.log(cookie[0].value);
        cookieLoaded = true;
    });
}

//in other parts of the code...
//you probably want this to be in events, like click handlers, etc.

if (cookieLoaded) {
  //DO STUFF
} else {
  alert('You are not authenticated');
  //or, disable buttons, etc.
}
</code>```

Body:
I think I have a good understanding of what asynchronous means in JavaScript.

I am well aware that I can use something like callback functions to modify variables from asynchronous functions.

I am not, however, sure how to use this with the cookies in Electron.

What I mean is, I can get the cookie by doing:

function getCookie( name ) {

    // 'ses' refers to 'mainWindow.webContents.session'
    ses.cookies.get({name: name}, function(err, cookie) {
        if ( err ) throw err;
        console.log(cookie[0].value);
    });

}

I can easily output the cookie to the console. However, since this is asynchronous, I don't know how to set any variables.

How can I achieve this? How do I set a variable form inside the 'cookies.get' method, since I can not use callbacks?

Body:
You might try the use of a global variable:

var cookieLoaded = false;
function getCookie( name ) {
    // 'ses' refers to 'mainWindow.webContents.session'
    ses.cookies.get({name: name}, function(err, cookie) {
        if ( err ) throw err;
        console.log(cookie[0].value);
        cookieLoaded = true;
    });
}

//in other parts of the code...
//you probably want this to be in events, like click handlers, etc.

if (cookieLoaded) {
  //DO STUFF
} else {
  alert('You are not authenticated');
  //or, disable buttons, etc.
}


问:
Difference between self and private method call in R6
Lately I found myself coding some stuff in R6, and while having fun handling some objects an interesting question came out. When creating a private method (e.g. foo, of the bar) and calling it inside other public methods it works if I either call it using:

```<code>self$foo
</code>```

and

```<code>private$foo
</code>```

What I am asking is: what is the difference between those two ways of calling a method in R6?
Thank you in advance!

答:
From the "Introduction to R6 classes" vignette (emphasis mine):

self

Inside methods of the class, self refers to the object. Public members of the object (all you’ve seen so far) are accessed with self$x

private

Whereas public members are accessed with self, like self$add(), private members are accessed with private, like private$queue.

So, even if you can access private methods through self, you should do it through private. Don't rely on behavior which may go away, seeing as how the documentation says it shouldn't work like that.

That said, I can't access private methods using self:

```<code>library(R6)

bar <- R6Class("bar",
  private = list(
    foo = function() {
      message("just foo it")
    }
  ),
  public = list(
    call_self = function() {
      self$foo()
    },
    call_private = function() {
      private$foo()
    }
  )
)

b <- bar$new()
b$call_private()
# just foo it
b$call_self()
# Error in b$call_self() : attempt to apply non-function
</code>```

Body:
Lately I found myself coding some stuff in R6, and while having fun handling some objects an interesting question came out. When creating a private method (e.g. foo, of the bar) and calling it inside other public methods it works if I either call it using:

self$foo

and

private$foo

What I am asking is: what is the difference between those two ways of calling a method in R6?
Thank you in advance!

Body:
From the "Introduction to R6 classes" vignette (emphasis mine):

self

Inside methods of the class, self refers to the object. Public members of the object (all you’ve seen so far) are accessed with self$x

private

Whereas public members are accessed with self, like self$add(), private members are accessed with private, like private$queue.

So, even if you can access private methods through self, you should do it through private. Don't rely on behavior which may go away, seeing as how the documentation says it shouldn't work like that.

That said, I can't access private methods using self:

library(R6)

bar <- R6Class("bar",
  private = list(
    foo = function() {
      message("just foo it")
    }
  ),
  public = list(
    call_self = function() {
      self$foo()
    },
    call_private = function() {
      private$foo()
    }
  )
)

b <- bar$new()
b$call_private()
# just foo it
b$call_self()
# Error in b$call_self() : attempt to apply non-function


问:
Deploy Node.js RestFull API to Heroku
I have a school assignment where i must build a node.js server (Without Express) that receives a POST request containing {day: 25, month:12, year:2017} and sends the number of days remaining to that date.

I was able to solve this using moment npm package (https://www.npmjs.com/package/moment)

The server is listening on port 3000.

The code works perfectly when i send a post request to 127.0.0.1:3000

However, i changed listen port to 80, created a new app on heroku and then deployed my code and it doesn't work anymore, heroku says application crash.

Does anyone have an idea ?

server is created like this :

```<code>var http = require('http');
var moment = require('moment');
moment().format();

var server = http.createServer(function(request, response) {
    ....
});
server.listen(80);
</code>```

答:
Heroku uses the process.env of nodeJS. In order to make sure your app works on heroku you should set the an variable called port that takes either port 3000 / 80 for local app and process.env.PORT for heroku deployments.

```<code>const port = process.env.PORT || 3000
</code>```

Hope that helped!

Title: Deploy Node.js RestFull API to Heroku

Body:
I have a school assignment where i must build a node.js server (Without Express) that receives a POST request containing {day: 25, month:12, year:2017} and sends the number of days remaining to that date.

I was able to solve this using moment npm package (https://www.npmjs.com/package/moment)

The server is listening on port 3000.

The code works perfectly when i send a post request to 127.0.0.1:3000

However, i changed listen port to 80, created a new app on heroku and then deployed my code and it doesn't work anymore, heroku says application crash.

Does anyone have an idea ?

server is created like this :

var http = require('http');
var moment = require('moment');
moment().format();

var server = http.createServer(function(request, response) {
    ....
});
server.listen(80);

Body:
Heroku uses the process.env of nodeJS. In order to make sure your app works on heroku you should set the an variable called port that takes either port 3000 / 80 for local app and process.env.PORT for heroku deployments.

const port = process.env.PORT || 3000

Hope that helped!


问:
Does Spark dataset.write() result in the rows being collected at the driver node?
I am trying to fine tune the performance a spark job that writes the results of a processed data set (on cluster) to the HDFS and also to a relational database. I am using dataset.write().jdbc() and dataset.write().csv() methods respectively. I am wondering if these methods will result in all the rows being collected to the driver node, thus impacting the performance of the job ?</p>

答: No, Each executor writes its own RDD unless you use collect or coalesce in your code.


问:
How to save button value to databse in django?
I'm trying to create my first django app - sports predictions game.

I want user to select from three possible results using 3 buttons (images) which pass 3 different values to the db:

1 - home team wins

0 - draw

2 - away team wins

I am able to save data using forms when I type something into it, but how do I pass value of these buttons to my database?

code on my game.html:

```<code>{% csrf_token %}

{{ form }}
<input type="submit" value = 1>
<input type="submit" value = 0>
<input type="submit" value = 2> </form>
</code>```

and my view:

```<code>def game(request, Game_id):
    thisgame = get_object_or_404(Game, pk=Game_id)
    nextgame = int(thisgame.id)+1
    template = loader.get_template('polls/game.html')
    form = NewBetForm(request.POST or None)
    current_user = request.user

    allgames = Game.objects.all()
    betchoices = BetChoice.objects.all()

    context = { 'thisgame': thisgame,
                'nextgame': nextgame,
                'form': form,
                'current_user': current_user,
                'betchoices': betchoices,}

    if form.is_valid():
        bet = form.save(commit=False)
        bet.gameid = Game.objects.get(id=Game_id)
        bet.userid_id = current_user.id
        bet.save()
    else:
        print (form.errors)
</code>```

and my form:

```<code>class NewBetForm(forms.ModelForm):
    class Meta:
        model = GameBet
        fields = ['bet']
</code>```

and the error I get is Bet - this field is required

Thank you for all ideas!

答: As with any other type of form field, a submit button needs a name attribute before it will send any data to the backend. From there, you can just pick up its value via request.POST['whatever_the_name_is'] and assign it to your newly created object - or, if you use the name that is already a field in the form, it will be assigned automatically.

Body:
I'm trying to create my first django app - sports predictions game.

I want user to select from three possible results using 3 buttons (images) which pass 3 different values to the db:

1 - home team wins

0 - draw

2 - away team wins

I am able to save data using forms when I type something into it, but how do I pass value of these buttons to my database?

code on my game.html:

{% csrf_token %}

{{ form }}
<input type="submit" value = 1>
<input type="submit" value = 0>
<input type="submit" value = 2> </form>

and my view:

def game(request, Game_id):
    thisgame = get_object_or_404(Game, pk=Game_id)
    nextgame = int(thisgame.id)+1
    template = loader.get_template('polls/game.html')
    form = NewBetForm(request.POST or None)
    current_user = request.user

    allgames = Game.objects.all()
    betchoices = BetChoice.objects.all()

    context = { 'thisgame': thisgame,
                'nextgame': nextgame,
                'form': form,
                'current_user': current_user,
                'betchoices': betchoices,}

    if form.is_valid():
        bet = form.save(commit=False)
        bet.gameid = Game.objects.get(id=Game_id)
        bet.userid_id = current_user.id
        bet.save()
    else:
        print (form.errors)

and my form:

class NewBetForm(forms.ModelForm):
    class Meta:
        model = GameBet
        fields = ['bet']

and the error I get is Bet - this field is required

Thank you for all ideas!


问:
customize google map's InfoWindow
I want to completely customize the infowindow in google maps v3? I just want to show a image there, No white rounded background with arrow.

Is it possible in v3? or any workaround?

Something like this

答:
take a look at the sources of this example - completely customized info window (Google Map API v3 is used).

I found that example on Google Map API v3 Group - "Custom InfoWindow examples" - just in case you will need more info

Title: customize google map's InfoWindow