问:
save multiple fields with same name in database using ajax
I want to save the table having multiple rows that is generated dynamically when i try to save a data only first letter is saved in database. and when i try to save the next row it says 500 error in console. i want to save all the data of all the rows one by one in a database how can i achive this?

Here is my code :

```<code> <!--    <form action="" method="POST">  -->
                    <?php $data = array(
                        'id'=>'inventory_form',
                        ); ?>
                    <?php  echo form_open('main/store',$data); ?>
                   <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="inv_tbl">
                            <thead>
                                <th>No</th>
                                <th>~</th>
                                <th>Barcode</th>
                                <th>Product Name</th>
                                <th>SM</th>
                                <th>SPL</th>
                                <th>Quantity</th>
                                <th>Price</th>
                                <th>Discount</th>
                                <th>Amount</th>
                                <th><input type="button" value="+" id="add" class="btn btn-primary add_inv_row"></th>
                            </thead>
                            <tbody class="detail">
                                <tr>
                                    <td class="no">1</td>
                                    <td class="text-center"><input type="checkbox" id="till_check" class="is_checked" name="till_check[]" value="Bike"></td>

                                    <td>
                                        <select name="barcode[]" id="barcode" class="form-control selectpicker barcode" data-live-search="true">
                                        <option value="">Please select a barcode</option>
                                        <?php  foreach($barcodes as $barcode) :?>
                                        <option value="<?php echo $barcode->barcode; ?>"><?php echo $barcode->barcode; ?></option>
                                        <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="text" id="brcode_product" class="form-control productname" name="productname[]"></td>
                                    <td>
                                        <select name="sm[]" id="sm" class="form-control selectpicker sm" data-live-search="true">
                                        <option value="">Please select a Employee code</option>
                                        <?php  foreach($employee_codes as $employee_code) :?>
                                        <option value="<?php echo $employee_code->emp_code; ?>"><?php echo $employee_code->emp_code; ?></option>
                                        <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="text" id="spl" class="form-control spl" name="spl[]"></td>
                                    <td><input type="text" id="quantity" class="form-control quantity" name="quantity[]"></td>
                                    <td><input type="text" id="price" class="form-control price" name="price[]"></td>
                                    <td><input type="text" id="discount" class="form-control discount" name="discount[]"></td>
                                    <td><input type="text" id="amount" class="form-control amount" name="amount[]"></td>
                                    <td><a href="#" class="remove">Delete</a></td>

                                </tr>
                            </tbody>
                            <tfoot>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>

                                <th class="text-center"><button class="btn btn-success" id="save_btn" type="submit" name="sale_submit_btn">Save</button></th>
                                <th style="text-align:center;" class="total">0<b></b></th>

                            </tfoot>

                        </table>

                    </div>

                    <?php echo form_close(); ?>
                    <!--</form>-->
</code>```

My Javascript code :-

```<code>function total() {
    var t = 0;
    $('.amount').each(function (i, e) {
        var amt = $(this).val() - 0;
        t += amt;
    });
    $('.total').html(t);
}

function addnewrow() {
    var n = ($('.detail tr').length - 0) + 1;

    var tr = '<tr>' +
        '<td class="no">' + n + '</td>' +
        '<td><input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="till_check[' + till_check_counter + ']"></td>' +
        '<td><select class="form-control barcode selectpicker  dyselect_' + product_barcode_counter + '" data-live-search="true" name="barcode[' + product_barcode_counter + ']" id="barcode[' + product_barcode_counter + ']">' + '<option>Please select a bar code</option>' + '</select></td>' +
        '<td><input type="text" class="form-control prdctn_' + product_name_counter + ' productname"  id="brcode_product['+product_name_counter+']"  name="productname[' + product_name_counter + ']" id="productname[' + product_name_counter + ']"></td>' +
        '<td><select class="form-control selectpicker dysm_' + sm_counter + ' sm " data-live-search="true" name="sm[' + sm_counter + ']" id="sm[' + sm_counter + ']">' + '<option>Please select a Employee code</option>' + '</select></td>' +
        '<td><input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="spl[' + spl_counter + ']"></td>' +
        '<td><input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="quantity[' + product_quantity_counter + ']"></td>' +
        '<td><input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="price[' + product_price_counter + ']"></td>' +
        '<td><input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="discount[' + product_discount_counter + ']"></td>' +
        '<td><input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="amount[' + product_amount_counter + ']"></td>' +
        '<td><a href="#" class="remove">Delete</td>' +
        '</tr>';
    $('.detail').append(tr);

    //increamenting the counter
    ++product_barcode_counter;
    ++till_check_counter;
    ++product_name_counter;
    ++product_quantity_counter;
    ++sm_counter;
    ++spl_counter;
    ++product_price_counter;
    ++product_discount_counter;
    ++product_amount_counter;

    //setting the validation rules for every product attribute by calling the function
    createValidation();
    get_barcodes();
    get_employee_codes();

}

    $('#save_btn').on('click', function () {
        var barcode = $('#barcode  option:selected').val();
        var productname = $('#brcode_product').val();
        var sm = $('#sm  option:selected').val();
        var spl = $('#spl').val();
        var quantity = $('#quantity').val();
        var price = $('#price').val();
        var discount = $('#discount').val();
        var amount = $('#amount').val();

        var dataString = 'barcode=' + barcode + '&productname=' + productname + '&sm=' + sm + '&spl=' + spl + '&quantity' + quantity + '&price=' + price + '&discount=' + discount + '&amount=' + amount;
        $.ajax({
        url: "http://localhost/retail/main/store",
        type: "POST",
        data: {
            /*barcode: barcode,
            productname: productname,
            sm: sm,
            spl: spl,
            quantity: quantity,
            price: price,
            discount: discount,
            amount: amount*/
            data:$('#inventory_form').serialize()
        },
        success: function (res) {
            alert(res);
        }

    });
</code>```

Here is my Conroller code :

```<code>public function store(){

            /* echo ($_POST['barcode']);
             echo "<br/>";
             echo ($_POST['productname']);
             echo "<br/>";
             echo ($_POST['smsm']);
             echo "<br/>";
             echo ($_POST['spl']);
             echo "<br/>";
             echo ($_POST['quantity']);
             echo "<br/>";
             echo ($_POST['price']);
             echo "<br/>";
             echo ($_POST['discount']);
             echo "<br/>";
             echo ($_POST['amount']);
             echo "<br/>";*/

        //echo $this->input->post('barcode');

    if ($this->session->userdata('status')== 1) {
         for ($i = 0; $i < count($_POST['productname']); $i++) {

         $order_id = $this->session->userdata('id');
         $product_name = $this->input->post('productname')[$i];
         $barcode = $this->input->post('barcode')[$i];
         $spl= $this->input->post('spl')[$i];
         $sm= $this->input->post('sm')[$i];
         $quantity = $this->input->post('quantity')[$i];
         $price = $this->input->post('price')[$i];
         $discount =$this->input->post('discount')[$i];
         $amount = $this->input->post('amount')[$i];

        $data = array(

             'order_id'=> $order_id,
             'product_name'=>$product_name,
             'barcode'=> $barcode,
             'sm'=> $sm,
             'spl'=> $spl,
             'quantity'=>$quantity,
             'price'=>$price,
             'discount'=> $discount,
             'amount'=> $amount,

        );

             $this->Sale_model->insert_sales_data($data);
             echo "Data inserted successfully!";

         }
      }

      else
      {
          redirect('login');
      }

    }
</code>```

I am using Codeigniter .Please tell me how can i  the functionality that i mentioned above?

答:
```<code>$('#save_btn').on('click', function () { var formdataString = $("#inventory_form"); $.ajax({ url: "http://localhost/retail/main/store", type: "POST", data: formdataString.serialize(), success: function (res) { alert(res); } }); });
</code>```

Body:
I want to save the table having multiple rows that is generated dynamically when i try to save a data only first letter is saved in database. and when i try to save the next row it says 500 error in console. i want to save all the data of all the rows one by one in a database how can i achive this?

Here is my code :

                    <?php $data = array(
                        'id'=>'inventory_form',
                        ); ?>
                    <?php  echo form_open('main/store',$data); ?>

                                No
                                ~
                                Barcode
                                Product Name
                                SM
                                SPL
                                Quantity
                                Price
                                Discount
                                Amount
                                <input type="button" value="+" id="add" class="btn btn-primary add_inv_row">

                                    1
                                    <input type="checkbox" id="till_check" class="is_checked" name="till_check[]" value="Bike">

                                        <select name="barcode[]" id="barcode" class="form-control selectpicker barcode" data-live-search="true">
                                        <option value="">Please select a barcode</option>
                                        <?php  foreach($barcodes as $barcode) :?>
                                        <option value="<?php echo $barcode->barcode; ?>"><?php echo $barcode->barcode; ?></option>
                                        <?php endforeach; ?>
                                        </select>

                                    <input type="text" id="brcode_product" class="form-control productname" name="productname[]">

                                        <select name="sm[]" id="sm" class="form-control selectpicker sm" data-live-search="true">
                                        <option value="">Please select a Employee code</option>
                                        <?php  foreach($employee_codes as $employee_code) :?>
                                        <option value="<?php echo $employee_code->emp_code; ?>"><?php echo $employee_code->emp_code; ?></option>
                                        <?php endforeach; ?>
                                        </select>

                                    <input type="text" id="spl" class="form-control spl" name="spl[]">
                                    <input type="text" id="quantity" class="form-control quantity" name="quantity[]">
                                    <input type="text" id="price" class="form-control price" name="price[]">
                                    <input type="text" id="discount" class="form-control discount" name="discount[]">
                                    <input type="text" id="amount" class="form-control amount" name="amount[]">
                                    Delete

                                <button class="btn btn-success" id="save_btn" type="submit" name="sale_submit_btn">Save</button>
                                0

                    <?php echo form_close(); ?>

