问:
Generic method and JSON
I wrote generic method which returns list of some objects, for example Orders. My question is why in second, non-generic method it returns correct list of Orders and the first method (generic) returns list of linkedHashMaps instead of Orders?

Generic:

```<code> private <T> List<T> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<T>> mapType = new TypeReference<List<T>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}
</code>```

Non-generic:

```<code>private List<Order> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<Order>> mapType = new TypeReference<List<Order>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}
</code>```

Generic method returns that:
LinkedHashMap

答:
Because in the non generic method you have explicitly said that you are adding Order.

And in the generic one you are sending back objects, which are essentialy of type Order.

In any case both of it will return List.

Title: Generic method and JSON

Body:
I wrote generic method which returns list of some objects, for example Orders. My question is why in second, non-generic method it returns correct list of Orders and the first method (generic) returns list of linkedHashMaps instead of Orders?

Generic:

 private <T> List<T> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<T>> mapType = new TypeReference<List<T>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}

Non-generic:

private List<Order> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<Order>> mapType = new TypeReference<List<Order>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}

Generic method returns that:
LinkedHashMap


来源: stackexchange

问:
Generating all possible combinations inefficient
Code to generate all possible combinations of a list of numbers and fetch combinations  with a particular sum:

```<code>combos = []

for each in combinations_with_replacement(list, number):
    if sum(list(map(int, each))) == particular_number:
        combos.append(list(map(int, each)))
</code>```

the code is working perfectly fine. But the problem is if the number argument in the function combinations_with_replacement is more than 8 it is taking a lot of time. Is there a optimized way my logic can be replaced with?

答:
First of all, quit repeating work.

Convert the list elements to integers before you enter the loop.

The combination is already in a tuple; do you really need to convert it to a list for combos?

Instead of generating all combinations for a variety of list lengths, try the recursive solution you can find with a "sum to target" search.  This will greatly reduce the quantity of lists to try.

The basic idea of the recursive solution is:

```<code># Given: remaining target sum and list of numbers (lon) to use
if target = 0:
    return []
if target < 0 or len(lon) == 0:
    return None

if target >= lon[0]:
    # add one of the first number; recur
    result = sum_to_target(target - lon[0], lon)
    return result + [lon[0]] if result else None

# Done with this number; try the rest of the list
result = sum_to_target(target, lon[1:])
return result if result else None
</code>```

Try every step both with and without the first number of the list.
If you exceed the target or run out of numbers, you fail.
If you hit the target exactly, you succeed: build the valid set of numbers as you crawl back up the call stack.

Note that I've left the problem of concatenating all solutions as an exercise for you ... as well as some debugging and boundary details.

ContentLicense: CC BY-SA 3.0

Body:
Code to generate all possible combinations of a list of numbers and fetch combinations  with a particular sum:

combos = []

for each in combinations_with_replacement(list, number):
    if sum(list(map(int, each))) == particular_number:
        combos.append(list(map(int, each)))

the code is working perfectly fine. But the problem is if the number argument in the function combinations_with_replacement is more than 8 it is taking a lot of time. Is there a optimized way my logic can be replaced with?

Body:
First of all, quit repeating work.

Convert the list elements to integers before you enter the loop.

The combination is already in a tuple; do you really need to convert it to a list for combos?

Instead of generating all combinations for a variety of list lengths, try the recursive solution you can find with a "sum to target" search.  This will greatly reduce the quantity of lists to try.

The basic idea of the recursive solution is:

# Given: remaining target sum and list of numbers (lon) to use
if target = 0:
    return []
if target < 0 or len(lon) == 0:
    return None

if target >= lon[0]:
    # add one of the first number; recur
    result = sum_to_target(target - lon[0], lon)
    return result + [lon[0]] if result else None

# Done with this number; try the rest of the list
result = sum_to_target(target, lon[1:])
return result if result else None

Try every step both with and without the first number of the list.
If you exceed the target or run out of numbers, you fail.
If you hit the target exactly, you succeed: build the valid set of numbers as you crawl back up the call stack.

Note that I've left the problem of concatenating all solutions as an exercise for you ... as well as some debugging and boundary details.


问:
GNU ARM Eclipse: how to simulate pin input?
I want to pass sine wave data onto a pin (any possible one), so that my program would be able to read it when being run in an emulator.

How how can I pass data in the form of (time:value) or just pass a function float generatorForPinX(int time); to act as signal generator into the GNU ARM Eclipse (I use QEMU but if any other emulator is required I am willing to migrate) board emulator?

答:
These instructions are for emulating an Olimex STM32 P103 Development Kit.

Download and build

First download and build Qemu STM32, which includes patches for emulating the ADC peripheral on the STM32:

```<code>wget https://github.com/beckus/qemu_stm32/archive/stm32.tar.gz
tar xf stm32.tar.gz
cd qemu_stm32-stm32
./configure --target-list="arm-softmmu"
make
cd ..
</code>```

If the configure step fails, then install the missing requirements. See the README for more information.

Then download the Olimex STM32 P103 Development Kit Demos:

```<code>wget https://github.com/beckus/stm32_p103_demos/archive/master.tar.gz
tar xf master.tar.gz
</code>```

Look in stm32_p103_demos-master/demos/adc_single/main.c for an example program which uses the ADC.

Run the demo application

To build and run the adc_single demo:

```<code>cd stm32_p103_demos-master
QEMU_ARM_DIR=../qemu_stm32-stm32/arm-softmmu/ make adc_single_QEMURUN_TEL
(from another terminal) telnet localhost 7777
</code>```

UART2 is attached to the telnet server on port 7777, which you should see output from. See the README for more information on how to build and run the demo applications.

Looking at the source for the adc_single demo application, it has 3 different modes:

Mode 1 (the default) will read from the temperature sensor on ADC channel 16

Mode 2 will read the Vdd value from ADC channel 16

Mode 3 will read from ADC channel 8.

The modes can be selected by using a button, but since we are emulating the hardware with QEMU, the button is not available. I switched between the modes by changing the int mode = 1; value and recompiling the program.

ADC emulation

The method that QEMU uses to emulate each ADC channel is viewable in the stm32_adc_start_conv function in hw/arm/stm32_adc.c:

```<code>static void stm32_adc_start_conv(Stm32Adc *s)
{
    uint64_t curr_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
    int channel_number=stm32_ADC_get_channel_number(s,1);
    // Write result of conversion
    if(channel_number==16){
        s->Vdda=rand()%(1200+1) + 2400; //Vdda belongs to the interval [2400 3600] mv
        s->Vref=rand()%(s->Vdda-2400+1) + 2400; //Vref belongs to the interval [2400 Vdda] mv
        s->ADC_DR= s->Vdda - s->Vref;
    }
    else if(channel_number==17){
        s->ADC_DR= (s->Vref=rand()%(s->Vdda-2400+1) + 2400); //Vref [2400 Vdda] mv
    }
    else{
        s->ADC_DR=((int)(1024.*(sin(2*M_PI*qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)/1e9)+1.))&0xfff);
    }
    s->ADC_SR&=~ADC_SR_EOC;  // jmf : indicates ongoing conversion
    // calls conv_complete when expires
    timer_mod(s->conv_timer,  curr_time + stm32_ADC_get_nbr_cycle_per_sample(s,channel_number));
}
</code>```

As you can see, ADC channel 16 will emulate a random Vdd input, ADC channel 17 will emulate a random temperature input, and all other channels will follow a sine wave from 0 to 2048. Here is a graph of the ADC values returned from all 3 modes:

If you want to have an ADC channel use a different emulation pattern, you can modify stm32_adc_start_conv and rebuild QEMU following the steps above.

Body:
These instructions are for emulating an Olimex STM32 P103 Development Kit.

Download and build

First download and build Qemu STM32, which includes patches for emulating the ADC peripheral on the STM32:

wget https://github.com/beckus/qemu_stm32/archive/stm32.tar.gz
tar xf stm32.tar.gz
cd qemu_stm32-stm32
./configure --target-list="arm-softmmu"
make
cd ..

If the configure step fails, then install the missing requirements. See the README for more information.

Then download the Olimex STM32 P103 Development Kit Demos:

wget https://github.com/beckus/stm32_p103_demos/archive/master.tar.gz
tar xf master.tar.gz

Look in stm32_p103_demos-master/demos/adc_single/main.c for an example program which uses the ADC.

Run the demo application

To build and run the adc_single demo:

cd stm32_p103_demos-master
QEMU_ARM_DIR=../qemu_stm32-stm32/arm-softmmu/ make adc_single_QEMURUN_TEL
(from another terminal) telnet localhost 7777

UART2 is attached to the telnet server on port 7777, which you should see output from. See the README for more information on how to build and run the demo applications.

Looking at the source for the adc_single demo application, it has 3 different modes:

Mode 1 (the default) will read from the temperature sensor on ADC channel 16

Mode 2 will read the Vdd value from ADC channel 16

Mode 3 will read from ADC channel 8.

The modes can be selected by using a button, but since we are emulating the hardware with QEMU, the button is not available. I switched between the modes by changing the int mode = 1; value and recompiling the program.

ADC emulation

The method that QEMU uses to emulate each ADC channel is viewable in the stm32_adc_start_conv function in hw/arm/stm32_adc.c:

static void stm32_adc_start_conv(Stm32Adc *s)
{
    uint64_t curr_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
    int channel_number=stm32_ADC_get_channel_number(s,1);
    // Write result of conversion
    if(channel_number==16){
        s->Vdda=rand()%(1200+1) + 2400; //Vdda belongs to the interval [2400 3600] mv
        s->Vref=rand()%(s->Vdda-2400+1) + 2400; //Vref belongs to the interval [2400 Vdda] mv
        s->ADC_DR= s->Vdda - s->Vref;
    }
    else if(channel_number==17){
        s->ADC_DR= (s->Vref=rand()%(s->Vdda-2400+1) + 2400); //Vref [2400 Vdda] mv
    }
    else{
        s->ADC_DR=((int)(1024.*(sin(2*M_PI*qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)/1e9)+1.))&0xfff);
    }
    s->ADC_SR&=~ADC_SR_EOC;  // jmf : indicates ongoing conversion
    // calls conv_complete when expires
    timer_mod(s->conv_timer,  curr_time + stm32_ADC_get_nbr_cycle_per_sample(s,channel_number));
}

As you can see, ADC channel 16 will emulate a random Vdd input, ADC channel 17 will emulate a random temperature input, and all other channels will follow a sine wave from 0 to 2048. Here is a graph of the ADC values returned from all 3 modes:

If you want to have an ADC channel use a different emulation pattern, you can modify stm32_adc_start_conv and rebuild QEMU following the steps above.


问:
Error Page - how to print stack trace in JSP
I've created exception handling in my Spring application using spring SimpleMappingExceptionResolver. Everything works fine. Now I need to somehow print the caught exception within the jsp page. Something like message and stack trace. In my jsp I've found the exception object in "exception" attribute. All I need to do is something like that:

```<code>${exception.printStackTrace()}
</code>```

But I don't know how. Is there any way how to do that?:-)

Thanks for any suggestion,

Mateo

答:
The easiest solution I can think of is to loop over the stack trace elements, taking advantage of the Throwable.getStackTrace() method:

```<code><c:forEach items="${exception.stackTrace}" var="element">
    <c:out value="${element}" />
</c:forEach>
</code>```

You'd need to add some formatting, of course.

ContentLicense: CC BY-SA 2.5

Body:
I've created exception handling in my Spring application using spring SimpleMappingExceptionResolver. Everything works fine. Now I need to somehow print the caught exception within the jsp page. Something like message and stack trace. In my jsp I've found the exception object in "exception" attribute. All I need to do is something like that:

${exception.printStackTrace()}

But I don't know how. Is there any way how to do that?:-)

Thanks for any suggestion,

Mateo

Body:
The easiest solution I can think of is to loop over the stack trace elements, taking advantage of the Throwable.getStackTrace() method:

<c:forEach items="${exception.stackTrace}" var="element">
    <c:out value="${element}" />
</c:forEach>

You'd need to add some formatting, of course.


问:
How to exclude a button in a dynamically generated page from refreshing with other contents
Please guys i need your ever reliable assistance in fixing this:
I have a page which loads users comments from database with ajax and a setInterval function used to
refresh the page every 5 seconds. Each comment displays with a dynamically generated reply button underneath
that fades out to reveal reply textarea field upon clicking.
What i'm trying to achieve is to exclude the button from refreshing alongside the contents every 5 seconds.
This is because when the reply button is clicked and the reply textarea is revealed for reply to be typed, at 5
seconds the page refreshes, the textarea closes and the button returns.
Here is my fetch_posts.php file:

```<code>    <?php
    require ("includes/conn.php");
                $stmt=$conn->prepare("SELECT post_id, name, topic, post, time FROM posts ORDER BY time DESC");
                $stmt->execute();
                $result = $stmt->get_result();
                $num_of_rows = $result->num_rows;
                if ($num_of_rows > 0){
                    while ($row = $result->fetch_assoc()){
                        $id = $row['post_id'];
                        $name = $row['name'];
                        $topic = $row['topic'];
                        $post = $row['post'];
                        $time = strtotime($row['time']);
                        $time = date('d M, H:i a', $time);
            ?>
                    <div class="col-md-1">
                        <img src="images/human_avtr.png" alt="image" width="50px" height="50px" background="#FC6806">
                    </div>
                    <div class="col-md-11">
                        <h5 style="color:#FC6806"><strong><?php echo ucfirst($name); ?></strong></h5><h6 style="color:#FC6806"><?php echo $time; ?></h6>
                        <h5 style="color:#0269C2"><strong><?php echo ucfirst($topic); ?></strong></h5>
                        <p><?php echo $post; ?></p>
                    </div>
                    <div class="row col-md-offset-2 col-xs-offset-2">
                        <button type="button" class="btn btn-primary" id="reply_button">Reply</button>
                    </div>
                    <div class="row reply_txt" style="clear:both">
                        <div class="col-md-6 col-md-offset-1" id="rep_fields">
                            <textarea class="form-control" id="comment_reply" rows="3"></textarea><br/>
                            <button type="submit" class="btn btn-primary" id="send_reply">Reply Comment</button>
                            <button type="submit" class="btn btn-danger" id="cancel_reply">Cancel</button>
                        </div>
                    </div>
          <?php }
                }
           ?>
<script>
     $(".reply_txt").hide();
</script>
</code>```

And here my jquery to fade out the post reply button, reveal the reply textarea, fetch data and set the SetInterval function.

```<code> $(document).on("click", "button#reply_button", function(e){
            e.preventDefault();
            var reply_button = $(this).closest('div');
            var reply_field = reply_button.next(".reply_txt");
            $(reply_button).fadeOut();
            $(reply_field).fadeIn();
        });
function fetchPosts(){
        $.ajax({
            url: "fetch_posts.php",
            type: "POST",
            data: {},
            success: function(data){
                $("#show_comments").html(data);
                 fetchPosts();
            }
        });
    }
    setInterval(fetchPosts, 5000);
</code>```

答:
I would recommend rewriting your code to have fetch_posts.php return a JSON String of the post information and have the $.ajax success function create the HTML for the posts. This way you're passing less data between the server and client, and you can use Javascript to parse the data by ID and append new posts, rather than overwrite all existing ones. I would even go as far as having the $.ajax request tell fetch_posts.php what the most recent post is and change the MySQL query to only pull newer posts.

EDIT to help with getting started coding:

PHP could be rewritten to export a JSON string instead of HTML:

```<code><?php
require ("includes/conn.php");
$stmt=$conn->prepare("SELECT post_id, name, topic, post, time FROM posts ORDER BY time DESC");
$stmt->execute();
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
if ($num_of_rows > 0){
    $dataArray = [];
    while ($row = $result->fetch_assoc()){
        $data['post_id'] = $row['post_id'];
        $data['name'] = $row['name'];
        $data['topic'] = $row['topic'];
        $data['post'] = $row['post'];
        $data['time'] = date('d M, H:i a', strtotime($row['time']));
        $dataArray[] = $data;
    }
    echo json_encode($dataArray);
}
?>
</code>```

and have javascript parse it (create the HTML string):

```<code>$(document).on("click", "button#reply_button", function(e){
    e.preventDefault();
    var reply_button = $(this).closest('div');
    var reply_field = reply_button.next(".reply_txt");
    $(reply_button).fadeOut();
    $(reply_field).fadeIn();
});
function fetchPosts(){
    $.ajax({
        url: "fetch_posts.php",
        type: "POST",
        data: {},
        success: function(data){
            var jsonData = JSON.parse(data);
            // This will return an object like this:
            // {0: {post_id: '', name: '', ...}, 1: {post_id: '', name: '', ...}}
            // You can then use these objects in your javascript.
            $.each(data, function(post) {
                // FIRST check if the post_id is already in the posts:
                if ( !$("#posts_list").children("div[data-id=" + post.post_id + "]").exists() ) {
                    var thePostHTML = "<div data-id=\"" + post.post_id + "\">"; // etc...
                    $("#posts_list").append(thePostHTML);
                }
            });
        $("#show_comments").html(data);
        fetchPosts();
        }
    });
}
setInterval(fetchPosts, 5000);
</code>```

Body:
Please guys i need your ever reliable assistance in fixing this:
I have a page which loads users comments from database with ajax and a setInterval function used to
refresh the page every 5 seconds. Each comment displays with a dynamically generated reply button underneath
that fades out to reveal reply textarea field upon clicking.
What i'm trying to achieve is to exclude the button from refreshing alongside the contents every 5 seconds.
This is because when the reply button is clicked and the reply textarea is revealed for reply to be typed, at 5
seconds the page refreshes, the textarea closes and the button returns.
Here is my fetch_posts.php file:

    <?php
    require ("includes/conn.php");
                $stmt=$conn->prepare("SELECT post_id, name, topic, post, time FROM posts ORDER BY time DESC");
                $stmt->execute();
                $result = $stmt->get_result();
                $num_of_rows = $result->num_rows;
                if ($num_of_rows > 0){
                    while ($row = $result->fetch_assoc()){
                        $id = $row['post_id'];
                        $name = $row['name'];
                        $topic = $row['topic'];
                        $post = $row['post'];
                        $time = strtotime($row['time']);
                        $time = date('d M, H:i a', $time);
            ?>

<?php echo ucfirst($name); ?>

<?php echo $time; ?>

<?php echo ucfirst($topic); ?>

<?php echo $post; ?>

                        <button type="button" class="btn btn-primary" id="reply_button">Reply</button>

                            <textarea class="form-control" id="comment_reply" rows="3"></textarea>

                            <button type="submit" class="btn btn-primary" id="send_reply">Reply Comment</button>
                            <button type="submit" class="btn btn-danger" id="cancel_reply">Cancel</button>

          <?php }
                }
           ?>

And here my jquery to fade out the post reply button, reveal the reply textarea, fetch data and set the SetInterval function.

 $(document).on("click", "button#reply_button", function(e){
            e.preventDefault();
            var reply_button = $(this).closest('div');
            var reply_field = reply_button.next(".reply_txt");
            $(reply_button).fadeOut();
            $(reply_field).fadeIn();
        });
function fetchPosts(){
        $.ajax({
            url: "fetch_posts.php",
            type: "POST",
            data: {},
            success: function(data){
                $("#show_comments").html(data);
                 fetchPosts();
            }
        });
    }
    setInterval(fetchPosts, 5000);

Body:
I would recommend rewriting your code to have fetch_posts.php return a JSON String of the post information and have the $.ajax success function create the HTML for the posts. This way you're passing less data between the server and client, and you can use Javascript to parse the data by ID and append new posts, rather than overwrite all existing ones. I would even go as far as having the $.ajax request tell fetch_posts.php what the most recent post is and change the MySQL query to only pull newer posts.

EDIT to help with getting started coding:

PHP could be rewritten to export a JSON string instead of HTML:

<?php
require ("includes/conn.php");
$stmt=$conn->prepare("SELECT post_id, name, topic, post, time FROM posts ORDER BY time DESC");
$stmt->execute();
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
if ($num_of_rows > 0){
    $dataArray = [];
    while ($row = $result->fetch_assoc()){
        $data['post_id'] = $row['post_id'];
        $data['name'] = $row['name'];
        $data['topic'] = $row['topic'];
        $data['post'] = $row['post'];
        $data['time'] = date('d M, H:i a', strtotime($row['time']));
        $dataArray[] = $data;
    }
    echo json_encode($dataArray);
}
?>

and have javascript parse it (create the HTML string):