My Javascript code :-

function total() {
    var t = 0;
    $('.amount').each(function (i, e) {
        var amt = $(this).val() - 0;
        t += amt;
    });
    $('.total').html(t);
}

function addnewrow() {
    var n = ($('.detail tr').length - 0) + 1;

    var tr = '
' +
        '' + n + '	' +
        '<input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="till_check[' + till_check_counter + ']">	' +
        '<select class="form-control barcode selectpicker  dyselect_' + product_barcode_counter + '" data-live-search="true" name="barcode[' + product_barcode_counter + ']" id="barcode[' + product_barcode_counter + ']">' + '<option>Please select a bar code</option>' + '</select>	' +
        '<input type="text" class="form-control prdctn_' + product_name_counter + ' productname"  id="brcode_product['+product_name_counter+']"  name="productname[' + product_name_counter + ']" id="productname[' + product_name_counter + ']">	' +
        '<select class="form-control selectpicker dysm_' + sm_counter + ' sm " data-live-search="true" name="sm[' + sm_counter + ']" id="sm[' + sm_counter + ']">' + '<option>Please select a Employee code</option>' + '</select>	' +
        '<input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="spl[' + spl_counter + ']">	' +
        '<input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="quantity[' + product_quantity_counter + ']">	' +
        '<input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="price[' + product_price_counter + ']">	' +
        '<input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="discount[' + product_discount_counter + ']">	' +
        '<input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="amount[' + product_amount_counter + ']">	' +
        'Delete	' +
        '
';
    $('.detail').append(tr);

    //increamenting the counter
    ++product_barcode_counter;
    ++till_check_counter;
    ++product_name_counter;
    ++product_quantity_counter;
    ++sm_counter;
    ++spl_counter;
    ++product_price_counter;
    ++product_discount_counter;
    ++product_amount_counter;

    //setting the validation rules for every product attribute by calling the function
    createValidation();
    get_barcodes();
    get_employee_codes();

}

    $('#save_btn').on('click', function () {
        var barcode = $('#barcode  option:selected').val();
        var productname = $('#brcode_product').val();
        var sm = $('#sm  option:selected').val();
        var spl = $('#spl').val();
        var quantity = $('#quantity').val();
        var price = $('#price').val();
        var discount = $('#discount').val();
        var amount = $('#amount').val();

        var dataString = 'barcode=' + barcode + '&productname=' + productname + '&sm=' + sm + '&spl=' + spl + '&quantity' + quantity + '&price=' + price + '&discount=' + discount + '&amount=' + amount;
        $.ajax({
        url: "http://localhost/retail/main/store",
        type: "POST",
        data: {
            /*barcode: barcode,
            productname: productname,
            sm: sm,
            spl: spl,
            quantity: quantity,
            price: price,
            discount: discount,
            amount: amount*/
            data:$('#inventory_form').serialize()
        },
        success: function (res) {
            alert(res);
        }

    });

Here is my Conroller code :

public function store(){

            /* echo ($_POST['barcode']);
             echo "
";
             echo ($_POST['productname']);
             echo "
";
             echo ($_POST['smsm']);
             echo "
";
             echo ($_POST['spl']);
             echo "
";
             echo ($_POST['quantity']);
             echo "
";
             echo ($_POST['price']);
             echo "
";
             echo ($_POST['discount']);
             echo "
";
             echo ($_POST['amount']);
             echo "
";*/

        //echo $this->input->post('barcode');

    if ($this->session->userdata('status')== 1) {
         for ($i = 0; $i < count($_POST['productname']); $i++) {

         $order_id = $this->session->userdata('id');
         $product_name = $this->input->post('productname')[$i];
         $barcode = $this->input->post('barcode')[$i];
         $spl= $this->input->post('spl')[$i];
         $sm= $this->input->post('sm')[$i];
         $quantity = $this->input->post('quantity')[$i];
         $price = $this->input->post('price')[$i];
         $discount =$this->input->post('discount')[$i];
         $amount = $this->input->post('amount')[$i];

        $data = array(

             'order_id'=> $order_id,
             'product_name'=>$product_name,
             'barcode'=> $barcode,
             'sm'=> $sm,
             'spl'=> $spl,
             'quantity'=>$quantity,
             'price'=>$price,
             'discount'=> $discount,
             'amount'=> $amount,

        );

             $this->Sale_model->insert_sales_data($data);
             echo "Data inserted successfully!";

         }
      }

      else
      {
          redirect('login');
      }

    }

I am using Codeigniter .Please tell me how can i  the functionality that i mentioned above?


来源: stackexchange

问:
Why can't direct routing be used for distributed data with a secondary index?
I'm reading the following article: Elements of Scale: Composing and Scaling Data platforms

I'm stuck on understanding the following sentences:

A secondary index is an index that isn’t on the primary key. This means the data will not be partitioned by the values in the index. Directed routing via a hash function is no longer an option. We have to broadcast requests to all machines.

Can anyone explain why this is the case? I am a beginner to data platforms but have gotten so far and understand the article.

Specifically, why can't we look up values in the secondary index for their primary key, then look up their location via a hash function on that primary key? Why broadcast requests to all machines?

Thank you for your time

答:
For the examples they are giving the data has been distributed over 4 nodes. Each node has a secondary index but only for values on that node. The secondary index does not have all records on all nodes. So a caller wanting to search would need to send to all nodes.

Eg with just 2 nodes

Node 1 has (1,a) (2,a) (3,b)

Node 2 has (100,a) (105,c)

Node 1 has a primary index 1,2,3. And a secondary index a,a,b

Node 2 has a primary index 100,105. And a secondary index a,c

A caller wanting to search for 'c' would need to broadcast to both nodes to search the two secondary indexs.

If however you maintain a complete copy of the secondary index a,a,a,b,c somewhere you could query that index and then go directly to the target node. But this has a lot more complications in practice than you might expect.

Edit 22 June. When you try an maintain a secondary index on a third node then you have the following complications to consider.

Insert/edit operations now involve 2 or even 3 nodes so you need to implement a two phase commit protocol of some kind, or alternative schemes.

As more nodes are involved, you may find the overall reliability decreases as the MTBF is lower.

You need to consider what happens with network partitioning.

Maintainance operations might be harder. How do you effectively validate an index is correct without generating too much network traffic for example.

How will updates edit the index node? Are clients responsible for this, or do the main storage nodes update index nodes?

A good place to learn more is to review the CAP theorem, look into 2 phase commit schemes, and potentially look at some of the IEEE papers published in the distributed systems journal.

ContentLicense: CC BY-SA 3.0


问:
When connected to proxy networks, Grafana does not display the dashboards for Cloudwatch
While choosing the data source for ElasticSearch,I see a direct connect option or connect it via proxy whereas it is not present for Cloudwatch. When connected to proxy networks, Grafana does not display the dashboards. Tried setting proxy for windows in custom.ini file but it doesnt help. Request for a solution.

Please include this information:

What Grafana version are you using?
Grafana 4.3.1
What datasource are you using?
CloudWatch
What OS are you running grafana on?
Windows7
What did you do?
Tried setting proxy in custom.ini file

答:
The direct/proxy setting defines whether connections to the data source should be made "direct" from the browser (requiring proper CORS setup, etc) or whether to "proxy" them through the Grafana server.

If you need Grafana to use an HTTP(S) proxy for connections made by the Grafana server, then you need to set the environment variable HTTP_PROXY="http://proxyIp:proxyPort" and Grafana (as well as any other programs using the standard golang http libraries) will use the defined proxy.


问:
Installing gremlin server manually with TITAN DB
I am trying to upgrade my tinkertop version to 3.2.4 version. currently I am using titan-1.0.0-hadoop1 version. since it is not embedded with the recent tinkertop(gremlin) version. I want to upgrade.

I did following steps:
     1. Downloaded gremlin-server 3.2.4 version, unzip it
     2. Edited the GREMLIN_SERVER_HOME/conf/gremlin-server.yaml and include the
        following settings to the defaults:

```<code>           graphs: {
                  graph: conf/titan-berkeleydb.properties}
                  plugins:
                   - aurelius.titan
                   }
  3. then in terminal I ran the following command
      bin/gremlin-server.sh -i com.thinkaurelius.titan titan-core 1.0.0
</code>```

after third step I am getting the following error

DependencyGrabber$_copyTo_closure6 - Copying - /home/titan123/Downloads/apache-tinkerpop-gremlin-server-3.2.4/ext/titan-core/plugin/jsr305-3.0.0.jar
Could not install the dependency: java.lang.NullPointerException: Cannot get property 'mainAttributes' on null object

答:
This is going to be quite a bit of effort on your part. I highly suggest using JanusGraph instead of Titan if this is a concern. https://github.com/JanusGraph/janusgraph/pull/78 addressed updating the forked Titan codebase (now JanusGraph) to 3.2.3

Titan is no longer maintained, but has been forked by the JanusGraph project which has a lot of active development on it. The current release (0.1.1 as of this writing) is backwards compatible with Titan 1.0.0

http://janusgraph.org/

Body:
I am trying to upgrade my tinkertop version to 3.2.4 version. currently I am using titan-1.0.0-hadoop1 version. since it is not embedded with the recent tinkertop(gremlin) version. I want to upgrade.

I did following steps:
     1. Downloaded gremlin-server 3.2.4 version, unzip it
     2. Edited the GREMLIN_SERVER_HOME/conf/gremlin-server.yaml and include the
        following settings to the defaults:

           graphs: {
                  graph: conf/titan-berkeleydb.properties}
                  plugins:
                   - aurelius.titan
                   }
  3. then in terminal I ran the following command
      bin/gremlin-server.sh -i com.thinkaurelius.titan titan-core 1.0.0

after third step I am getting the following error

DependencyGrabber$_copyTo_closure6 - Copying - /home/titan123/Downloads/apache-tinkerpop-gremlin-server-3.2.4/ext/titan-core/plugin/jsr305-3.0.0.jar
Could not install the dependency: java.lang.NullPointerException: Cannot get property 'mainAttributes' on null object


问:
Prevent Spring Data for Mongo to convert ids to ObjectId
I'm using Spring Data for Mongo on an existing database. The previous application used plain strings for ids instead of ObjectId.

My problem is that Spring Data insists on converting the strings to ObjectId, which makes all queries by id to fail.

For example, when I do repository.findOne(''), the query executed is { "_id" : { "$oid" : "50cf9f34458cf91108ceb2b4"}} when it should be { "_id" : "50cf9f34458cf91108ceb2b4" }

Is there a way to avoid Spring Data to convert string ids to ObjectId?

Thanks!

Diego

答:
I've faced same problem and my solution was like below: </p>

```<code>  @Bean
  public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, CustomConversions conversions) {
    MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), context) {
      @Override
      public void afterPropertiesSet() {
        conversions.registerConvertersIn(conversionService);
      }
    };
    converter.setCustomConversions(conversions);
    return converter;
  }
</code>```

<p>The idea is to prevent default converters registration. </p>

Body:
I've faced same problem and my solution was like below:

  @Bean
  public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, CustomConversions conversions) {
    MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), context) {
      @Override
      public void afterPropertiesSet() {
        conversions.registerConvertersIn(conversionService);
      }
    };
    converter.setCustomConversions(conversions);
    return converter;
  }