$(document).on("click", "button#reply_button", function(e){
    e.preventDefault();
    var reply_button = $(this).closest('div');
    var reply_field = reply_button.next(".reply_txt");
    $(reply_button).fadeOut();
    $(reply_field).fadeIn();
});
function fetchPosts(){
    $.ajax({
        url: "fetch_posts.php",
        type: "POST",
        data: {},
        success: function(data){
            var jsonData = JSON.parse(data);
            // This will return an object like this:
            // {0: {post_id: '', name: '', ...}, 1: {post_id: '', name: '', ...}}
            // You can then use these objects in your javascript.
            $.each(data, function(post) {
                // FIRST check if the post_id is already in the posts:
                if ( !$("#posts_list").children("div[data-id=" + post.post_id + "]").exists() ) {
                    var thePostHTML = "<div data-id=\"" + post.post_id + "\">"; // etc...
                    $("#posts_list").append(thePostHTML);
                }
            });
        $("#show_comments").html(data);
        fetchPosts();
        }
    });
}
setInterval(fetchPosts, 5000);


问:
Mongoose.js instance.save() callback not firing
```<code>var mongo = require('mongoose');
var connection = mongo.createConnection('mongodb://127.0.0.1/test');

connection.on("error", function(errorObject){
  console.log(errorObject);
  console.log('ONERROR');
});

var Schema = mongo.Schema;
var BookSchema = new Schema({ title : {type : String, index : {unique : true}}});
var BookModel = mongo.model('abook', BookSchema);
var b = new BookModel({title : 'aaaaaa'});

b.save( function(e){
  if(e){
    console.log('error')
  }else{
    console.log('no error')
}});
</code>```

Neither the 'error', or 'no error' are printed to the terminal. What's more the connection.on 'error' doesn't seem to fire either. I have confirmed that MongoDb is running.

答:
The posted answer does not solve the problem. Unfortunately, I cannot just upgrade my database, so that is not a solution either for me. But here I found a solution to this problem: https://github.com/Automattic/mongoose/issues/4064

Just use .$__save instead of .save as shown:

```<code>var b = new BookModel({title : 'aaaaaa'});

b.$__save({}, function(e){
  if(e){
    console.log('error')
    // callback will show if e exists
  }else{
    console.log('no error')
    // callback will show 'no error'
}});
</code>```

Body:
var mongo = require('mongoose');
var connection = mongo.createConnection('mongodb://127.0.0.1/test');

connection.on("error", function(errorObject){
  console.log(errorObject);
  console.log('ONERROR');
});

var Schema = mongo.Schema;
var BookSchema = new Schema({ title : {type : String, index : {unique : true}}});
var BookModel = mongo.model('abook', BookSchema);
var b = new BookModel({title : 'aaaaaa'});

b.save( function(e){
  if(e){
    console.log('error')
  }else{
    console.log('no error')
}});

Neither the 'error', or 'no error' are printed to the terminal. What's more the connection.on 'error' doesn't seem to fire either. I have confirmed that MongoDb is running.

Body:
The posted answer does not solve the problem. Unfortunately, I cannot just upgrade my database, so that is not a solution either for me. But here I found a solution to this problem: https://github.com/Automattic/mongoose/issues/4064

Just use .$__save instead of .save as shown:

var b = new BookModel({title : 'aaaaaa'});

b.$__save({}, function(e){
  if(e){
    console.log('error')
    // callback will show if e exists
  }else{
    console.log('no error')
    // callback will show 'no error'
}});


问:
Creating a new hash with default keys
I want to create a hash with an index that comes from an array.

```<code>ary = ["a", "b", "c"]
h = Hash.new(ary.each{|a| h[a] = 0})
</code>```

My goal is to start with a hash like this:

```<code>h = {"a"=>0, "b"=>0, "c"=>0}
</code>```

so that later when the hash has changed I can reset it with h.default

Unfortunately the way I'm setting up the hash is not working... any ideas?

答:
Alternate way of having a hash with the keys actually added</p>

```<code>Hash[[:a, :b, :c].zip([])] # => {:a=>nil, :b=>nil, :c=>nil}

Hash[[:a, :b, :c].zip(Array.new(3, 0))] # => {:a=>0, :b=>0, :c=>0}
</code>```

Title: Creating a new hash with default keys

Body:
I want to create a hash with an index that comes from an array.

ary = ["a", "b", "c"]
h = Hash.new(ary.each{|a| h[a] = 0})

My goal is to start with a hash like this:

h = {"a"=>0, "b"=>0, "c"=>0}

so that later when the hash has changed I can reset it with h.default

Unfortunately the way I'm setting up the hash is not working... any ideas?

Body:
Alternate way of having a hash with the keys actually added

Hash[[:a, :b, :c].zip([])] # => {:a=>nil, :b=>nil, :c=>nil}

Hash[[:a, :b, :c].zip(Array.new(3, 0))] # => {:a=>0, :b=>0, :c=>0}


问:
Unexpected token < in JSON at position Ionic
I'm working on a project using Ionic 2 framework, but I'm getting an error of Unexpected token < in JSON at position 0 home.ts:37, whenever I submit a form input into my  MySQL database. I have checked my ports, all working fine. What could be causing the issue?

full error

```<code>SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.es5.js:800)
    at MapSubscriber.project (service.ts:28)
    at MapSubscriber._next (map.js:77)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.es5.js:1229)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4119)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)
</code>```

launch.json

```<code>    {

    "version": "0.2.0",
    "configurations": [

        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${file}",
            "outFiles": [
                "${workspaceRoot}/out/**/*.js"
            ]
        }
    ]
}
</code>```

Here's my code:

home.html

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      Agregar producto
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="insertar" (ngSubmit)="InsertarProducto()">
            <ion-list>
                  <ion-item>
                        <ion-label floating>nombre</ion-label>
                        <ion-input type="text" name="nombre" formControlName="nombre" ></ion-input>
                  </ion-item>
                  <ion-item>
                        <ion-label floating>stock</ion-label>
                        <ion-input type="text" name="stock" formControlName="stock" ></ion-input>
                  </ion-item>
                      <button  [disabled]="insertar.invalid" ion-button full block color="secondary">Enviar</button>
            </ion-list>
  </form>

</ion-content>
</code>```

home.ts

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ServiceProvider } from '../../providers/service/service';
import { FormBuilder, Validators } from '@angular/forms';
import { ToastController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  insertar : any = {};

  constructor(public navCtrl: NavController , public service : ServiceProvider, public formB : FormBuilder,  public toastCtrl: ToastController)
  {

            this.insertar = this.formB.group({
             nombre:['', Validators.required],
             stock:['', Validators.required]
            });
   }

   InsertarProducto(){

      /*let toast = this.toastCtrl.create({
      message: 'Usuario agregado correctamente',
      duration: 3000
    });*/

    this.service.InsertarProd(this.insertar.value)
    .subscribe(
      data=> console.log(data.mensage), //toast.present()
      err=> console.log(err));
  }

}
</code>```

service.ts

```<code>import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Http , Headers, Response} from '@angular/http';
//import { Observable } from "rxjs/Observable";

/*
  Generated class for the ServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ServiceProvider {

    api : string = 'http://localhost:8080/ING/';

  constructor(public http: Http) {
    console.log('Hello ServiceProvider Provider');
  }

   InsertarProd(params){
             let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
           return this.http.post(this.api + 'insertarprod.php' , params,{
           headers:headers,
           method:"POST",
         }).map(
           (res:Response)=>{return res.json();}
         )
  }

}
</code>```

insertarprod.php

```<code><?php

header("Access-Control-Allow-Origin:http://localhost:8100");
header("Content-Type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    $data = file_get_contents("php://input");
    $objData = json_decode($data);

    $nombre = $objData->nombre;
    $stock = $objData->stock;

    $nombre = stripslashes($nombre);
    $stock = stripslashes($stock);

    $nombre = trim($nombre);
    $stock = trim($stock);

    $datos;

    @$db = new PDO("mysql:host=localhost;dbname=aula", "root", "");

    $prueba = array('mensaje2' => "conexion correcta");
    echo json_encode($prueba);

    if($db){
        $sql = " insert into productos values(NULL,'".$nombre."','".$stock."')";
        $query = $db->prepare($sql);
        $query ->execute();
        if(!$query){
                   $datos = array('mensage' => "no fue posible insertar datos");
                   echo json_encode($datos);
         }
        else{
                   $datos = array('mensage' => "Datos ingresados correctamente");
                  echo json_encode($datos);
         };
    }
   else{
          $datos = array('mensage' => "No es posible insertar datos.");
          echo json_encode($datos);
    };

    ?>
</code>```

答:
Your json is valid except the comment:
https://jsonlint.com/
See: Can comments be used in JSON? about comments in json files.</p>

Body:
I'm working on a project using Ionic 2 framework, but I'm getting an error of Unexpected token < in JSON at position 0 home.ts:37, whenever I submit a form input into my  MySQL database. I have checked my ports, all working fine. What could be causing the issue?

full error

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.es5.js:800)
    at MapSubscriber.project (service.ts:28)
    at MapSubscriber._next (map.js:77)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.es5.js:1229)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4119)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)

launch.json

    {

    "version": "0.2.0",
    "configurations": [

        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${file}",
            "outFiles": [
                "${workspaceRoot}/out/**/*.js"
            ]
        }
    ]
}

Here's my code:

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Agregar producto
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="insertar" (ngSubmit)="InsertarProducto()">
            <ion-list>
                  <ion-item>
                        <ion-label floating>nombre</ion-label>
                        <ion-input type="text" name="nombre" formControlName="nombre" ></ion-input>
                  </ion-item>
                  <ion-item>
                        <ion-label floating>stock</ion-label>
                        <ion-input type="text" name="stock" formControlName="stock" ></ion-input>
                  </ion-item>
                      <button  [disabled]="insertar.invalid" ion-button full block color="secondary">Enviar</button>
            </ion-list>
  </form>

</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ServiceProvider } from '../../providers/service/service';
import { FormBuilder, Validators } from '@angular/forms';
import { ToastController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  insertar : any = {};

  constructor(public navCtrl: NavController , public service : ServiceProvider, public formB : FormBuilder,  public toastCtrl: ToastController)
  {

            this.insertar = this.formB.group({
             nombre:['', Validators.required],
             stock:['', Validators.required]
            });
   }

   InsertarProducto(){

      /*let toast = this.toastCtrl.create({
      message: 'Usuario agregado correctamente',
      duration: 3000
    });*/

    this.service.InsertarProd(this.insertar.value)
    .subscribe(
      data=> console.log(data.mensage), //toast.present()
      err=> console.log(err));
  }

}

service.ts

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Http , Headers, Response} from '@angular/http';
//import { Observable } from "rxjs/Observable";

/*
  Generated class for the ServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ServiceProvider {

    api : string = 'http://localhost:8080/ING/';

  constructor(public http: Http) {
    console.log('Hello ServiceProvider Provider');
  }

   InsertarProd(params){
             let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
           return this.http.post(this.api + 'insertarprod.php' , params,{
           headers:headers,
           method:"POST",
         }).map(
           (res:Response)=>{return res.json();}
         )
  }

}

insertarprod.php

<?php

header("Access-Control-Allow-Origin:http://localhost:8100");
header("Content-Type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    $data = file_get_contents("php://input");
    $objData = json_decode($data);

    $nombre = $objData->nombre;
    $stock = $objData->stock;

    $nombre = stripslashes($nombre);
    $stock = stripslashes($stock);

    $nombre = trim($nombre);
    $stock = trim($stock);

    $datos;

    @$db = new PDO("mysql:host=localhost;dbname=aula", "root", "");

    $prueba = array('mensaje2' => "conexion correcta");
    echo json_encode($prueba);

    if($db){
        $sql = " insert into productos values(NULL,'".$nombre."','".$stock."')";
        $query = $db->prepare($sql);
        $query ->execute();
        if(!$query){
                   $datos = array('mensage' => "no fue posible insertar datos");
                   echo json_encode($datos);
         }
        else{
                   $datos = array('mensage' => "Datos ingresados correctamente");
                  echo json_encode($datos);
         };
    }
   else{
          $datos = array('mensage' => "No es posible insertar datos.");
          echo json_encode($datos);
    };

    ?>


问:
Write some random numbers to the pipe?
my question is can I write an integer to pipe ? and how ?

I need to make 3 processes first one generate 2 numbers, second make sum of the numbers, third print the result (USING PIPE)

Thanks all

答:
The complicated part of what you're trying to do is creating the pipeline.  You could just have the shell do it for you...

```<code>$ ./makenumbers | ./addnumbers | ./printresult
</code>```

but that's boring, eh?  And you have to have three executables.  So let's have a look at what those vertical bars are doing at the C level.

You create a pipe with the pipe system call.  You reassign standard input/output with dup2.  You create new processes with fork, and you wait for them to terminate with waitpid.  A program to set the whole thing up would look something like this:

```<code>int
main(void)
{
    pid_t children[2];
    int pipe1[2], pipe2[2];
    int status;

    pipe(pipe1);
    pipe(pipe2);

    children[0] = fork();
    if (children[0] == 0)
    {
        /* in child 0 */
        dup2(pipe1[1], 1);
        generate_two_numbers_and_write_them_to_fd_1();
        _exit(0);
    }

    children[1] = fork();
    if (children[1] == 0)
    {
        /* in child 1 */
        dup2(pipe1[0], 0);
        dup2(pipe2[1], 1);
        read_two_numbers_from_fd_0_add_them_and_write_result_to_fd_1();
        _exit(0);
    }

    /* parent process still */
    dup2(pipe2[0], 0);
    read_a_number_from_fd_0_and_print_it();

    waitpid(children[0], &status, 0);
    waitpid(children[1], &status, 0);

    return 0;
}
</code>```

Please note:

I left out all error handling, because that would make the program about three times longer.  Your instructor wants you to include error handling.

Similarly, I left out checking the exit status of the children; your instructor also wants you to check that.

You do not need the dup2 calls; you could just pass the pipe fd numbers to the subroutine calls.  But if you were exec-ing a new binary in the child, which is more typical, you would need them.  You would then also have to worry about making sure all file descriptors numbered 3 and higher were closed.

There is a reason I am using _exit instead of exit.  Try to figure out what it is.

You need to use read and write instead of stdio.h calls in the subroutines called from child processes.  The reason is related to the reason I am using _exit.

Title: Write some random numbers to the pipe?

Body:
The complicated part of what you're trying to do is creating the pipeline.  You could just have the shell do it for you...

$ ./makenumbers | ./addnumbers | ./printresult

but that's boring, eh?  And you have to have three executables.  So let's have a look at what those vertical bars are doing at the C level.

You create a pipe with the pipe system call.  You reassign standard input/output with dup2.  You create new processes with fork, and you wait for them to terminate with waitpid.  A program to set the whole thing up would look something like this:

int
main(void)
{
    pid_t children[2];
    int pipe1[2], pipe2[2];
    int status;

    pipe(pipe1);
    pipe(pipe2);

    children[0] = fork();
    if (children[0] == 0)
    {
        /* in child 0 */
        dup2(pipe1[1], 1);
        generate_two_numbers_and_write_them_to_fd_1();
        _exit(0);
    }

    children[1] = fork();
    if (children[1] == 0)
    {
        /* in child 1 */
        dup2(pipe1[0], 0);
        dup2(pipe2[1], 1);
        read_two_numbers_from_fd_0_add_them_and_write_result_to_fd_1();
        _exit(0);
    }

    /* parent process still */
    dup2(pipe2[0], 0);
    read_a_number_from_fd_0_and_print_it();

    waitpid(children[0], &status, 0);
    waitpid(children[1], &status, 0);

    return 0;
}

Please note:

I left out all error handling, because that would make the program about three times longer.  Your instructor wants you to include error handling.

Similarly, I left out checking the exit status of the children; your instructor also wants you to check that.

You do not need the dup2 calls; you could just pass the pipe fd numbers to the subroutine calls.  But if you were exec-ing a new binary in the child, which is more typical, you would need them.  You would then also have to worry about making sure all file descriptors numbered 3 and higher were closed.

There is a reason I am using _exit instead of exit.  Try to figure out what it is.

You need to use read and write instead of stdio.h calls in the subroutines called from child processes.  The reason is related to the reason I am using _exit.


问:
MS-Access 2016 - update a record based on a record from another table
I'm new to MS access. I have a few tables. Table 'Learners' contains columns such as 'LearnerID' (unique), firstname, surname, status, etc. There's another table (LearnerUpdate) that I created by importing a spreadsheet. The LearnerUpdate also contains a learnerID and their names. I need to match the learner ID and update teh LearnerUpdate table to include the 'status' taken from the 'Learners' table. How do I do it?
I'm not even sure what to google for. The Access terminology is alien to me.

Thank you

答:
Assuming the column you want to update in the LearnerUpdate table is named 'Status', then try to execute this SQL in the Queries table:</p>

```<code>UPDATE LearnerUpdate
INNER JOIN Learners
ON LearnerUpdate.LearnerID = Learners.LearnerID
SET LearnerUpdate.Status = Learners.Status
</code>```

Body:
Assuming the column you want to update in the LearnerUpdate table is named 'Status', then try to execute this SQL in the Queries table:

UPDATE LearnerUpdate
INNER JOIN Learners
ON LearnerUpdate.LearnerID = Learners.LearnerID
SET LearnerUpdate.Status = Learners.Status


问:
Location Services not working in iOS 11
I just rebuilt my app with the iOS 11 SDK in an attempt to remove the blue banner that is now always appearing. I thought - "Brilliant, that worked", only to discover that location services are now not working at all.

The application used to work with iOS 10 - Has anybody heard anything?

答:
It would appear that apple have added yet another privacy feature. The user is now able to override our requestAlwaysAuthorization and downgrade it to requestWhenInUseAuthorization - Which means as a developer we now have to supply both descriptions in the Info.plist

I found that they have added a new key NSLocationAlwaysAndWhenInUseUsageDescription

```<code>/*
*      Either the NSLocationAlwaysAndWhenInUseUsageDescription key or both the
*      NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription
*      keys must be specified in your Info.plist; otherwise, this method will do
*      nothing, as your app will be assumed not to support Always authorization.
*/
</code>```

However, upon using this new key - the location service still didn't work, upon further searching I found this gem mixed in with all the extra debugging information:

This app has attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data

Which directly contradicts the the comment that I found in the updated CLLocationManager.h file. So I've created a radar.

Good news, if you follow the advice of the debugging console, IE. add both the new key NSLocationAlwaysAndWhenInUseUsageDescription and one of the old keys NSLocationWhenInUseUsageDescription, locations services will start to work again.

Title: Location Services not working in iOS 11

Body:
It would appear that apple have added yet another privacy feature. The user is now able to override our requestAlwaysAuthorization and downgrade it to requestWhenInUseAuthorization - Which means as a developer we now have to supply both descriptions in the Info.plist

I found that they have added a new key NSLocationAlwaysAndWhenInUseUsageDescription

/*
*      Either the NSLocationAlwaysAndWhenInUseUsageDescription key or both the
*      NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription
*      keys must be specified in your Info.plist; otherwise, this method will do
*      nothing, as your app will be assumed not to support Always authorization.
*/

However, upon using this new key - the location service still didn't work, upon further searching I found this gem mixed in with all the extra debugging information:

This app has attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data

Which directly contradicts the the comment that I found in the updated CLLocationManager.h file. So I've created a radar.

Good news, if you follow the advice of the debugging console, IE. add both the new key NSLocationAlwaysAndWhenInUseUsageDescription and one of the old keys NSLocationWhenInUseUsageDescription, locations services will start to work again.


问:
Facebook api and java
Im playing around with the facebook api and java. Now i created a small application from a tutorial I saw, but when I cant compile it properly because netbeans underlines the lines:

```<code>import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.google.code.facebookapi.Attachment;
import com.google.code.facebookapi.AttachmentMediaImage;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FeedFacebookPhoto;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.TemplatizedAction;
</code>```

How do i import these into netbeans to use?

答:
You need to download the necessary jar files and add them as libraries in netbeans. You will find the apache commons library on the apache.org website and the other library is probably on the Google Code website.

Start by downloading the jar files and placing them in a location on your machine. Then in netbeans > project explorer right-click on the project Name >libraries tag and click Add Library. Then browse for the location of the jar files that you downloaded. Add each library this way.

Title: Facebook api and java

Body:
Im playing around with the facebook api and java. Now i created a small application from a tutorial I saw, but when I cant compile it properly because netbeans underlines the lines:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.google.code.facebookapi.Attachment;
import com.google.code.facebookapi.AttachmentMediaImage;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FeedFacebookPhoto;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.TemplatizedAction;

How do i import these into netbeans to use?


问:
How to use f1 score metrics from sklearn using libact?
I used SkeleanrProbaAdapter from libact, to use the Sklearn Gradient Boosting classifier as shown here:

clf=SklearnProbaAdapter(GradientBoostingClassifier(n_estimators=5, learning_rate=1.0,max_depth=2, random_state=0))

Following the example libact provides in their documentation, I initialized and measure the error in this way:

qs=UncertaintySampling(trn_ds1, method='lc', model=clf)
model = clf
...training and labeling...
E_out = np.append(E_out, 1 - model.score(tst_ds))

Now I am trying to use f1 metrics from libact. I tried

E_out = np.append(E_out, 1 - model.score(tst_ds, criterion="f1"))

but since model is not multilabel, an error is raised. Any help deeply appreciated.

答:
I ended up using  sklearn.metrics f1 score. Here is the code if someone finds this useful: </p>

```<code>from sklearn.metrics import f1_score
def run(trn_ds, tst_ds, lbr, model, qs, quota,fully_labeled_trn_ds,train_each,labels):
    E_in, E_out, E_full,E_out_f1 = [], [],[],[]
    counter=0
    for i in range(quota):
        # Standard usage of libact objects
        ask_id = qs.make_query()
        X, _ = zip(*trn_ds.data)
        _, Y = zip(*fully_labeled_trn_ds.data)
        lb = lbr.label(X[ask_id])
        trn_ds.update(ask_id, lb)
        if counter%train_each==0:
            model.train(trn_ds)
        E_in = np.append(E_in, 1 - model.score(trn_ds))
        E_out = np.append(E_out, 1 - model.score(tst_ds))
        E_full= np.append(E_full, 1 - model.score(fully_labeled_trn_ds))
        E_out_f1 = np.append(E_out_f1, f1_score(Y,model.predict(X),average='micro'))
    return E_in, E_out, E_full,E_out_f1