The idea is to prevent default converters registration.


问:
laravel 5.4 undefined variable in view
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

```<code>public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}
</code>```

And this is the show function within the same controller -

```<code>public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }
</code>```

The error message I'm getting is -

```<code>Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

And in the show.blade.php this is a sample of what I have -

```<code><h1>{{ $data4page->h4Ttle }}</h1>
<p>{{ $data4page->description }}</p>
<h4>{{ $data4page->h4Ttle }}</h4>
</code>```

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

```<code>return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);
</code>```

Update: I earlier had typos but now the error I get is -

```<code>undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

This is the show.blade.php -

```<code>@extends('main')
@section('title')
@section('content')
      <div class="app-template">
         <main class="wrapperMain">
            <div class="">
               <aside class="navSidebar">
                  <nav class="navProperty">
                     <h1 class="navProperty-title">{{ $data4page->h1Ttle }}</h1>
                  </nav>
                  <footer class="footerProperty">
                     <div class="upcomingSchedule">
                        <h4 class="upcomingSchedule-heading">{{ $data4page->h4Ttle }}</h4>
                     </div>
                  </footer>
               </aside>
            </div>
            <div class="content content--withSidebar">
               <div class="lead--Home">
                  <p>{{ $data4page->description }}</p>
               </div>
            </div>
         </main>
@endsection
</code>```

答:
You need to loop through the collection to get the value</p>

```<code>@section('content')
     <div class="app-template">
        <main class="wrapperMain">
           @foreach ($data4page as $d4p)
           <div class="">
              <aside class="navSidebar">
                 <nav class="navProperty">
                    <h1 class="navProperty-title">{{ $d4p->h1Ttle }}</h1>
                 </nav>
                 <footer class="footerProperty">
                    <div class="upcomingSchedule">
                       <h4 class="upcomingSchedule-heading">{{ $d4p->h4Ttle }}</h4>
                    </div>
                 </footer>
              </aside>
           </div>
           <div class="content content--withSidebar">
              <div class="lead--Home">
                 <p>{{ $d4p->description }}</p>
              </div>
           </div>
           @endforeach
        </main>
@endsection
</code>```

Title: laravel 5.4 undefined variable in view

Body:
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}

And this is the show function within the same controller -

public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }

The error message I'm getting is -

Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)

And in the show.blade.php this is a sample of what I have -

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

{{ $data4page->h4Ttle }}

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);

Update: I earlier had typos but now the error I get is -

undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)

This is the show.blade.php -

@extends('main')
@section('title')
@section('content')

{{ $data4page->h1Ttle }}

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

@endsection

Body:
You need to loop through the collection to get the value

@section('content')
     <div class="app-template">
        <main class="wrapperMain">
           @foreach ($data4page as $d4p)
           <div class="">
              <aside class="navSidebar">
                 <nav class="navProperty">
                    <h1 class="navProperty-title">{{ $d4p->h1Ttle }}</h1>
                 </nav>
                 <footer class="footerProperty">
                    <div class="upcomingSchedule">
                       <h4 class="upcomingSchedule-heading">{{ $d4p->h4Ttle }}</h4>
                    </div>
                 </footer>
              </aside>
           </div>
           <div class="content content--withSidebar">
              <div class="lead--Home">
                 <p>{{ $d4p->description }}</p>
              </div>
           </div>
           @endforeach
        </main>
@endsection


问:
Signup page with additional options
I'm trying to create a pricing page where the user first selects the topic, and then they selects the plan.

I cant figure out to do both on one page, as the topic will be the same for all of the plans, but each plan is different.

I have a hidden field called topic which holds the selected topic, but how do I know which submit button will be clicked.

Heres an image with what I'm trying to achieve.

http://cl.ly/3N3b3U0J261r3f1T3q3i

答: Hmm, maybe, you could add a name to each form and then check in the params which form it is.</p>

ContentLicense: CC BY-SA 2.5

Title: Signup page with additional options


问:
Can't center divs HTML CSS
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01">
  </div>

  <div id="bg_02">
  </div>

  <div id="bg_03">
  </div>

  <div id="bg_04">
  </div>

  <div id="bg_05">
  </div>
</div></code>```

答:
p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.center_div{
text-align:center;
margin:20px auto;
display:flex;
justify-content:center;
align-items:center;
}

.common_div{
width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 3%;
  display:inline-block;
}

#bg_01 {
  background-color: #80b3ff;

}

#bg_02 {
  background-color: #afe9af;

}

#bg_03 {
  background-color: #ffb380;

}

#bg_04 {
  background-color: #ffaaaa;

}

#bg_05 {
  background-color: #eeaaff;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName" >
    <p>Colour</p>
  </div>
  <div class="center_div">
  <div id="bg_01" class="common_div">
  </div>

  <div id="bg_02" class="common_div">
  </div>

  <div id="bg_03" class="common_div">
  </div>

  <div id="bg_04" class="common_div">
  </div>

  <div id="bg_05" class="common_div">
  </div>
  </div>

</div></code>```

Is this the same that you are looking for?

Hope this helps.

Title: Can't center divs HTML CSS

Body:
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

Colour

Body:
p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.center_div{
text-align:center;
margin:20px auto;
display:flex;
justify-content:center;
align-items:center;
}

.common_div{
width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 3%;
  display:inline-block;
}

#bg_01 {
  background-color: #80b3ff;

}

#bg_02 {
  background-color: #afe9af;

}

#bg_03 {
  background-color: #ffb380;

}

#bg_04 {
  background-color: #ffaaaa;

}

#bg_05 {
  background-color: #eeaaff;

}

<div id="page">
  <div id="pageName" >
    <p>Colour</p>
  </div>
  <div class="center_div">
  <div id="bg_01" class="common_div">
  </div>

  <div id="bg_02" class="common_div">
  </div>

  <div id="bg_03" class="common_div">
  </div>

  <div id="bg_04" class="common_div">
  </div>

  <div id="bg_05" class="common_div">
  </div>
  </div>

</div>

Is this the same that you are looking for?

Hope this helps.


问:
c language if wrong number is entered ask the user again
I am trying to get the user to re enter the the number again if they enter a value of less than ten
i am certain the problem lies with the while statement.
this what i have

```<code>printf_s("Enter the player first name: ");
scanf_s("%s", names[i], 25);  //enters name and creates a newline <enter key>//

printf_s("Minimum number to stop in a turn: ");
scanf_s("%d", &min_number, sizeof(int));
do {
printf_s("please enter a number greater or egual to 10");
} while (min_number <= 10);
        scanf_s("%d ", &min_number);
        printf_s("please enter a number greater or equal to 10\n\n");
</code>```

is a do while loop the best option or should i look at using another type of loop

enter image description here

答:
As I was corrected, thoughfully scanf returns the number of receiving arguments successfully assigned.
Here is a fixed version:

```<code>void main(){
        int num = 0;
     while(num <=10){
         scanf("%d ", &num);
         printf_s("please enter a number greater or equal to 10\n\n");
     }
 }
</code>```

After the authour edited the code in his question and upon his request:

```<code>do {
        printf_s("please enter a number greater or egual to 10\n\n");
        scanf_s("%d", &min_number);
    } while (min_number < 10);
</code>```

When doing the do/while loop the body of the loop is in the
 do{body goes here}while(some condition);.

After another edit, on author request:

```<code>printf_s("Minimum number to stop in a turn: ");
    scanf_s("%d", &min_number, sizeof(int));

    while(min_number < 10){
        printf_s("please enter a number greater or egual to 10\n\n");
        scanf_s("%d", &min_number);

    }
</code>```

This will do the following it will ask for "Minimum number to stop in a turn: " if it is greater or equal to 10 it will continue after the loop. If it is not it will give clarification "please enter a number greater or egual to 10" and will receive another input. It will loop until it receive greater or egual to 10.

Body:
I am trying to get the user to re enter the the number again if they enter a value of less than ten
i am certain the problem lies with the while statement.
this what i have

printf_s("Enter the player first name: ");
scanf_s("%s", names[i], 25);  //enters name and creates a newline <enter key>//

printf_s("Minimum number to stop in a turn: ");
scanf_s("%d", &min_number, sizeof(int));
do {
printf_s("please enter a number greater or egual to 10");
} while (min_number <= 10);
        scanf_s("%d ", &min_number);
        printf_s("please enter a number greater or equal to 10\n\n");

is a do while loop the best option or should i look at using another type of loop

enter image description here

Body:
As I was corrected, thoughfully scanf returns the number of receiving arguments successfully assigned.
Here is a fixed version:

void main(){
        int num = 0;
     while(num <=10){
         scanf("%d ", &num);
         printf_s("please enter a number greater or equal to 10\n\n");
     }
 }

After the authour edited the code in his question and upon his request:

do {
        printf_s("please enter a number greater or egual to 10\n\n");
        scanf_s("%d", &min_number);
    } while (min_number < 10);

When doing the do/while loop the body of the loop is in the
 do{body goes here}while(some condition);.

After another edit, on author request:

printf_s("Minimum number to stop in a turn: ");
    scanf_s("%d", &min_number, sizeof(int));

    while(min_number < 10){
        printf_s("please enter a number greater or egual to 10\n\n");
        scanf_s("%d", &min_number);

    }

This will do the following it will ask for "Minimum number to stop in a turn: " if it is greater or equal to 10 it will continue after the loop. If it is not it will give clarification "please enter a number greater or egual to 10" and will receive another input. It will loop until it receive greater or egual to 10.


问:
Optimize an algorithm which is executed a lot of times
I have a couple of for loops and the innermost one will be executed a lot of times. This innermost loop contains some heavy calculations using numpy, so all of this is taking a lot of time. So I am trying to optimize the innermost loop.

The most inner-loop contains the following logic:

I have two numpy-arrays (much larger in real life):

```<code>left = np.asarray([0.4, 0.2, 0.2, 0.7, 0.6, 0.2, 0.3])
right= np.asarray([0.2, 0.7, 0.3, 0.2, 0.1, 0.9, 0.7])
</code>```

These are compared to a threshold to see if I should go left or right. If left[x] > 0.55 and right[x] < 0.45 I want to go left.
If left[x] < 0.55 and right[x] > 0.45 I want to go right.
I have solved this by creating two boolean arrays, one for left and one for right, according to:

```<code>leftListBool = ((left > 0.55)*1 + (right < 0.45)*1 - 1) > 0
rightListBool = ((right > 0.55)*1 + (left < 0.45)*1 - 1) > 0
</code>```

Which for the above example gives me:

```<code>leftListBool = [False False False  True  True False False]
rightListBool = [False  True False False False  True  True]
</code>```

But I am not allowed to go left if I went left the last time (and same for right). Therefore I loop these list according to:

```<code>wentLeft = False
wentRight = False
a = 0
for idx, v in enumerate(leftListBool):
    if leftListBool[idx] and not wentRight:
        a += DoAThing(idx)
        wentLeft = False
        wentRight = True
    elif rightListBool[idx] and not wentLeft:
        a += DoAnotherThing(idx)
        wentLeft = True
        wentRight = False
</code>```

Where DoAThing() and DoAnotherThing() simply fetches a value from a numpy-array.

This is as far as I have come in terms of optimization (it was much worse before). Note that I need to do DoAThing() and DoAnotherThing() in the correct orders, since they depend on the previous value.

What have I tried?

My first idea was to create a unified list of leftListbool and rightListBool, which would look like (left = 1 and right = -1):

```<code>unified = [0 1 0 -1 -1 1 1]
</code>```

But I am stuck to do this in a more optimal way than:

```<code>buyListBool.astype(int)-sellListBool.astype(int)
</code>```

But even if I achieve this, I need to only include the first value, if for example I have two 1 following each other, which would result in:

```<code>unified = [0 1 0 -1 0 1 0]
</code>```

In which case I could reduce the for-loop to:

```<code>for i in unified:
    if i == 1:
        a += DoAThing(a)
    elif i == -1:
        a += DoAnotherThing(a)
</code>```

But even this for-loop can mayby be optimized using some numpy-magic which I haven't figured out yet.

Complete runable code:

```<code>start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,3)
        left = res[:,0]
        right = res[:,1]
        valList = res[:,2]

        #These two statements can probably be optimized
        leftListBool = ((left > topLimit)*1 + (right < bottomLimit)*1 - 1) > 0
        rightListBool = ((right > topLimit)*1 + (left < bottomLimit)*1 - 1) > 0

        wentLeft = False
        wentRight = False
        a=0
        #Hopefully this loop can be optimized
        for idx, v in enumerate(leftListBool):
            if leftListBool[idx] and not wentRight:
                a += valList[idx]
                wentLeft = False
                wentRight = True
            elif rightListBool[idx] and not wentLeft:
                a += valList[idx]
                wentLeft = True
                wentRight = False

end = time.time()
print(end - start)
</code>```

答:
If you need to loop over your sequence and you care about performance you shouldn't use numpy.arrays. NumPy arrays are great when NumPy can do the loop, but if you have to loop over it yourself it will be slow (I covered the details why iterations over arrays are quite slow in another answer recently, if you want to take a look: "convert np array to a set takes too long").

You could simply use tolist and zip to avoid the iterating numpy-array overhead:

```<code>import time
import numpy as np

start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,2)
        left = res[:,0].tolist()      # tolist!
        right = res[:,1].tolist()     # tolist!

        wentLeft = False
        wentRight = False
        a=0

        for leftitem, rightitem in zip(left, right):
            if leftitem > topLimit and rightitem < bottomLimit and not wentRight:
                wentLeft, wentRight = False, True
            elif rightitem > topLimit and leftitem < bottomLimit and not wentLeft:
                wentLeft, wentRight = True, False

end = time.time()
print(end - start)
</code>```

This reduced the runtime by 30% on my computer.

You could also do the tolist conversion lateron (which may or may not be faster):

```<code>start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,2)
        left = res[:,0]
        right = res[:,1]

        # use tolist after the comparisons
        leftListBool = ((left > topLimit) & (right < bottomLimit)).tolist()
        rightListBool = ((right > topLimit) & (left < bottomLimit)).tolist()

        wentLeft = False
        wentRight = False
        a=0
        #Hopefully this loop can be optimized
        for idx in range(len(leftListBool)):  # avoid direct iteration over an array
            if leftListBool[idx] and not wentRight:
                #a += DoAThing(a)
                wentLeft = False
                wentRight = True
            elif rightListBool[idx] and not wentLeft:
                #a += DoAnotherThing(a)
                wentLeft = True
                wentRight = False

end = time.time()
print(end - start)
</code>```

That was roughly as fast as the other approach but when left and right get much bigger than 200 elements it could become much faster.

However that was just based on the algorithm without knowledge of DoAThing and DoAnotherThing. It's possible that you could construct them in a way that allowed vectorized operations (which could speed it up by an order of magnitude without using lists). That's much tougher though and I don't know what these functions are doing.

ContentLicense: CC BY-SA 4.0

Body:
I have a couple of for loops and the innermost one will be executed a lot of times. This innermost loop contains some heavy calculations using numpy, so all of this is taking a lot of time. So I am trying to optimize the innermost loop.

The most inner-loop contains the following logic:

I have two numpy-arrays (much larger in real life):

left = np.asarray([0.4, 0.2, 0.2, 0.7, 0.6, 0.2, 0.3])
right= np.asarray([0.2, 0.7, 0.3, 0.2, 0.1, 0.9, 0.7])

These are compared to a threshold to see if I should go left or right. If left[x] > 0.55 and right[x] < 0.45 I want to go left.
If left[x] < 0.55 and right[x] > 0.45 I want to go right.
I have solved this by creating two boolean arrays, one for left and one for right, according to:

leftListBool = ((left > 0.55)*1 + (right < 0.45)*1 - 1) > 0
rightListBool = ((right > 0.55)*1 + (left < 0.45)*1 - 1) > 0

Which for the above example gives me:

leftListBool = [False False False  True  True False False]
rightListBool = [False  True False False False  True  True]