</code>```

<p>I just changed that part in the run function that is called inside active_learning function in the example of libact. </p>

Body:
I ended up using  sklearn.metrics f1 score. Here is the code if someone finds this useful:

from sklearn.metrics import f1_score
def run(trn_ds, tst_ds, lbr, model, qs, quota,fully_labeled_trn_ds,train_each,labels):
    E_in, E_out, E_full,E_out_f1 = [], [],[],[]
    counter=0
    for i in range(quota):
        # Standard usage of libact objects
        ask_id = qs.make_query()
        X, _ = zip(*trn_ds.data)
        _, Y = zip(*fully_labeled_trn_ds.data)
        lb = lbr.label(X[ask_id])
        trn_ds.update(ask_id, lb)
        if counter%train_each==0:
            model.train(trn_ds)
        E_in = np.append(E_in, 1 - model.score(trn_ds))
        E_out = np.append(E_out, 1 - model.score(tst_ds))
        E_full= np.append(E_full, 1 - model.score(fully_labeled_trn_ds))
        E_out_f1 = np.append(E_out_f1, f1_score(Y,model.predict(X),average='micro'))
    return E_in, E_out, E_full,E_out_f1

I just changed that part in the run function that is called inside active_learning function in the example of libact.


问:
condense an if/else if statement using logical operators with javascript
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

```<code>$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };
</code>```

答:
I reconsidered - you can make it a bit better in one way, and worse in another.

For each expression like this:

```<code>$scope.leftOperand = $scope.leftOperand + operandEntered;
</code>```

you can use the assignment operator:

```<code>$scope.leftOperand += operandEntered;
</code>```

to shorten it slightly.

I have re-re-re-considered. Assuming you are actually doing string concatenation to build numbers from entered digits, I think this is what you want (I did skip over the 'answer' condition as something that shouldn't happen).

```<code>$scope.setOperand = function (operandEntered) {
    var prop = ($scope.operator === null) ? 'leftOperand' : 'rightOperand';
    $scope[prop] = ($scope[prop] === null) ? operandEntered : $scope[prop]+operandEntered;
};
</code>```

Body:
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };

Body:
I reconsidered - you can make it a bit better in one way, and worse in another.

For each expression like this:

$scope.leftOperand = $scope.leftOperand + operandEntered;

you can use the assignment operator:

$scope.leftOperand += operandEntered;

to shorten it slightly.

I have re-re-re-considered. Assuming you are actually doing string concatenation to build numbers from entered digits, I think this is what you want (I did skip over the 'answer' condition as something that shouldn't happen).

$scope.setOperand = function (operandEntered) {
    var prop = ($scope.operator === null) ? 'leftOperand' : 'rightOperand';
    $scope[prop] = ($scope[prop] === null) ? operandEntered : $scope[prop]+operandEntered;
};


问:
subsonic - convert an linq query to sql query / DataReader
Let's say I have a the following query:

```<code>int x = 5;
var result = from p in db.products
             where p.CategoryId == x
             select p;

int count = result.Count();
List<product> products = result.ToList();
</code>```

That's what I have now. But aditionally I need to have a DataReader from result:

```<code>// that's what I need:
var reader = ConvertSubSonicLinqQueryToDataReader(result);
</code>```

How can I convert the linq statement to something I can work with?
A DataReader or a DbCommand or even plain sql with a list of paramters.

I know SubSonic can do that (since it translates the query to plain sql anyway) but I haven't found anything in the public accessible methods yet.

Any suggestions?

答:
Converting the LINQ query is the wrong approach. LINQ returns results at a level of abstraction higher than a DataReader works at.

There's also the issue of deferred execution so your LINQ query may not be executed as a single SQL statement anyway.

Rater than use a LINQ statement why not just use an SqlQuery instead?

```<code>var qry = new Select().From(Product.Schema).Where(Product.CategoryIdColumn).IsEqualTo(x);

return qry.ExecuteReader();
</code>```

Edit:

Just seen you're using SubSonic3 (not 2 as the above code would be for) but the potential misuse of LINQ and duplication of work still stands.

Body:
Let's say I have a the following query:

int x = 5;
var result = from p in db.products
             where p.CategoryId == x
             select p;

int count = result.Count();
List<product> products = result.ToList();

That's what I have now. But aditionally I need to have a DataReader from result:

// that's what I need:
var reader = ConvertSubSonicLinqQueryToDataReader(result);

How can I convert the linq statement to something I can work with?
A DataReader or a DbCommand or even plain sql with a list of paramters.

I know SubSonic can do that (since it translates the query to plain sql anyway) but I haven't found anything in the public accessible methods yet.

Any suggestions?

Body:
Converting the LINQ query is the wrong approach. LINQ returns results at a level of abstraction higher than a DataReader works at.

There's also the issue of deferred execution so your LINQ query may not be executed as a single SQL statement anyway.

Rater than use a LINQ statement why not just use an SqlQuery instead?

var qry = new Select().From(Product.Schema).Where(Product.CategoryIdColumn).IsEqualTo(x);

return qry.ExecuteReader();

Edit:

Just seen you're using SubSonic3 (not 2 as the above code would be for) but the potential misuse of LINQ and duplication of work still stands.


问:
SSIS Derived Column (Find String)
I am extracting pattern from the 'Notes' column, I am looking for an alpha numeric word (MXPC123456) from the notes and I want to store the output in a new column. So for that I am using a Derived Column and FindString() function.

I am getting error when I run this code using the following expression in Drived Column inside my SSIS package:

```<code>(DT_WSTR,255)SUBSTRING(TEXT_LINE1,FINDSTRING(TEXT_LINE1,"MXPC",1),10).
</code>```

Don't know what I am doing wrong.

Error: 0xC0049067 at Get DC Coms Data, Derived Column [67]: An error occurred while evaluating the function.

Error: 0xC0209029 at Get DC Coms Data, Derived Column [67]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "component "Derived Column" (67)" failed because error code 0xC0049067 occurred, and the error row disposition on "output column "CKT_MX" (91)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error: 0xC0047022 at Get DC Coms Data, SSIS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Derived Column" (67) failed with error code 0xC0209029 while processing input "Derived Column Input" (68). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

Could you please help?

Regards
Prab

答:
There are 2 things that may cause this error:

TEXT_LINE1 doesn't contains "MXPC" string , so  FINDSTRING(TEXT_LINE1,"MXPC",1) will return 0 and the SUBSTRING function will throw an exception

TEXT_LINE1 contains "MXPC" string but there is no 10 characters after the FINDSTRING returned value

TEXT_LINE1 IS NULL

so you can add some validation to this expression

```<code> ISNULL([TEXT_LINE1]) == TRUE ? "" : (FINDSTRING([TEXT_LINE1],"MXPC",1) == 0    ?  "" :
 (LEN([TEXT_LINE1])  >= FINDSTRING([TEXT_LINE1],"MXPC",1) + 9  ?   SUBSTRING([TEXT_LINE1],FINDSTRING([TEXT_LINE1],"MXPC",1),10)  : ""))
</code>```

Title: SSIS Derived Column (Find String)

Body:
I am extracting pattern from the 'Notes' column, I am looking for an alpha numeric word (MXPC123456) from the notes and I want to store the output in a new column. So for that I am using a Derived Column and FindString() function.

I am getting error when I run this code using the following expression in Drived Column inside my SSIS package:

(DT_WSTR,255)SUBSTRING(TEXT_LINE1,FINDSTRING(TEXT_LINE1,"MXPC",1),10).

Don't know what I am doing wrong.

Error: 0xC0049067 at Get DC Coms Data, Derived Column [67]: An error occurred while evaluating the function.

Error: 0xC0209029 at Get DC Coms Data, Derived Column [67]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "component "Derived Column" (67)" failed because error code 0xC0049067 occurred, and the error row disposition on "output column "CKT_MX" (91)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error: 0xC0047022 at Get DC Coms Data, SSIS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Derived Column" (67) failed with error code 0xC0209029 while processing input "Derived Column Input" (68). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

Could you please help?

Regards
Prab

Body:
There are 2 things that may cause this error:

TEXT_LINE1 doesn't contains "MXPC" string , so  FINDSTRING(TEXT_LINE1,"MXPC",1) will return 0 and the SUBSTRING function will throw an exception

TEXT_LINE1 contains "MXPC" string but there is no 10 characters after the FINDSTRING returned value

TEXT_LINE1 IS NULL

so you can add some validation to this expression

 ISNULL([TEXT_LINE1]) == TRUE ? "" : (FINDSTRING([TEXT_LINE1],"MXPC",1) == 0    ?  "" :
 (LEN([TEXT_LINE1])  >= FINDSTRING([TEXT_LINE1],"MXPC",1) + 9  ?   SUBSTRING([TEXT_LINE1],FINDSTRING([TEXT_LINE1],"MXPC",1),10)  : ""))


问:
How to make a react bootstrap dropdown with panelgroups
I am trying to make a dropdown where each menuitem will have submenuitems
as

```<code>Drodown(select)
 1. List item(header)
      Litem-1(subheader)
      Litem-2(subheader)
 2. Header-2(header)
       Litem-2-1(subheader)
       Litem-2-2(subheader)