But I am not allowed to go left if I went left the last time (and same for right). Therefore I loop these list according to:

wentLeft = False
wentRight = False
a = 0
for idx, v in enumerate(leftListBool):
    if leftListBool[idx] and not wentRight:
        a += DoAThing(idx)
        wentLeft = False
        wentRight = True
    elif rightListBool[idx] and not wentLeft:
        a += DoAnotherThing(idx)
        wentLeft = True
        wentRight = False

Where DoAThing() and DoAnotherThing() simply fetches a value from a numpy-array.

This is as far as I have come in terms of optimization (it was much worse before). Note that I need to do DoAThing() and DoAnotherThing() in the correct orders, since they depend on the previous value.

What have I tried?

My first idea was to create a unified list of leftListbool and rightListBool, which would look like (left = 1 and right = -1):

unified = [0 1 0 -1 -1 1 1]

But I am stuck to do this in a more optimal way than:

buyListBool.astype(int)-sellListBool.astype(int)

But even if I achieve this, I need to only include the first value, if for example I have two 1 following each other, which would result in:

unified = [0 1 0 -1 0 1 0]

In which case I could reduce the for-loop to:

for i in unified:
    if i == 1:
        a += DoAThing(a)
    elif i == -1:
        a += DoAnotherThing(a)

But even this for-loop can mayby be optimized using some numpy-magic which I haven't figured out yet.

Complete runable code:

start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,3)
        left = res[:,0]
        right = res[:,1]
        valList = res[:,2]

        #These two statements can probably be optimized
        leftListBool = ((left > topLimit)*1 + (right < bottomLimit)*1 - 1) > 0
        rightListBool = ((right > topLimit)*1 + (left < bottomLimit)*1 - 1) > 0

        wentLeft = False
        wentRight = False
        a=0
        #Hopefully this loop can be optimized
        for idx, v in enumerate(leftListBool):
            if leftListBool[idx] and not wentRight:
                a += valList[idx]
                wentLeft = False
                wentRight = True
            elif rightListBool[idx] and not wentLeft:
                a += valList[idx]
                wentLeft = True
                wentRight = False

end = time.time()
print(end - start)

Body:
If you need to loop over your sequence and you care about performance you shouldn't use numpy.arrays. NumPy arrays are great when NumPy can do the loop, but if you have to loop over it yourself it will be slow (I covered the details why iterations over arrays are quite slow in another answer recently, if you want to take a look: "convert np array to a set takes too long").

You could simply use tolist and zip to avoid the iterating numpy-array overhead:

import time
import numpy as np

start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,2)
        left = res[:,0].tolist()      # tolist!
        right = res[:,1].tolist()     # tolist!

        wentLeft = False
        wentRight = False
        a=0

        for leftitem, rightitem in zip(left, right):
            if leftitem > topLimit and rightitem < bottomLimit and not wentRight:
                wentLeft, wentRight = False, True
            elif rightitem > topLimit and leftitem < bottomLimit and not wentLeft:
                wentLeft, wentRight = True, False

end = time.time()
print(end - start)

This reduced the runtime by 30% on my computer.

You could also do the tolist conversion lateron (which may or may not be faster):

start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,2)
        left = res[:,0]
        right = res[:,1]

        # use tolist after the comparisons
        leftListBool = ((left > topLimit) & (right < bottomLimit)).tolist()
        rightListBool = ((right > topLimit) & (left < bottomLimit)).tolist()

        wentLeft = False
        wentRight = False
        a=0
        #Hopefully this loop can be optimized
        for idx in range(len(leftListBool)):  # avoid direct iteration over an array
            if leftListBool[idx] and not wentRight:
                #a += DoAThing(a)
                wentLeft = False
                wentRight = True
            elif rightListBool[idx] and not wentLeft:
                #a += DoAnotherThing(a)
                wentLeft = True
                wentRight = False

end = time.time()
print(end - start)

That was roughly as fast as the other approach but when left and right get much bigger than 200 elements it could become much faster.

However that was just based on the algorithm without knowledge of DoAThing and DoAnotherThing. It's possible that you could construct them in a way that allowed vectorized operations (which could speed it up by an order of magnitude without using lists). That's much tougher though and I don't know what these functions are doing.


问:
Enum multiple cases with the same value in Swift
In C you could make your enums have this:

```<code>typedef enum _Bar {
    A = 0,
    B = 0,
    C = 1
} Bar;
</code>```

In Swift I want to make the equivalent. However, the compiler complains that it isn't unique. How do I tell it that I want two cases to have the same value?

```<code>enum Bar : Int {
    case A = 0
    case B = 0 // Does not work
    case C = 1
}
</code>```

I've tried

```<code>case A | B = 0
</code>```

and

```<code>case A, B = 0
</code>```

But it doesn't seem to work as I want it to.

答:
Here is another way of getting around it:</p>

```<code>enum Animal {

  case dog
  case cat
  case mouse
  case zebra

  var description: String {
    switch self {
    case .dog:
      return "dog"

    case .cat:
      return "dog"

    case .mouse:
      return "dog"

    case .zebra:
      return "zebra"

    default:
      break
    }
  }
}
</code>```

Body:
In C you could make your enums have this:

typedef enum _Bar {
    A = 0,
    B = 0,
    C = 1
} Bar;

In Swift I want to make the equivalent. However, the compiler complains that it isn't unique. How do I tell it that I want two cases to have the same value?

enum Bar : Int {
    case A = 0
    case B = 0 // Does not work
    case C = 1
}

I've tried

case A | B = 0

and

case A, B = 0

But it doesn't seem to work as I want it to.

Body:
Here is another way of getting around it:

enum Animal {

  case dog
  case cat
  case mouse
  case zebra

  var description: String {
    switch self {
    case .dog:
      return "dog"

    case .cat:
      return "dog"

    case .mouse:
      return "dog"

    case .zebra:
      return "zebra"

    default:
      break
    }
  }
}


问:
Dynamically assigning variable names JavaScript
I am trying to dynamically assign variable names using the user's input. For example:

```<code>var input = document.querySelector('input');

for(var i = 0; i < 10; i++){
   var newVariableName = //input.value;
}
</code>```

Any help would be very much appreciated.

Thank you,
Scratch Cat

答:
Everything in JavaScript is an object. The way JavaScript works, you can add properties to objects in two ways:

Specify them the fixed way (e.g. obj.propertyName = 'Value')

Specify them using array notation (e.g. obj[propertyName] = 'Value'). In this case, note that propertyName is a string value.

In both cases, the result will be exactly the same. You could retrieve those properties likewise, e.g. obj.propertyName and obj[propertyName]. Both will return 'Value'.

In your case, @LuudJacobs's suggestion about using the window object will most probably do the trick...

Body:
I am trying to dynamically assign variable names using the user's input. For example:

var input = document.querySelector('input');

for(var i = 0; i < 10; i++){
   var newVariableName = //input.value;
}

Any help would be very much appreciated.

Thank you,
Scratch Cat


问:
How to pass two list to multiprocessing target function and process the individual list with individual process
I have two list one list contains server name and the second list contains service list.the length of both the list is equal.

```<code>server_list = [u'server1', u'server2', u'sever3', u'server4']
servive_name = [[u'postfix', u'diamond', u'lldpd', u'ssh', u'nagios-nrpe-server'], [u'postfix', u'lldpd', u'ssh', u'nagios-nrpe-server'], [u'postfix', u'lldpd', u'ssh', u'nagios-nrpe-server'], [u'postfix', u'lldpd', u'ssh', u'nagios-nrpe-server']]
</code>```

i have this function

```<code>ssh_to_restart(server_name,services,output):
{
 // do ssh on the server and restart the service from service list
}
</code>```

what i want is each process takes the server name and the service list from the respective list (ex- server1 has to map with 1st list in the service_list and so on)and execute the ssh_to_restart() function.
also number of process created with it should be equal to the length of the server_list.
how can i achieve this with something like this code

```<code>output = multiprocessing.Queue()
processes = [multiprocessing.Process(target=ssh_to_server, args=(server_list,service_list,output))]
</code>```

EDIT:-

i tried with these codes

```<code>from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
  pool.map(ssh_to_restart,zip(server_list,service_list))
  pool.close()
  pool.join()
</code>```

but got this error

```<code>TypeError: ssh_to_restart() takes exactly 2 arguments (1 given)
</code>```

答:
i did solve the problem with

```<code>from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
pool.map(ssh_to_restart,zip(server_list,service_list))
pool.close()
pool.join()
</code>```

the error

```<code>TypeError: ssh_to_restart() takes exactly 2 arguments (1 given)
</code>```

was solved by adding double parenthesis around

```<code>ssh_to_restart((server_name,services,output)):
{
// do ssh on the server and restart the service from service list
}
</code>```

extra parentheses in the definition of insert_and_process - python treat that as a single parameter that should be a 2-item sequence. The first element of the sequence is attributed to the first variable, and the other to the second

Body:
I have two list one list contains server name and the second list contains service list.the length of both the list is equal.

server_list = [u'server1', u'server2', u'sever3', u'server4']
servive_name = [[u'postfix', u'diamond', u'lldpd', u'ssh', u'nagios-nrpe-server'], [u'postfix', u'lldpd', u'ssh', u'nagios-nrpe-server'], [u'postfix', u'lldpd', u'ssh', u'nagios-nrpe-server'], [u'postfix', u'lldpd', u'ssh', u'nagios-nrpe-server']]

i have this function

ssh_to_restart(server_name,services,output):
{
 // do ssh on the server and restart the service from service list
}

what i want is each process takes the server name and the service list from the respective list (ex- server1 has to map with 1st list in the service_list and so on)and execute the ssh_to_restart() function.
also number of process created with it should be equal to the length of the server_list.
how can i achieve this with something like this code

output = multiprocessing.Queue()
processes = [multiprocessing.Process(target=ssh_to_server, args=(server_list,service_list,output))]

EDIT:-

i tried with these codes

from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
  pool.map(ssh_to_restart,zip(server_list,service_list))
  pool.close()
  pool.join()

but got this error

TypeError: ssh_to_restart() takes exactly 2 arguments (1 given)

Body:
i did solve the problem with

from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
pool.map(ssh_to_restart,zip(server_list,service_list))
pool.close()
pool.join()

the error

TypeError: ssh_to_restart() takes exactly 2 arguments (1 given)

was solved by adding double parenthesis around

ssh_to_restart((server_name,services,output)):
{
// do ssh on the server and restart the service from service list
}

extra parentheses in the definition of insert_and_process - python treat that as a single parameter that should be a 2-item sequence. The first element of the sequence is attributed to the first variable, and the other to the second


问:
How to build Swift 3 project on Xcode 9?
Xcode 9 Release Notes says that Swift 3 compilation is supported:

One compiler for Swift 4 and Swift 3, Swift 4 and Swift 3 targets can be compiled together in the same project.

I have installed Xcode 9 beta.
But when I press Build it shows bunch of errors. Are some special preparations need to do when use Swift 3 in Xcode 9?

UPD:

Module compiled with Swift 3.1 cannot be imported in Swift 4.0

答: Select the target, goto Build Settings > Swift Language Version:


问:
How to run sails 1.0 in console mode when using typescript
Sails 1.0-beta now supports TypeScript.

To do so, you need to add something in your app.js file and run your app using node app.js instead of the usual sails lift or sails console.
While this works great to replace sails lift, I find myself missing the console mode, really handy to run quick tests.

I tried running node app.js console and node app.js --console but it just lifts the app in regular mode.
I suspect I need to change something in my app.js but I couldn't find anything in the docs.

Does anyone knows how to run sails-1.0-beta with typescript compatibility and in console mode?

答:
Hackish way

Find your sails (global) installation. Possible locations:

/usr/local/lib/node_modules/

~/.nvm/versions/node/$NODE_VERSION/node_modules

Add a line in bin/sails.js in this location (same line as your app.js)

require('typescript-require');

OR require('ts-node/register');

This will affect all sails project which use this global sails installation


问:
Order of the finalize() operations in Java
I'm trying to understand an exercise about Java's garbage collector and the finalize() method.

```<code>public class Five {
    static int x = 1;
    class String5 {
        String s;
        String5() {
            this.s = ""+(++x);
        }
        public void finalize() {
            System.out.print(s);
        }
    }

    String5 a = new String5();
    void f() {
        String5 a = new String5();
    }
    public void finalize() {
        System.out.print("H");
    }

    public static void main(String[] args) {
        Five a5 = new Five();
        a5.f();
        a5 = new Five();
        a5.f();
        System.gc();
        System.runFinalization();
    }
}
</code>```

The exercise asks me to predict the output. The correct answer was 532H. I predicted that the output should be 2H35, and I don't understand why my ordering was incorrect.

答:
According to the JLS, the Java language defines no order of the execution of finalize methods, so the actual order is an implementation detail.

JLS 12.6. Finalization of Class Instances:

The Java programming language imposes no ordering on finalize method calls. Finalizers may be called in any order, or even concurrently.

The order that you encountered seems to suggest a stack implementation - the 4th and last created instance of String5 which is eligible for garbage collection is finalized first (printing 5), followed by the 2nd and 1st (the 3rd is not eligible for garbage collection) which print 3 and 2, and finally the first Five instance is finalized and prints H.

However, different JDK implementations may produce different order.

Body:
I'm trying to understand an exercise about Java's garbage collector and the finalize() method.

public class Five {
    static int x = 1;
    class String5 {
        String s;
        String5() {
            this.s = ""+(++x);
        }
        public void finalize() {
            System.out.print(s);
        }
    }

    String5 a = new String5();
    void f() {
        String5 a = new String5();
    }
    public void finalize() {
        System.out.print("H");
    }

    public static void main(String[] args) {
        Five a5 = new Five();
        a5.f();
        a5 = new Five();
        a5.f();
        System.gc();
        System.runFinalization();
    }
}

The exercise asks me to predict the output. The correct answer was 532H. I predicted that the output should be 2H35, and I don't understand why my ordering was incorrect.


问:
Giving border to
 of table in a table
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

```<code><table>

    <tr>
        <td>A</td>
    </tr>

    <tr>
        <td>
           <table class="t_border">
              <tr>
                 <td>B</td>
              </tr>
        </td>
    </tr>
</tbody>
</code>```

答:
you can set separate style for the class .t_border, see example code..</p>

```<code><table>

    <tr>
        <td>A</td>
    </tr>

    <tr>
        <td>
           <table class="t_border">
              <tr>
                 <td>B</td>
              </tr>
        </td>
    </tr>
           </table></td></tr></table>

<style>
    .t_border
    {
        border: 1px solid red;
    }
</style>
</code>```

Title: Giving border to <tr> of table in a table

Body:
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

        A

                 B

Body:
you can set separate style for the class .t_border, see example code..

<table>

    <tr>
        <td>A</td>
    </tr>

    <tr>
        <td>
           <table class="t_border">
              <tr>
                 <td>B</td>
              </tr>
        </td>
    </tr>
           </table></td></tr></table>

<style>
    .t_border
    {
        border: 1px solid red;
    }
</style>


问:
Initialize a DbSet without a Context in C# - Mocking
I'm writing a Test Cases for a Common generic methods, In that I don't have any database configuration, but the method generic method is handling the IQueryable object. So, I tried the following code

```<code>public static DbSet<Person> GetPersonDbSet() {
    DbSet<Person> record = null;
    record.Add(new Person() {
        PersonId = 1,
        FirstName = "Ram",
        LastName = "Kumar"
    });

    record.Add(new Person() {
        PersonId = 2,
        FirstName = "Raj",
        LastName = "Kumar"
    });

    return record;
}
</code>```

Original Method:

```<code>public static class MyLib {
    public static IQueryable Pagination<T>(IOrderedQueryable<T> query, int offset, int limit) {

        // Validation Code (...)

        // Main Logic
        return query.Skip(offset).Take(limit);

    }
}
</code>```

Test Method:

```<code>[Fact]
public void CheckPagination() {
    var query = GetPersonDbSet().OrderBy(i => i.FirstName);

    var result = MyLib.Pagination(query, 1, 5);
    int count = result.Count();
    Assert.True(count > 0);
}
</code>```

I got an exception in GetPersonDbSet() while on adding the entity, because the variable DbSet<Person> record was initialized with null. Kindly assist me how to Initialize and achieve this without a context (because in this project I'm not using any Database Context).

答:
I'd start with:

DbSet<Person> record = new TestDbSet<Person>();

and have a read of https://msdn.microsoft.com/en-us/library/dn314431(v=vs.113).aspx (which includes the definition of TestDbSet).

Body:
I'm writing a Test Cases for a Common generic methods, In that I don't have any database configuration, but the method generic method is handling the IQueryable object. So, I tried the following code

public static DbSet<Person> GetPersonDbSet() {
    DbSet<Person> record = null;
    record.Add(new Person() {
        PersonId = 1,
        FirstName = "Ram",
        LastName = "Kumar"
    });

    record.Add(new Person() {
        PersonId = 2,
        FirstName = "Raj",
        LastName = "Kumar"
    });

    return record;
}

Original Method:

public static class MyLib {
    public static IQueryable Pagination<T>(IOrderedQueryable<T> query, int offset, int limit) {

        // Validation Code (...)

        // Main Logic
        return query.Skip(offset).Take(limit);

    }
}

Test Method:

[Fact]
public void CheckPagination() {
    var query = GetPersonDbSet().OrderBy(i => i.FirstName);

    var result = MyLib.Pagination(query, 1, 5);
    int count = result.Count();
    Assert.True(count > 0);
}

I got an exception in GetPersonDbSet() while on adding the entity, because the variable DbSet<Person> record was initialized with null. Kindly assist me how to Initialize and achieve this without a context (because in this project I'm not using any Database Context).


问:
reuse mysql query code among few methods in same controller - Laravel 5.4
I have few queries which I would like to use it to few methods in the same controller.for example below code:

```<code>$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
</code>```

I need to call above query in 4 methods in UserController.

I thought of doing something like:

```<code>public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
</code>```

Then

```<code>UserController

public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}
</code>```

But I get an error. How do I do this so when I change the code in one place it reflects everywhere?

Updated question

```<code>public function notify()
    {
    $bio = User::where('id',Auth::user()->id)->value('bio');
    $photo = User::where('id',Auth::user()->id)->value('photo');
    $friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
    $notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
    $status = User::where('id',Auth::user()->id)->value('search_status');

    }

    public function index()
    {

    $this->notify();
    return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
    }
</code>```

答:
Your UserController could looks like this

```<code>class UserController extends BaseController {

  public function notify()
  {
      $array['bio'] = User::where('id',Auth::user()->id)->value('bio');
      $array['photo'] = User::where('id',Auth::user()->id)->value('photo');
      $array['friends'] = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
      $array['notifications'] = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
      $array['status'] = User::where('id',Auth::user()->id)->value('search_status');

      return $array;
  }

  public function index()
  {
    return view('/users/index', $this->notify());
  }

}
</code>```

Body:
I have few queries which I would like to use it to few methods in the same controller.for example below code:

$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');

I need to call above query in 4 methods in UserController.

I thought of doing something like:

public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}

Then

UserController

public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}