</code>```

I am using react bootstrap dropdown to achieve this
where each menuitem would have a panelgroup of items as Litem-1 and Litem-2

So When i click on select the dropdown should open up, but when i click on individual headers(which are not expanded by default), should expand and should not close the dropdown and when clicked on subheaders dropdown has to be closed
I have tried using open option of dropdown ,using this i am trying to control the visibility of the dropdown i could achieve the same for headers when i try to do the same i could not achieve because the event is bubbling up till the parent and dropdown remains open , i also tried to use stopPropagation but looks like menuitem is not respecting it not sure why it is the case

I tried to solve this as this
https://codepen.io/anon/pen/WONMGd
can some one please comment if this approach is right and also why cannot I use event.stopPropagation and prevent default here

Thanks

答:
To use panels in the way you sort of want them to you have to set the accordion prop on your panel to be true.  Check out the code below:

```<code><Dropdown.Menu className="Groups" bsRole="menu">
          <MenuItem  onClick={this.menuItemClickedThatShouldntCloseDropdown.bind(this)}>
           <PanelGroup activeKey="1" accordion activeKey={this.state.activeKey}>
             <Panel header="header1" eventKey='1'>
               <span onClick={this.menuItemShouldCloseDropDown.bind(this)}>Content-1</span>
             </Panel>
              <Panel header="header2" eventKey='2'>
                <span onClick={this.menuItemShouldCloseDropDown.bind(this)}>content=2</span>
             </Panel>
            </PanelGroup>
        </MenuItem>
           <MenuItem  onClick={this.menuItemClickedThatShouldntCloseDropdown}>
            hi
        </MenuItem>
      </Dropdown.Menu>

  </Dropdown>
</code>```

and add this to your class definition:

```<code>  handleSelect(activeKey) {
    this.setState({ activeKey })
  }
</code>```

This seems to solve at least one of your problems.  Id recommend tearing out the other pseudo-state this._forceOpen logic to see what you really need.

Body:
I am trying to make a dropdown where each menuitem will have submenuitems
as

Drodown(select)
 1. List item(header)
      Litem-1(subheader)
      Litem-2(subheader)
 2. Header-2(header)
       Litem-2-1(subheader)
       Litem-2-2(subheader)

I am using react bootstrap dropdown to achieve this
where each menuitem would have a panelgroup of items as Litem-1 and Litem-2

So When i click on select the dropdown should open up, but when i click on individual headers(which are not expanded by default), should expand and should not close the dropdown and when clicked on subheaders dropdown has to be closed
I have tried using open option of dropdown ,using this i am trying to control the visibility of the dropdown i could achieve the same for headers when i try to do the same i could not achieve because the event is bubbling up till the parent and dropdown remains open , i also tried to use stopPropagation but looks like menuitem is not respecting it not sure why it is the case

I tried to solve this as this
https://codepen.io/anon/pen/WONMGd
can some one please comment if this approach is right and also why cannot I use event.stopPropagation and prevent default here

Thanks

Body:
To use panels in the way you sort of want them to you have to set the accordion prop on your panel to be true.  Check out the code below:

<Dropdown.Menu className="Groups" bsRole="menu">
          <MenuItem  onClick={this.menuItemClickedThatShouldntCloseDropdown.bind(this)}>
           <PanelGroup activeKey="1" accordion activeKey={this.state.activeKey}>
             <Panel header="header1" eventKey='1'>
               <span onClick={this.menuItemShouldCloseDropDown.bind(this)}>Content-1</span>
             </Panel>
              <Panel header="header2" eventKey='2'>
                <span onClick={this.menuItemShouldCloseDropDown.bind(this)}>content=2</span>
             </Panel>
            </PanelGroup>
        </MenuItem>
           <MenuItem  onClick={this.menuItemClickedThatShouldntCloseDropdown}>
            hi
        </MenuItem>
      </Dropdown.Menu>

  </Dropdown>

and add this to your class definition:

  handleSelect(activeKey) {
    this.setState({ activeKey })
  }

This seems to solve at least one of your problems.  Id recommend tearing out the other pseudo-state this._forceOpen logic to see what you really need.


问:
Same firebase project for both Android and iOS
My friend have finished setting up a Firebase backend for an Android application, and the project is on his private firebase account. Now I am starting to code the iOS version which should access the same Firebase backend.

My question is this... do I need to get his firebase email and password to work on the project or there is a way to import it to my account so I can work on it ?
tip: The solution should be like that, if any change happen in  iOS or Android, must change in both of them.

答: You can add multiple developers to a single project, and you can have multiple apps added to your project. Do the following: your friend must add you to the project, and you must create an iOS application for that project in Firebase.</p>


问:
R: is there something like dmatrices ( from python) in R for categorical values?
In python you can use the dmatrices function from the patsy module when using categorical values for regressions to create 0 and 1 matrices for the categorical values.

Is there a library/function in R that performs the same function?

答:
Suppose we have this data frame where columns x and y are numeric and column f is a factor.  Then we can run the regression like this and lm will convert the formula to an appropriate model matrix including 0/1 columns and then run the regression on that:

```<code># test data
set.seed(123)
DF <- transform(data.frame(f = gl(3, 5, labels = letters[1:3]), x = 1:15),
         y = rnorm(15, 1:15))

# run regression
fo <- y ~ x + f
lm(fo, DF)
</code>```

The model matrix is computed in doing the above so there is no need to explicitly compute it but if you want to anyways try this:

```<code># view model matrix
model.matrix(fo, DF)
</code>```

Body:
Suppose we have this data frame where columns x and y are numeric and column f is a factor.  Then we can run the regression like this and lm will convert the formula to an appropriate model matrix including 0/1 columns and then run the regression on that:

# test data
set.seed(123)
DF <- transform(data.frame(f = gl(3, 5, labels = letters[1:3]), x = 1:15),
         y = rnorm(15, 1:15))

# run regression
fo <- y ~ x + f
lm(fo, DF)

The model matrix is computed in doing the above so there is no need to explicitly compute it but if you want to anyways try this:

# view model matrix
model.matrix(fo, DF)


问:
mysql dynamic column based on weekday
I have a table:

```<code>id 0_open 0_close 1_open 1_close 2_open 2_close 3_open 3_close 4_open 4_close 5_open 5_close 6_open 6_close

1 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00
</code>```

Where 0-6 - weekday (From Mon to Sun);

How can I select rows:

```<code>SELECT * FROM table WHERE TIME(NOW()) BETWEEN 2_open AND 2_close
</code>```

If today is Wednesday (Index: 2)?

答:
It's something you have to handle in the business layer of the application (i.e. maybe a function in the middleware/backend layer that takes a date as an argument and returns column names).

Talking about the functions, you can also write a function in MySQL that takes a date and returns two values which can be used in the above query. You can make use of DAYOFWEEK() library function of MySQL to determine the column names.

Title: mysql dynamic column based on weekday

Body:
I have a table:

id 0_open 0_close 1_open 1_close 2_open 2_close 3_open 3_close 4_open 4_close 5_open 5_close 6_open 6_close

1 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00

Where 0-6 - weekday (From Mon to Sun);

How can I select rows:

SELECT * FROM table WHERE TIME(NOW()) BETWEEN 2_open AND 2_close

If today is Wednesday (Index: 2)?


问:
How do I safely embed a youtube video into a Chrome extension without violating Content Security Policy?
I've been searching around for answers on this issues for a while now but couldn't get any of the provided solutions to work.

Here's the youtube code I'm trying to embed:
http://jsfiddle.net/BFDKS/1204/

The video iframe is added to index.html and within app.js I call:

```<code>    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;

    function onYouTubeIframeAPIReady() {
        player = new YT.Player('ytplayer', {
            events: {
                'onReady': onPlayerReady
            }
        });
    }

    function onPlayerReady() {
        player.playVideo();
        // Mute!
        player.mute();
    }
</code>```

The problem is I receive a CSR error in the console

This leads me to my manifest.json file:

```<code>{
"name": "",
"manifest_version": 2,
"version": "0.0.6",
"icons": {
  "16": "icon-16.png",
  "48": "icon-48.png",
  "128": "icon-128.png"
},
"content_security_policy": "script-src 'self' https://www.google-analytics.com/; https://www.youtube.com/*; object-src 'self'",
"permissions": [
    "activeTab",
    "*://*.google-analytics.com/*"
],
"chrome_url_overrides": {
    "newtab": "index.html"
},
"description": ""
</code>```

}

That's basically where I'm at now and having trouble making progress. I'm really just trying to embed a autoplaying youtube video that is muted by default with closed captions turned on. Any ideas? Greatly appreciated!

答:
I figured it out, the manifest.json file needed the following:

```<code>    "content_security_policy": "script-src 'self' https://www.google-analytics.com/ https://www.youtube.com/ https://s.ytimg.com; object-src 'self'; child-src https://www.youtube.com/ https://s.ytimg.com",
</code>```

Thank you for the guidance wOxxOm

Body:
I've been searching around for answers on this issues for a while now but couldn't get any of the provided solutions to work.

Here's the youtube code I'm trying to embed:
http://jsfiddle.net/BFDKS/1204/

The video iframe is added to index.html and within app.js I call:

    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;

    function onYouTubeIframeAPIReady() {
        player = new YT.Player('ytplayer', {
            events: {
                'onReady': onPlayerReady
            }
        });
    }

    function onPlayerReady() {
        player.playVideo();
        // Mute!
        player.mute();
    }

The problem is I receive a CSR error in the console

This leads me to my manifest.json file:

{
"name": "",
"manifest_version": 2,
"version": "0.0.6",
"icons": {
  "16": "icon-16.png",
  "48": "icon-48.png",
  "128": "icon-128.png"
},
"content_security_policy": "script-src 'self' https://www.google-analytics.com/; https://www.youtube.com/*; object-src 'self'",
"permissions": [
    "activeTab",
    "*://*.google-analytics.com/*"
],
"chrome_url_overrides": {
    "newtab": "index.html"
},
"description": ""

}

That's basically where I'm at now and having trouble making progress. I'm really just trying to embed a autoplaying youtube video that is muted by default with closed captions turned on. Any ideas? Greatly appreciated!

Body:
I figured it out, the manifest.json file needed the following:

    "content_security_policy": "script-src 'self' https://www.google-analytics.com/ https://www.youtube.com/ https://s.ytimg.com; object-src 'self'; child-src https://www.youtube.com/ https://s.ytimg.com",

Thank you for the guidance wOxxOm


问:
How to handle the new window in Selenium WebDriver using Java?
This is my code:

```<code>driver.findElement(By.id("ImageButton5")).click();
//Thread.sleep(3000);
String winHandleBefore = driver.getWindowHandle();
driver.switchTo().window(winHandleBefore);
driver.findElement(By.id("txtEnterCptCode")).sendKeys("99219");
</code>```

Now I have the next error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with id == txtEnterCptCode (WARNING: The server
  did not provide any stacktrace information)
      Command duration or timeout: 404 milliseconds.

Any ideas?

答:
i was having some issues with windowhandle and tried this one. this one works good for me. </p>

```<code>String parentWindowHandler = driver.getWindowHandle();
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
    driver.switchTo().window(subWindowHandler);

    System.out.println(subWindowHandler);
}