But I get an error. How do I do this so when I change the code in one place it reflects everywhere?

Updated question

public function notify()
    {
    $bio = User::where('id',Auth::user()->id)->value('bio');
    $photo = User::where('id',Auth::user()->id)->value('photo');
    $friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
    $notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
    $status = User::where('id',Auth::user()->id)->value('search_status');

    }

    public function index()
    {

    $this->notify();
    return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
    }

Body:
Your UserController could looks like this

class UserController extends BaseController {

  public function notify()
  {
      $array['bio'] = User::where('id',Auth::user()->id)->value('bio');
      $array['photo'] = User::where('id',Auth::user()->id)->value('photo');
      $array['friends'] = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
      $array['notifications'] = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
      $array['status'] = User::where('id',Auth::user()->id)->value('search_status');

      return $array;
  }

  public function index()
  {
    return view('/users/index', $this->notify());
  }

}


问:
Send notification globally using FCM
I want to send notification to my iOS application from server side. I am using PHP at server side and FCM to send notifications. I have the server_key for my firebase project.

I sent the following to FCM

```<code>{
  "to": "red_id",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}
</code>```

But I want to send notification globally without using "to" clause. Need help

答:
Firebase Cloud Messaging always send messages to specific targets. While those targets can be broad, there is no way to send untargeted messages.

If you want to send a message to all users of your app, the easiest way is to have your app subscribe to a topic (e.g. all on startup. That way you can target all users of your app, by sending a message to topic /topic/all.

Title: Send notification globally using FCM

Body:
I want to send notification to my iOS application from server side. I am using PHP at server side and FCM to send notifications. I have the server_key for my firebase project.

I sent the following to FCM

{
  "to": "red_id",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

But I want to send notification globally without using "to" clause. Need help


问:
Kotlin inline keyword causing IntelliJ IDEA Coverage reporting 0%
I created a very simple test function as below

```<code>class SimpleClassTest {

    lateinit var simpleObject: SimpleClass
    @Mock lateinit var injectedObject: InjectedClass

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
    }

    @Test
    fun testSimpleFunction() {
        simpleObject = lookupInstance()
    }

    inline fun lookupInstance() = SimpleClass(injectedObject)
}
</code>```

I Run it with Coverage... The test coverage number is 0%. But if I remove the inline keyword, the test coverage number shows now.

Is this a Kotlin issue or Android IntelliJ IDEA Coverage issue? (note: JaCoco coverage is good).

Note: I'm using Android Studio 2.0 and Kotlin 1.0.2

答: When an inlined function is compiled, the compiler essentially pastes its body into the call site (in place of the function call).  This means that the coverage analysis can't tell that it's an inlined function because it doesn't really exist where you defined it.  In other words, this behavior is a natural artifact of what it means for a function to be inlined.</p>

Body:
I created a very simple test function as below

class SimpleClassTest {

    lateinit var simpleObject: SimpleClass
    @Mock lateinit var injectedObject: InjectedClass

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
    }

    @Test
    fun testSimpleFunction() {
        simpleObject = lookupInstance()
    }

    inline fun lookupInstance() = SimpleClass(injectedObject)
}

I Run it with Coverage... The test coverage number is 0%. But if I remove the inline keyword, the test coverage number shows now.

Is this a Kotlin issue or Android IntelliJ IDEA Coverage issue? (note: JaCoco coverage is good).

Note: I'm using Android Studio 2.0 and Kotlin 1.0.2


问:
Compare Time in Rails without the seconds
In my Rails 5 app I want to send an alert 10 minutes after a certain datetime in my database. For example 10 minutes after the created_at datetime.

So I run a cronjob every 1 minute and have to look in my database for all records where created_at was 10 minutes ago.

My created_at field is in the format 2017-06-01 12:00:00. How can I get all records where created_at was 10 minutes ago?

My problem are the seconds and I can't simple do (this is not valid Ruby code, it's just to show my point):

```<code>where created_at == 10.minutes.ago
</code>```

I would have to do something like

```<code>where created_at > 10.minutes.ago AND created_at < 9.minutes.ago
</code>```

But this does not seem very clean. Are there better solutions?

答:
You have to provide range in order to get records..however, to avoid dependencies with seconds, you can do something like below elegantly..</p>

```<code>range = range = 10.minutes.ago.beginning_of_minute..10.minutes.ago.end_of_minute
records = YourModel.where(created_at: range)
</code>```

Body:
In my Rails 5 app I want to send an alert 10 minutes after a certain datetime in my database. For example 10 minutes after the created_at datetime.

So I run a cronjob every 1 minute and have to look in my database for all records where created_at was 10 minutes ago.

My created_at field is in the format 2017-06-01 12:00:00. How can I get all records where created_at was 10 minutes ago?

My problem are the seconds and I can't simple do (this is not valid Ruby code, it's just to show my point):

where created_at == 10.minutes.ago

I would have to do something like

where created_at > 10.minutes.ago AND created_at < 9.minutes.ago

But this does not seem very clean. Are there better solutions?

Body:
You have to provide range in order to get records..however, to avoid dependencies with seconds, you can do something like below elegantly..

range = range = 10.minutes.ago.beginning_of_minute..10.minutes.ago.end_of_minute
records = YourModel.where(created_at: range)


问:
When a user clicks Show link, display the password, hide it when clicked again
I am trying to get this simple script to work. Basically, when a user clicks on the Show link, it will display the password in the password text box and hide it when it is clicked again. I have searched for solutions but couldn't find anything for what I need. Here is the code:

JavaScript

```<code>    function toggle_password(target){
    var tag = getElementById(target);
    var tag2 = getElementById("showhide");
    if (tag2.innerHTML == 'Show'){
        tag.setAttribute('type', 'text');
        tag2.innerHTML = 'Hide';
    }
    else{
        tag.setAttribute('type', 'password');
        tag2.innerHTML = 'Show';
    }

    }
</code>```

HTML

```<code><label for="pwd0">Password:</label>
<input type="password" value="####" name="password" id="pwd0" />
<a href="#" onclick="toggle_password('pwd0');" id="showhide">Show</a>
</code>```

When I click the link, nothing happens. I have tested this without using the if statement too and still did nothing.

答:
http://www.voidtricks.com/password-show-hide-checkbox-click/
This is a simple tutorial to show a password in a input box when a checkbox is checked and hide it when the checkbox is unchecked using jQuery.

Javascript

```<code><script type="text/javascript">
 $(document).ready(function () {
 $("#showHide").click(function () {
 if ($(".password").attr("type")=="password") {
 $(".password").attr("type", "text");
 }
 else{
 $(".password").attr("type", "password");
 }

 });
 });
</script>

<!-- language: lang-html -->
</code>```

HTML
    *

```<code><input type="password" class="password"><br>
    <input type="checkbox" id="showHide"> Show?
</code>```

*
    We have a password input field with the class “password” and a checkbox with the id “showHide”

Easy solution for show / hide password using checkboxes, and this is noob level just copy/paste. DONE !!!   ;-)

Body:
I am trying to get this simple script to work. Basically, when a user clicks on the Show link, it will display the password in the password text box and hide it when it is clicked again. I have searched for solutions but couldn't find anything for what I need. Here is the code:

JavaScript

    function toggle_password(target){
    var tag = getElementById(target);
    var tag2 = getElementById("showhide");
    if (tag2.innerHTML == 'Show'){
        tag.setAttribute('type', 'text');
        tag2.innerHTML = 'Hide';
    }
    else{
        tag.setAttribute('type', 'password');
        tag2.innerHTML = 'Show';
    }

    }

HTML

Password:
<input type="password" value="####" name="password" id="pwd0" />
Show

When I click the link, nothing happens. I have tested this without using the if statement too and still did nothing.

Body:
http://www.voidtricks.com/password-show-hide-checkbox-click/
This is a simple tutorial to show a password in a input box when a checkbox is checked and hide it when the checkbox is unchecked using jQuery.

Javascript

<script type="text/javascript">
 $(document).ready(function () {
 $("#showHide").click(function () {
 if ($(".password").attr("type")=="password") {
 $(".password").attr("type", "text");
 }
 else{
 $(".password").attr("type", "password");
 }

 });
 });
</script>

<!-- language: lang-html -->

HTML
    *

<input type="password" class="password"><br>
    <input type="checkbox" id="showHide"> Show?

*
    We have a password input field with the class “password” and a checkbox with the id “showHide”

Easy solution for show / hide password using checkboxes, and this is noob level just copy/paste. DONE !!!   ;-)


问:
Custom font showing up in IB but not on device
I'm trying to use fonts from the Open Sans family. I added the fonts to my Xcode project, I checked that they were added to my application's resources bundle and I added the fonts to my Info.plist file.

When I edit a XIB in Interface Builder, I can use Open Sans font on UILabels when selecting Custom in the font dropdown menu. The font are correctly rendered on the preview in Interface Builder, but then when I launch the application on the device, the font is not applied to the labels.

I tried setting the font programmatically, but that didn't work either. And I'm not getting any warning nor error.

What did I forgot to be able to use a custom font?

The behavior has been the same on an iPad Air running iOS7 and on an iPhone 6 running iOS8.

答:
Go to Target -> Build Phases -> Copy Bundle Resources , in there you check if the font file is there, if not press the plus button and add it manually. Sometimes the font files are not added automatically to the bundle resources.

Hope this helps.


问:
set up Date with Calendar or DateTime
I want to set the hour and the minute of a date-instance. I have 3 solutions.

Which should I take and why? :

version 1:

```<code>Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 8);
calendar.set(Calendar.HOUR, 30);

return calendar.getTime();
</code>```

version 2:

```<code>ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return Date.from(i.toInstant());
</code>```

version 3:

```<code>ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return new Date(i.toEpochSecond());
</code>```

答:
Version 1 is using the long outdated Calendar class. Another problem with it is that it is using the JVM’s current time zone setting without being explicit about this in the code, a trait that could give someone an unpleasant surprise some time in the future.

Version 2 is exploiting the newer classes as far as possible, and it is explicit about using the JVM’s time zone setting. The good solution.

Version 3 has the benefits of version 2 too, but a conversion to milliseconds since the epoch before converting to Date. The conversion via Instant in version 2 is more natural and therefore slightly preferred.

As has been mentioned in the comments, versions 2 and 3 as written in the question do not get rid of seconds and fraction of second. The simple solution (given that you want this) is to use truncatedTo():

```<code>    ZonedDateTime i = date.toInstant()
            .atZone(ZoneId.systemDefault())
            .withHour(8)
            .withMinute(30)
            .truncatedTo(ChronoUnit.MINUTES);
</code>```

Best of all of course if you could avoid using the also outdated Date class altogether.

Title: set up Date with Calendar or DateTime

Body:
I want to set the hour and the minute of a date-instance. I have 3 solutions.

Which should I take and why? :

version 1:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 8);
calendar.set(Calendar.HOUR, 30);

return calendar.getTime();

version 2:

ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return Date.from(i.toInstant());

version 3:

ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return new Date(i.toEpochSecond());

Body:
Version 1 is using the long outdated Calendar class. Another problem with it is that it is using the JVM’s current time zone setting without being explicit about this in the code, a trait that could give someone an unpleasant surprise some time in the future.

Version 2 is exploiting the newer classes as far as possible, and it is explicit about using the JVM’s time zone setting. The good solution.

Version 3 has the benefits of version 2 too, but a conversion to milliseconds since the epoch before converting to Date. The conversion via Instant in version 2 is more natural and therefore slightly preferred.

As has been mentioned in the comments, versions 2 and 3 as written in the question do not get rid of seconds and fraction of second. The simple solution (given that you want this) is to use truncatedTo():

    ZonedDateTime i = date.toInstant()
            .atZone(ZoneId.systemDefault())
            .withHour(8)
            .withMinute(30)
            .truncatedTo(ChronoUnit.MINUTES);

Best of all of course if you could avoid using the also outdated Date class altogether.


问:
REST only use get and post
Since not all client browsers support put and delete, is it good practice to only use 'get' and 'post' for all crud operations?</p>

答: See the first entry in this faq page:  http://code.google.com/p/implementing-rest/wiki/FAQ</p>

Title: REST only use get and post


问:
Linux - How can i replace some string with same string enclosed with braces?
I have some files in a dir, when i grep some string,  i get result like below.

scripts/FileReplace> grep -r "case" *

dir1/file2:case 'a'

dir2/file3:case "ssss"

file1:case 1

After i use replace cmd i expect strings in files updated as below

CASE ('a')

CASE ("ssss")

CASE (1)

ie,, "case" is replaced with "CASE" and text after space is enclosed in braces as above.

Any suggestion how i can do this with shell cmd.

答:
You can use sed and its substitution:

```<code>find . -type f -exec sed -i 's/case \(.\+\)/CASE (\1)/' {} +
</code>```

.\+ matches anything that has at least one character.

\(...\) creates a capture group, you can reference the first capture group as \1.

running with -i~ instead of -i will create backups of the files; recommended especially if you're just experimenting.

Body:
You can use sed and its substitution:

find . -type f -exec sed -i 's/case \(.\+\)/CASE (\1)/' {} +

.\+ matches anything that has at least one character.

\(...\) creates a capture group, you can reference the first capture group as \1.

running with -i~ instead of -i will create backups of the files; recommended especially if you're just experimenting.


问:
Last two record for each user in same row Postgresql
i have two tables Customer table and INVOICE table

```<code>CREATE TABLE main.CUSTOMER
(
CUSTOMER_ID     SERIAL          PRIMARY KEY,
NAME            VARCHAR(128)    NOT NULL,
BIRTH_DATE      DATE            NOT NULL,
CREATION_DATE   TIMESTAMP       NOT NULL    DEFAULT(NOW())
);

CREATE TABLE main.INVOICE
(
INVOICE_ID      SERIAL      PRIMARY KEY,
INVOICE_DATE    TIMESTAMP   NOT NULL,
AGENT_ID        BIGINT      NOT NULL,
AMOUNT          NUMERIC(18, 5) NOT NULL,
CUSTOMER_ID     BIGINT      NOT NULL,
FOREIGN KEY (CUSTOMER_ID) REFERENCES main.CUSTOMER (CUSTOMER_ID)
);
</code>```

How can i get Last two invoice amounts for each customer (in same row).

答:
One method is to use row_number():

```<code>select c.*,
       max(case when seqnum = 1 then amount end) as amount_latest,
       max(case when seqnum = 2 then amount end) as amount_prev
from customer c join
     (select i.*,
             row_number() over (partition by customer_id order by invoice_date desc) as seqnum
      from invoices i
     ) i
     on c.customer_id = i.customer_id
where i.seqnum in (1, 2)
group by c.customer_id;  -- other columns are not needed because `customer_id` is unique
</code>```

Body:
i have two tables Customer table and INVOICE table

CREATE TABLE main.CUSTOMER
(
CUSTOMER_ID     SERIAL          PRIMARY KEY,
NAME            VARCHAR(128)    NOT NULL,
BIRTH_DATE      DATE            NOT NULL,
CREATION_DATE   TIMESTAMP       NOT NULL    DEFAULT(NOW())
);

CREATE TABLE main.INVOICE
(
INVOICE_ID      SERIAL      PRIMARY KEY,
INVOICE_DATE    TIMESTAMP   NOT NULL,
AGENT_ID        BIGINT      NOT NULL,
AMOUNT          NUMERIC(18, 5) NOT NULL,
CUSTOMER_ID     BIGINT      NOT NULL,
FOREIGN KEY (CUSTOMER_ID) REFERENCES main.CUSTOMER (CUSTOMER_ID)
);

How can i get Last two invoice amounts for each customer (in same row).

Body:
One method is to use row_number():

select c.*,
       max(case when seqnum = 1 then amount end) as amount_latest,
       max(case when seqnum = 2 then amount end) as amount_prev
from customer c join
     (select i.*,
             row_number() over (partition by customer_id order by invoice_date desc) as seqnum
      from invoices i
     ) i
     on c.customer_id = i.customer_id
where i.seqnum in (1, 2)
group by c.customer_id;  -- other columns are not needed because `customer_id` is unique


问:
How to display the number of subroutines and their names in a perl script at the time of its execution?
Consider the following Perl script script.pl as an example:

```<code>use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();
</code>```

When I execute the script, it should show the following output:

./script.pl

number of subroutines:3

  names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

答:
You are looking for Devel::Symdump:

```<code>#!/usr/bin/env perl

use strict;
use warnings;

{
    require Devel::Symdump;
    my $sym = Devel::Symdump->new('main');
    my @subs = $sym->functions;
    printf "Number of subroutines: %d\n", scalar @subs;
    printf "Names of subroutines: %s\n", join(q{, } => map { s/^main:://; $_ } @subs);
}

sub f1 {
    # statements
}

sub f2 {
    # statements
}

sub f3 {
    # statements
}

f1();
f2();
f3();
</code>```

Output:

```Number of subroutines: 3
Names of subroutines: f2, f1, f3```

Body:
Consider the following Perl script script.pl as an example:

use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();

When I execute the script, it should show the following output:

./script.pl

number of subroutines:3

  names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

Body:
You are looking for Devel::Symdump:

#!/usr/bin/env perl

use strict;
use warnings;

{
    require Devel::Symdump;
    my $sym = Devel::Symdump->new('main');
    my @subs = $sym->functions;
    printf "Number of subroutines: %d\n", scalar @subs;
    printf "Names of subroutines: %s\n", join(q{, } => map { s/^main:://; $_ } @subs);
}

sub f1 {
    # statements
}

sub f2 {
    # statements
}

sub f3 {
    # statements
}

f1();
f2();
f3();

Output:

Number of subroutines: 3
Names of subroutines: f2, f1, f3