driver.switchTo().window(parentWindowHandler);
</code>```

Body:
This is my code:

driver.findElement(By.id("ImageButton5")).click();
//Thread.sleep(3000);
String winHandleBefore = driver.getWindowHandle();
driver.switchTo().window(winHandleBefore);
driver.findElement(By.id("txtEnterCptCode")).sendKeys("99219");

Now I have the next error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with id == txtEnterCptCode (WARNING: The server
  did not provide any stacktrace information)
      Command duration or timeout: 404 milliseconds.

Any ideas?

Body:
i was having some issues with windowhandle and tried this one. this one works good for me.

String parentWindowHandler = driver.getWindowHandle();
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
    driver.switchTo().window(subWindowHandler);

    System.out.println(subWindowHandler);
}

driver.switchTo().window(parentWindowHandler);


问:
Selecting multiple columns from .dat files in a bash loop and merging them horizontally
I am pretty much a beginner at this and am having trouble with processing .dat files. I have lots of .dat files (a_"number"_b.dat) containing 4 columns each and i would like to pull out columns 2 and 4 from each of them through a for loop and merge them horizontally in a new file i.e. pick out columns every loop and add them to the file side by side. I tried using both awk|paste statements and cut|paste statements but didn't get it working at all. In the awk case i end up with a file containing columns 2 and 4 only from the last file which was read in the loop and the cut|paste gives me a blank file. Here is the code i used:

```<code>for k in {1..9}
do
awk '{print $2,$4}' a_0"$k"_b.dat > atest.dat
paste atest.dat atestf.dat > atestf.dat
#cut -f2 a_0"$k"_b.dat | paste atest.dat
#cut -f4 a_0"$k"_b.dat | paste atest.dat
done
</code>```

Example of input and output:

```<code>file 1:
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
file2:
5 50 500 5000
6 60 600 6000
7 70 700 7000
8 80 800 8000

output expected:
10 1000 50 5000
20 2000 60 6000
30 3000 70 7000
40 4000 80 8000
</code>```

EDIT: i forgot to mention that some files have missing rows at the bottom and i would have to leave them as blank spaces when placing columns side by side.

答:
This one seems to work fine:

```<code>for ((k=1;k<=2;k++));do
tmp="$(cat mergefile)"
paste -d ' ' <(echo "$tmp") <(cut -d ' ' -f2,4 "file$k")  > mergefile
done
cat mergefile
#Output
 10 1000 50 5000
 20 2000 60 6000
 30 3000 70 7000
 40 4000 80 8000
</code>```

Cut default delimiter is tab, you need to explicitly specify space as delimiter.

Same applies to paste.

You can cannot open a file for reading and on the same time for writing.
Thus , your initial attempt paste atest.dat atestf.dat > atestf.dat fails since file atestf.dat is opened for reading by past and even for writing using > (output redirection). This is the reason i'm using a tmp variable to load the data already present in mergefile in my solution.

Body:
I am pretty much a beginner at this and am having trouble with processing .dat files. I have lots of .dat files (a_"number"_b.dat) containing 4 columns each and i would like to pull out columns 2 and 4 from each of them through a for loop and merge them horizontally in a new file i.e. pick out columns every loop and add them to the file side by side. I tried using both awk|paste statements and cut|paste statements but didn't get it working at all. In the awk case i end up with a file containing columns 2 and 4 only from the last file which was read in the loop and the cut|paste gives me a blank file. Here is the code i used:

for k in {1..9}
do
awk '{print $2,$4}' a_0"$k"_b.dat > atest.dat
paste atest.dat atestf.dat > atestf.dat
#cut -f2 a_0"$k"_b.dat | paste atest.dat
#cut -f4 a_0"$k"_b.dat | paste atest.dat
done

Example of input and output:

file 1:
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
file2:
5 50 500 5000
6 60 600 6000
7 70 700 7000
8 80 800 8000

output expected:
10 1000 50 5000
20 2000 60 6000
30 3000 70 7000
40 4000 80 8000

EDIT: i forgot to mention that some files have missing rows at the bottom and i would have to leave them as blank spaces when placing columns side by side.

Body:
This one seems to work fine:

for ((k=1;k<=2;k++));do
tmp="$(cat mergefile)"
paste -d ' ' <(echo "$tmp") <(cut -d ' ' -f2,4 "file$k")  > mergefile
done
cat mergefile
#Output
 10 1000 50 5000
 20 2000 60 6000
 30 3000 70 7000
 40 4000 80 8000

Cut default delimiter is tab, you need to explicitly specify space as delimiter.

Same applies to paste.

You can cannot open a file for reading and on the same time for writing.
Thus , your initial attempt paste atest.dat atestf.dat > atestf.dat fails since file atestf.dat is opened for reading by past and even for writing using > (output redirection). This is the reason i'm using a tmp variable to load the data already present in mergefile in my solution.


问:
"RCTBundleURLProvider.h" file not found - AppDelegate.m
I am trying to run my React Native app in XCode and I keep getting this error. I cannot figure out how to resolve the issue. Any suggestions?

Screen Shot of Error in XCode:

答:
I solved this problem by following steps:

In xcode choose project root.

Drag React.xcodeproj from Libraries to the root of the project.

Click on project name (in my case it name SaleKit) in TARGETS

Choose Build Phases

In dropdown of Target Dependencies add React

Rebuild or re-run


问:
Looking for average BGR values for each column in each color
We are working on a code that looks at a 96-well plate. We have the centers coordinates of each well. We then created a for loop that would allow us get the BGR value of each well. However, we need to somehow organize each column and average those values. I believe that we are getting an error from the first loop. With this one, it seems like the function only goes through the first loop and not the second one. When I run it, I get 3 values (assuming to be bgr values) and then proceeds to push out the averages. It also seems to repeat some average values. Any suggestions to what I can change, or errors at first-look. I will provide the image and legend below.

Links to images are:
http://imgur.com/Eb87ZxW (the image was scaled, so the coordinates may not work with the uploaded image)
http://imgur.com/P4tPPXX

```<code>import cv2, numpy as np, sys

#filename will be taken from the command line and process as the image variable
#filename= sys.argv([1])
img = cv2.imread('greenandblueplate.jpg')

#centroids
wells = [img[110,97], img[184,97], img[254,97], img[324,97], img[396,96], img[466,97], #columnH 12-7
         img[537,96], img[607,97], img[680,96], img[750,97], img[820,96], img[891,97], #columnH 6-1
         img[110,165],img[184,165],img[254,165],img[324,165],img[396,165],img[466,165], #columnG 12-7
         img[537,165],img[607,165],img[680,165],img[750,166],img[820,165],img[891,165], #columnG 6-1
         img[110,235],img[184,235],img[254,235],img[324,235],img[396,235],img[466,235], #columnF 12-7
         img[537,235],img[607,235],img[680,235],img[750,235],img[820,235],img[891,235], #columnF 6-1
         img[110,305],img[184,305],img[254,305],img[324,305],img[396,305],img[466,305], #columnE 12-7
         img[537,305],img[607,305],img[680,305],img[750,305],img[820,305],img[891,305], #columnE 6-1
         img[110,373],img[184,373],img[254,373],img[324,373],img[396,373],img[466,373], #columnD 12-7
         img[537,373],img[607,373],img[680,373],img[750,372],img[820,373],img[891,373], #columnD 6-1
         img[110,442],img[184,442],img[254,442],img[324,442],img[396,442],img[466,442], #columnC 12-7
         img[537,442],img[607,442],img[680,442],img[750,443],img[820,442],img[891,442], #columnC 6-1
         img[109,511],img[184,511],img[254,511],img[324,511],img[396,511],img[466,511], #columnB 12-7
         img[537,512],img[607,512],img[680,511],img[750,511],img[820,511],img[891,511], #columnB 6-1
         img[109,582],img[184,582],img[254,582],img[324,581],img[396,582],img[466,582], #columnA 12-7
         img[537,581],img[607,582],img[680,582],img[750,581],img[820,582],img[891,582]] #columnA 6-1

bAvgFilledWells = []
gAvgFilledWells = []
rAvgFilledWells = []

#filtering out the centroids that are not needed
#and getting the bgr values for the first color on the plate
for center in wells:
    if center[1] > 124:
        if center[0] < 360:
            b = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 0]
            g = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 1]
            r = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 2]
            bAvg = np.mean(b)
            gAvg = np.mean(g)
            rAvg = np.mean(r)

            bAvgFilledWells.append(bAvg)
            gAvgFilledWells.append(gAvg)
            rAvgFilledWells.append(rAvg)
            print(center)
            print("For the first color, average value for blue is:", bAvg)
            print("For the first color, average value for green is:", gAvg)
            print("For the first color, average value for red is:", rAvg)

bAvgFilledWells2 = []
gAvgFilledWells2 = []
rAvgFilledWells2 = []

#filtering out the centroids that are not needed
#and getting the bgr values for the second color on the plate
for center in wells:
    if center[1] > 124:
        if center[0] > 360 and center[0] < 642:
            b2 = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 0]
            g2 = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 1]
            r2 = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 2]
            bAvg2 = np.mean(b2)
            gAvg2 = np.mean(g2)
            rAvg2 = np.mean(r2)

            print(center)
            print("For the second color, average value for blue is:", bAvg2)
            print("For the second color, average value for green is:", gAvg2)
            print("For the second color, average value for blue is:", rAvg2)
            bAvgFilledWells2.append(bAvg2)
            gAvgFilledWells2.append(gAvg2)
            rAvgFilledWells2.append(rAvg2)
</code>```

答:
The huge array wells at the beginning looks cumbersome and repetitive. It could be improved by creating lists of the X/Y positions of columns A-H and rows 1-12.

And this is the source of your errors: in the loops, you're parsing center as if it is the x,y position, but in fact it is the pixel retrieved from img.

Instead something like:

```<code>columns = [110,124,160] # give 8 values for columns A-H
rows = [97, 165, 235] # give 12 values for rows 1-12
#...
for row = 0 to 3:
    for column = 0 to 7:
        center_column = columns[column]
        center_row = rows[row]
        #... get img pixels and process b,g,r values
</code>```

Body:
We are working on a code that looks at a 96-well plate. We have the centers coordinates of each well. We then created a for loop that would allow us get the BGR value of each well. However, we need to somehow organize each column and average those values. I believe that we are getting an error from the first loop. With this one, it seems like the function only goes through the first loop and not the second one. When I run it, I get 3 values (assuming to be bgr values) and then proceeds to push out the averages. It also seems to repeat some average values. Any suggestions to what I can change, or errors at first-look. I will provide the image and legend below.

Links to images are:
http://imgur.com/Eb87ZxW (the image was scaled, so the coordinates may not work with the uploaded image)
http://imgur.com/P4tPPXX

import cv2, numpy as np, sys

#filename will be taken from the command line and process as the image variable
#filename= sys.argv([1])
img = cv2.imread('greenandblueplate.jpg')

#centroids
wells = [img[110,97], img[184,97], img[254,97], img[324,97], img[396,96], img[466,97], #columnH 12-7
         img[537,96], img[607,97], img[680,96], img[750,97], img[820,96], img[891,97], #columnH 6-1
         img[110,165],img[184,165],img[254,165],img[324,165],img[396,165],img[466,165], #columnG 12-7
         img[537,165],img[607,165],img[680,165],img[750,166],img[820,165],img[891,165], #columnG 6-1
         img[110,235],img[184,235],img[254,235],img[324,235],img[396,235],img[466,235], #columnF 12-7
         img[537,235],img[607,235],img[680,235],img[750,235],img[820,235],img[891,235], #columnF 6-1
         img[110,305],img[184,305],img[254,305],img[324,305],img[396,305],img[466,305], #columnE 12-7
         img[537,305],img[607,305],img[680,305],img[750,305],img[820,305],img[891,305], #columnE 6-1
         img[110,373],img[184,373],img[254,373],img[324,373],img[396,373],img[466,373], #columnD 12-7
         img[537,373],img[607,373],img[680,373],img[750,372],img[820,373],img[891,373], #columnD 6-1
         img[110,442],img[184,442],img[254,442],img[324,442],img[396,442],img[466,442], #columnC 12-7
         img[537,442],img[607,442],img[680,442],img[750,443],img[820,442],img[891,442], #columnC 6-1
         img[109,511],img[184,511],img[254,511],img[324,511],img[396,511],img[466,511], #columnB 12-7
         img[537,512],img[607,512],img[680,511],img[750,511],img[820,511],img[891,511], #columnB 6-1
         img[109,582],img[184,582],img[254,582],img[324,581],img[396,582],img[466,582], #columnA 12-7
         img[537,581],img[607,582],img[680,582],img[750,581],img[820,582],img[891,582]] #columnA 6-1

bAvgFilledWells = []
gAvgFilledWells = []
rAvgFilledWells = []

#filtering out the centroids that are not needed
#and getting the bgr values for the first color on the plate
for center in wells:
    if center[1] > 124:
        if center[0] < 360:
            b = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 0]
            g = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 1]
            r = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 2]
            bAvg = np.mean(b)
            gAvg = np.mean(g)
            rAvg = np.mean(r)

            bAvgFilledWells.append(bAvg)
            gAvgFilledWells.append(gAvg)
            rAvgFilledWells.append(rAvg)
            print(center)
            print("For the first color, average value for blue is:", bAvg)
            print("For the first color, average value for green is:", gAvg)
            print("For the first color, average value for red is:", rAvg)

bAvgFilledWells2 = []
gAvgFilledWells2 = []
rAvgFilledWells2 = []

#filtering out the centroids that are not needed
#and getting the bgr values for the second color on the plate
for center in wells:
    if center[1] > 124:
        if center[0] > 360 and center[0] < 642:
            b2 = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 0]
            g2 = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 1]
            r2 = img[center[0]-4: center[0]+5, center[1]-4: center[1]+5, 2]
            bAvg2 = np.mean(b2)
            gAvg2 = np.mean(g2)
            rAvg2 = np.mean(r2)

            print(center)
            print("For the second color, average value for blue is:", bAvg2)
            print("For the second color, average value for green is:", gAvg2)
            print("For the second color, average value for blue is:", rAvg2)
            bAvgFilledWells2.append(bAvg2)
            gAvgFilledWells2.append(gAvg2)
            rAvgFilledWells2.append(rAvg2)

Body:
The huge array wells at the beginning looks cumbersome and repetitive. It could be improved by creating lists of the X/Y positions of columns A-H and rows 1-12.

And this is the source of your errors: in the loops, you're parsing center as if it is the x,y position, but in fact it is the pixel retrieved from img.

Instead something like:

columns = [110,124,160] # give 8 values for columns A-H
rows = [97, 165, 235] # give 12 values for rows 1-12
#...
for row = 0 to 3:
    for column = 0 to 7:
        center_column = columns[column]
        center_row = rows[row]
        #... get img pixels and process b,g,r values


问:
Bootstrap Div or Span like form-group input-group-addon
Is it possible to make something like the form-group input-group-addon layout just to display information? Not to use it in a form.

HTML:

```<code><div class="form-group ">
    <div class="input-group">
        <span class="input-group-addon">Firstname</span>
        <input value="Vincent" name="InputFirstname" type="text" required>
    </div>
</div>
</code>```

CSS:

```<code>input {
  background-color: white;
  border: 1px solid lightgrey;
  height:30px;
  padding-left:10px;
}
</code>```

http://jsfiddle.net/v69ju4Lz/

答:
HTML:

```<code><div class="form-group ">
    <div class="input-group">
        <span class="input-group-addon">Firstname</span>
        <span class="value">Vincent</span>
    </div>
</div>
</code>```

CSS:

```<code>.value {
  display:block;
  background-color: white;
  border: 1px solid lightgrey;
  height:30px;
  padding: 4px 10px;
  border-radius: 0 4px 4px 0;
}
</code>```

Body:
Is it possible to make something like the form-group input-group-addon layout just to display information? Not to use it in a form.

HTML:

        Firstname
        <input value="Vincent" name="InputFirstname" type="text" required>

CSS:

input {
  background-color: white;
  border: 1px solid lightgrey;
  height:30px;
  padding-left:10px;
}

http://jsfiddle.net/v69ju4Lz/

Body:
HTML:

<div class="form-group ">
    <div class="input-group">
        <span class="input-group-addon">Firstname</span>
        <span class="value">Vincent</span>
    </div>
</div>

CSS:

.value {
  display:block;
  background-color: white;
  border: 1px solid lightgrey;
  height:30px;
  padding: 4px 10px;
  border-radius: 0 4px 4px 0;
}


问:
How to apply odd and even color to a 5 column list
This list display's the background color for 1st line and 2nd line different if the column count is even. When I change the column count to 5 the line color no longer applies, it shows color to each field instead of each line, because row count is also 5. How to keep the custom row count? or any other way to apply background color to odd and even lines for 5 columns ?

```<code><ul id="list">
            <li>Peter</li>
            <li>Mary</li>
            <li>qaul</li>
            <li>Allen</li>
            <li>James</li>
            <li>Vicki</li>
            <li>Brock</li>
            <li>Dana</li>
            <li>Frank</li>
            <li>Gil</li>
            <li>Helen</li>
            <li>Peter</li>
            <li>sadf</li>
            <li>Paul</li>
            <li>cad</li>
            <li>Hyad</li>
            <li>k;pg</li>
            <li>werd</li>
            <li>radn</li>
            <li>vrank</li>
            <li>Gil</li>
            <li>zelen</li>
</ul>

#list {
  -moz-column-count: 5;
  -moz-column-gap: 0px;
  -webkit-column-count: 5;
  -webkit-column-gap: 0px;
  column-count: 5;
  column-gap: 0px;
 }

#list li {
  border-left:1px solid #dedede;
  border-top:1px solid #dedede;

}

#list li:nth-of-type(even) {
    background: #fff;

}
#list li:nth-of-type(odd) {
   background: #efefef;
}
</code>```

http://jsfiddle.net/De8Ku/3625/

答:
Maybe you should not use CSS3 column-count property. Because in this situation, the row amount is relative to the li's amount. Now, you have 22 li markups, when you add it to 25, the background will be wrong even you don't change column-count from 6 to 5.

You may change your HTML from a ul to a table, it is easy to control the row's background.

Thanks!

Body:
This list display's the background color for 1st line and 2nd line different if the column count is even. When I change the column count to 5 the line color no longer applies, it shows color to each field instead of each line, because row count is also 5. How to keep the custom row count? or any other way to apply background color to odd and even lines for 5 columns ?

Peter

Mary

qaul

Allen

James

Vicki

Brock

Dana

Frank

Gil

Helen

Peter

sadf

Paul

cad

Hyad

k;pg

werd

radn

vrank

Gil

zelen

#list {
  -moz-column-count: 5;
  -moz-column-gap: 0px;
  -webkit-column-count: 5;
  -webkit-column-gap: 0px;
  column-count: 5;
  column-gap: 0px;
 }

#list li {
  border-left:1px solid #dedede;
  border-top:1px solid #dedede;

}

#list li:nth-of-type(even) {
    background: #fff;

}
#list li:nth-of-type(odd) {
   background: #efefef;
}

http://jsfiddle.net/De8Ku/3625/