问:
What are some optimization techniques for MySQL table with 300+ million records?
I am looking at storing some JMX data from JVMs on many servers for about 90 days.  This data would be statistics like heap size and thread count.  This will mean that one of the tables will have around 388 million records.

From this data I am building some graphs so you can compare the stats retrieved from the Mbeans.  This means I will be grabbing some data at an interval using timestamps.

So the real question is, Is there anyway to optimize the table or query so you can perform these queries in a reasonable amount of time?

Thanks,

Josh

答:
If you are using MYSQL 5.1 you can use the new features.
but be warned they contain lot of bugs.

first you should use indexes.
if this is not enough you can try to split the tables by using partitioning.

if this also wont work, you can also try load balancing.

OwnerDisplayName: Josh Harris

OwnerDisplayName: bott


来源: stackexchange

问:
w3c markup validator ampersand (&) error
Is there any workaround for the w3c validation error for an & present in urls or some other place in HTML markup?

It says:

& did not start a character reference. (& probably should have been escaped as &.)

The ampersand in my case is a part of a url for gravatar thumbnail. This is the problematic part of a url:

c91588793296e2?s=50&d=http%3A%2F%.

答: Replace with &

ContentLicense: CC BY-SA 3.0

Body: Replace with &amp;

ContentLicense: CC BY-SA 2.5


问:
How to Embed Video Google Drive using Youtube Iframe
I'm using this code but not working

```<code><iframe class="youtube-player" width="100%" height="400" src="http://www.youtube.com/embed/https://drive.google.com/file/d/0BwbA32qGbwr8TTdidmFMZnV3SDg/view" frameborder="0"></iframe>
</code>```

please help me

thanks

答:
That's will be conflict in that way, you can't force like that.

you can try on this https://developers.google.com/youtube/iframe_api_reference

Body:
I'm using this code but not working

please help me

thanks


问:
xlsx error: "Removed Records: Named range from /xl/workbook.xml part" when tried to resolve errors
I have an xlsx file that I generate using SSIS. The data to this file is written through a data flow task where the xlsx file is the oledb destination. I have used the following connection string as an expression for the OLEDB connection:

```<code>"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ @[User::ExcelPath] +";
Extended Properties=\"Excel 12.0 Xml;HDR=YES\";"
</code>```

The file opens just fine before the data flow task. After the data flow task, I get a dialog as follows:

When I click yes, I get another message:

The contents of the xml file are

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">       <logFileName>error072840_02.xml</logFileName><summary>Errors were detected in file   'C:\output\documentId-1.xlsx'</summary><removedRecords summary="Following is a list of removed records:"><removedRecord>Removed Records: Named range from /xl/workbook.xml part (Workbook)</removedRecord></removedRecords></recoveryLog>
</code>```

I am not able to figure out what exactly is causing this error. Any help will be appreciated. TIA

答: For me personally, spaces/special characters were irrelevant in the tab (Sheet) names. The named range itself cannot have spaces/special characters as it is treated like a variable</p>

Body:
I have an xlsx file that I generate using SSIS. The data to this file is written through a data flow task where the xlsx file is the oledb destination. I have used the following connection string as an expression for the OLEDB connection:

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ @[User::ExcelPath] +";
Extended Properties=\"Excel 12.0 Xml;HDR=YES\";"

The file opens just fine before the data flow task. After the data flow task, I get a dialog as follows:

When I click yes, I get another message:

The contents of the xml file are

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">       <logFileName>error072840_02.xml</logFileName>Errors were detected in file   'C:\output\documentId-1.xlsx'<removedRecords summary="Following is a list of removed records:"><removedRecord>Removed Records: Named range from /xl/workbook.xml part (Workbook)</removedRecord></removedRecords></recoveryLog>

I am not able to figure out what exactly is causing this error. Any help will be appreciated. TIA


问:
How to add an extra textfield when user clicks on a button?
I have this code

<input type="text" name="search" placeholder="Author...">

I want a button and when I click on it, it should show this textfield and the button should disappear.

答:
```<code>You may do this simply by using AngularJS. Here is a short example.
</code>```

var app = angular.module("myApp", []);
            app.controller("myCtrl", function($scope) {
$scope.a=1;
$scope.b=null;
$scope.check=function(){
$scope.a=null;
$scope.b=1;
            }});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        <body ng-app="myApp" ng-controller="myCtrl">
            <div ng-show="a"><button ng-click="check()">Click</button></div>
            <div ng-show="b"><input></div>
          </div>
        </body></code>```

Body:
You may do this simply by using AngularJS. Here is a short example.

var app = angular.module("myApp", []);
            app.controller("myCtrl", function($scope) {
$scope.a=1;
$scope.b=null;
$scope.check=function(){
$scope.a=null;
$scope.b=1;
            }});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        <body ng-app="myApp" ng-controller="myCtrl">
            <div ng-show="a"><button ng-click="check()">Click</button></div>
            <div ng-show="b"><input></div>
          </div>
        </body>


问:
PHP find max between variables
I'm trying to find out wich variable is bigger (those are all integers):

```<code><?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
</code>```

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

```<code>  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;
</code>```

I want endoA and endoB to be identified...

答:
You can define an array instead, or compact your variables into an array:

```<code>//$array = array('ectoA'=>3,'ectoB'=>5,'mesoA'=>0,'mesoB'=>4,'endoA'=>11,'endoB'=>11);

$array   = compact('ectoA','ectoB','mesoA','mesoB','endoA','endoB');

$result  = array_keys($array, max($array));
</code>```

Then compute the max() of that array and use array_keys() to search for the max number and return the keys.

```<code>print_r($result);
</code>```

Yields:

```<code>Array
(
    [0] => endoA
    [1] => endoB
)
</code>```

Title: PHP find max between variables

Body:
I'm trying to find out wich variable is bigger (those are all integers):

<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;

I want endoA and endoB to be identified...

Body:
You can define an array instead, or compact your variables into an array:

//$array = array('ectoA'=>3,'ectoB'=>5,'mesoA'=>0,'mesoB'=>4,'endoA'=>11,'endoB'=>11);

$array   = compact('ectoA','ectoB','mesoA','mesoB','endoA','endoB');

$result  = array_keys($array, max($array));

Then compute the max() of that array and use array_keys() to search for the max number and return the keys.

print_r($result);

Yields:

Array
(
    [0] => endoA
    [1] => endoB
)


答:
Your code seems to be a working one.

But it would print for you the value of the maximum number, not the name of the variable.

To have the name of the variable at the end you should add some additional code like:

```<code>$max = (max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
if($max == $ectoA) echo "ectoA";
if($max == $ectoB) echo "ectoB";
// ... same goes for other variables
</code>```

But working with an array would be the most proper solution.

Title: PHP find max between variables

Body:
Your code seems to be a working one.

But it would print for you the value of the maximum number, not the name of the variable.

To have the name of the variable at the end you should add some additional code like:

$max = (max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
if($max == $ectoA) echo "ectoA";
if($max == $ectoB) echo "ectoB";
// ... same goes for other variables

But working with an array would be the most proper solution.


问:
SQL Server - find absence date occurrences
I have the following dataset:

enter image description here

Here is script for this data:

;with dataset AS (
    select 'EMP01' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-07' AS DATE) AS CUT_DATE
    UNION
    select 'EMP01' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-15' AS DATE) AS CUT_DATE
    UNION
    select 'EMP02' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-09' AS DATE) AS CUT_DATE
)
select *
from dataset
I need to divide these periods (PERIOD_START and PERIOD_END) by CUT_DATE (exclude cut dates from that periods) The number of cut dates could be any (3,5,8 etc).

Expecting result for the dataset above is:

答:
This is another way if way if lag is supported.

Rextester Sample

```<code>with tbl as
(select d.*
    ,case when (item_type = lag(item_type) over (partition by employee_id order by apply_date))
            then 0
            else 1
    end grp_tmp
from DATA2 d
where
    item_type <> 'Worked'
)
,tbl2 as
(select t.*
    ,sum(grp_tmp) over (order by employee_id,apply_date
                        rows between unbounded preceding and current row
                        )
    as grp
from tbl t
)
select
EMPLOYEE_ID
    ,ITEM_TYPE
    ,(CONVERT(VARCHAR(24),min(apply_date),103)
    +' - '
    +CONVERT(VARCHAR(24),max(apply_date),103)
    ) as range
from tbl2
group by EMPLOYEE_ID,
        ITEM_TYPE
        ,grp
order by
    employee_id
    ,min(apply_date);
</code>```

Output

```<code>+-------------+-----------+-------------------------+
| EMPLOYEE_ID | ITEM_TYPE |          range          |
+-------------+-----------+-------------------------+
|           1 | Sickness  | 23/05/2017 - 24/05/2017 |
|           1 | Vacation  | 26/05/2017 - 29/05/2017 |
|           1 | Sickness  | 01/06/2017 - 01/06/2017 |
|           2 | Sickness  | 25/05/2017 - 30/05/2017 |
+-------------+-----------+-------------------------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is another way if way if lag is supported.

Rextester Sample

with tbl as
(select d.*
    ,case when (item_type = lag(item_type) over (partition by employee_id order by apply_date))
            then 0
            else 1
    end grp_tmp
from DATA2 d
where
    item_type <> 'Worked'
)
,tbl2 as
(select t.*
    ,sum(grp_tmp) over (order by employee_id,apply_date
                        rows between unbounded preceding and current row
                        )
    as grp
from tbl t
)
select
EMPLOYEE_ID
    ,ITEM_TYPE
    ,(CONVERT(VARCHAR(24),min(apply_date),103)
    +' - '
    +CONVERT(VARCHAR(24),max(apply_date),103)
    ) as range
from tbl2
group by EMPLOYEE_ID,
        ITEM_TYPE
        ,grp
order by
    employee_id
    ,min(apply_date);

Output

+-------------+-----------+-------------------------+
| EMPLOYEE_ID | ITEM_TYPE |          range          |
+-------------+-----------+-------------------------+
|           1 | Sickness  | 23/05/2017 - 24/05/2017 |
|           1 | Vacation  | 26/05/2017 - 29/05/2017 |
|           1 | Sickness  | 01/06/2017 - 01/06/2017 |
|           2 | Sickness  | 25/05/2017 - 30/05/2017 |
+-------------+-----------+-------------------------+


问:
How does Google Protocol Buffers compare to ASN.1
What are the most noticable differences between Google Protocol Buffers and ASN.1 (with PER-encoding)? For my project the most imporant issue is the size of the serialized data. Has anyone done any data-size comparisons between the two?</p>

答: If you use ASN.1 with Unaligned PER, and define your data types using the appropriate constraints (e.g., specifying lower/upper bounds for integers, upper bounds for the length of lists, etc.), your encodings will be very compact. There will be no bits wasted for things like alignment or padding between the fields, and each field will be encoded in the minimum number of bits necessary to hold its permitted range of values.  For example, a field of type INTEGER (1..8) will be encoded in 3 bits (1='000', 2='001', ..., 8='111'); and a CHOICE with four alternatives will occupy 2 bits (indicating the chosen alternative) plus the bits occupied by the chosen alternative.  ASN.1 has many other interesting features that have been successfully used in many published standards.  An example is the extension marker ("..."), which when applied to SEQUENCE, CHOICE, ENUMERATED, and other types, enables backward- and forward compatibility between endpoints implementing different versions of the specification.</p>

OwnerDisplayName: Yrlec

LastEditorDisplayName: Gamecat


问:
Getting started with wxWidgets and CLion?
Can anyone suggest a tutorial or getting started guide to CLion and wxWdgets? I have searched around but am unable to find anything.</p>

答:
Well,

you should download WxWidgets here http://www.wxwidgets.org/downloads/.

Then, you should compile and install to your system.

Download and install CLion.

Create new Project.

Then, follow to this edit your CMakeLists.txt Building wxWidgets 3.1.0 on CLion (Ubuntu)

Then try Hello World sample http://docs.wxwidgets.org/trunk/overview_helloworld.html.

If everything okay, start to develop great apps!


问:
How can I print after each parameter is inputed in a method?
I know my problem but I can't seem to figure out a way to solve it.

What I want to do is after the user gives their preferred username, I want to print the phoneNumber next to it the input, and the problem I'm running into is this.

I would get the user to input,

Username: PhoneNumber: then now they can input

Instead what I want is something like this:

Username: input from the method parameter.....

phoneNumber: same thing as above

UPDATED VERSION:

This is the error I get

userName cannot be resolved to a variable

```<code> public void createCustomer(String userName) {

    System.out.print("Enter username: ");
    this.user = input.nextLine();
    this.user = userName;

    this.password = password;
    this.address = address;
    this.phoneNum = phoneNum;
    this.email = email;
}

public static void main (String args[]) {
    CustomerUI customer = new CustomerUI();
    Scanner input = new Scanner(System.in);

    if(shouldCreate() == true) {
        customer.createCustomer(userName);
    }
}
</code>```

答:
Instructions in a program are almost always executed in the order they are written (at lease within a method).

So what you do is first outputting the questions and later calling the input method. To change that you need to reorder the instructions.

problem is, that you directly pass the input return values to another method. So you have to introduce some local variables to store those return values until you pass them to the next method:

```<code>     System.out.print("");
    System.out.print("Username: ");
    String userName =input.nextLine();
    System.out.print("PhoneNumber: ");
    String phoneNumber =input.nextLine();
    customer.createCustomer(userName, phoneNumber,
          input.nextLine(),input.nextLine(),input.nextInt());
</code>```

Body:
I know my problem but I can't seem to figure out a way to solve it.

What I want to do is after the user gives their preferred username, I want to print the phoneNumber next to it the input, and the problem I'm running into is this.

I would get the user to input,

Username: PhoneNumber: then now they can input

Instead what I want is something like this:

Username: input from the method parameter.....

phoneNumber: same thing as above

UPDATED VERSION:

This is the error I get

userName cannot be resolved to a variable

 public void createCustomer(String userName) {

    System.out.print("Enter username: ");
    this.user = input.nextLine();
    this.user = userName;

    this.password = password;
    this.address = address;
    this.phoneNum = phoneNum;
    this.email = email;
}

public static void main (String args[]) {
    CustomerUI customer = new CustomerUI();
    Scanner input = new Scanner(System.in);

    if(shouldCreate() == true) {
        customer.createCustomer(userName);
    }
}

Body:
Instructions in a program are almost always executed in the order they are written (at lease within a method).

So what you do is first outputting the questions and later calling the input method. To change that you need to reorder the instructions.

problem is, that you directly pass the input return values to another method. So you have to introduce some local variables to store those return values until you pass them to the next method:

     System.out.print("");
    System.out.print("Username: ");
    String userName =input.nextLine();
    System.out.print("PhoneNumber: ");
    String phoneNumber =input.nextLine();
    customer.createCustomer(userName, phoneNumber,
          input.nextLine(),input.nextLine(),input.nextInt());


问:
Regarding same header and footer across web pages in HTML
I am developing a website and i want to have same header and footer across all web pages. Request you to please suggest me how i can do that.

Regards

答:
Since you use JSP, you can use template :

<%@include file='header.jsp'%>

and

<%@include file='footer.jsp'%>

in your jsp pages.


问:
Advanced Custom Fields (ACF Pro) + Slick Slider + Wordpress
I am using ACF Pro to make a slider carousel with Slick Slider. I can get it to work with a basic gallery field but I am not even getting it to show when I try to display a repeater field with several sub fields. I am not sure exactly what I am doing wrong but I have been playing with this for a while, and I feel like I am kinda' half there.

Working PHP

```<code><!-- Slider 1 -->

<?php
//Fields
//slider_portfolio = Gallery Field

  $images = get_field('slider_portfolio');

  if( $images ): ?>

  <div class="slider-for">

  <?php foreach( $images as $image ): ?>

  <div class="slick-container">
    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
  </div>

  <?php endforeach; ?>

  </div>

<?php endif;  ?>
</code>```

Non-Working PHP

This is the version I am trying to get to work. It is currently one image sub field inside a repeater field.

Fields:

slider_image = field (repeater field)

portfolio_slider = subfield (image field)

```<code><!-- Slider 2 -->

        <?php
        //Image Slider
        //slider_image = field (repeater field)
        //portfolio_slider = subfield (image field)

        function agero_slider() {

          if( have_rows('slider_image') ):
              echo '<div class="slider-for">';
             // loop through the rows of data

          while ( have_rows('slider_image') ) : the_row();

             // display a sub field value
             //vars
             $image = get_sub_field('portfolio_slider');
          ?>

          <div><img src="<?php echo $image['url']; ?>"/></div>

        <?php

          endwhile;
            echo '</div>
             <div class="slider-nav">';
             // loop through the rows of data
          while ( have_rows('slider_image') ) : the_row();
             // display a sub field value
             //vars
          $image = get_sub_field('portfolio_slider');

        ?>

        <div><img src="<?php echo $image['url']; ?>"/></div>

        <?php
          endwhile;
            echo '</div>';
          else :
             // no rows found
          endif;
        }

        ?>
</code>```

JS Code
This works, even though I need to build on it.

```<code>jQuery(document).ready(function($){
$('.slider-for').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   dots: true,
   arrows: false,
   asNavFor: '.slider-for',
   focusOnSelect: true,
   fade: true,
   autoplay: false
  });
});
</code>```

I'm not sure why the first code is working but the second is not.

Relevant links:

ACF - https://www.advancedcustomfields.com/resources/code-examples/

Slick - http://kenwheeler.github.io/slick/

The Tutorial that I am using as a rough guide to get started -
 http://wpbeaches.com/coding-a-slider-with-slick-and-acf-pro-in-wordpress/

If anyone can suggest what I am doing wrong or maybe suggest a concrete way to display multiple custom fields within a multi slide carousel where the text fields change with each slide image. Once I get this working I can expand it by making each repeater field a slide that can be updated through the UI.

I think maybe I am going about this wrong. Maybe I need to add everything inside a flexible content field or something? Not sure right now, but the second example seems like it should work.

答:
Ok I figured it out! The setup is a little different but it works great.

PHP / HTML Working Code

```<code><section class="dev-slider-wrppr">
  <div class="dev-slider-row">
    <div class="slider-for">
      <?php if( have_rows('slider_content') ): ?>
        <?php while( have_rows('slider_content') ): the_row(); ?>
           <?php
            $slideimage = get_sub_field('slider_image');
            $slidetitle = get_sub_field('slider_title');
            $slidebdycpy = get_sub_field('slider_body_copy');
            ?>
            <div class="slick-container">
              <h4 class="info-title text-center"><?php echo $slidetitle; ?></h4>
              <p class="description"><?php echo $slidebdycpy; ?></p>
              <img src="<?php echo $slideimage['url']; ?>" alt="<?php echo $slideimage['alt']; ?>" />
            </div>
        <?php endwhile; ?>
    <?php endif; ?>
  </div>
</section>
</code>```

JS Working Code

```<code>jQuery(document).ready(function($){
$('.slider-for').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   dots: true,
   arrows: false,
   asNavFor: '.slider-for',
   focusOnSelect: true,
   fade: true,
   autoplay: false
   });
});
</code>```

My ACF Setup

Now this is just the basic functionality. If anyone wants to use this they will still have to do some extra CSS & JS.

Body:
I am using ACF Pro to make a slider carousel with Slick Slider. I can get it to work with a basic gallery field but I am not even getting it to show when I try to display a repeater field with several sub fields. I am not sure exactly what I am doing wrong but I have been playing with this for a while, and I feel like I am kinda' half there.

Working PHP

<?php
//Fields
//slider_portfolio = Gallery Field

  $images = get_field('slider_portfolio');

  if( $images ): ?>

  <?php foreach( $images as $image ): ?>

    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

  <?php endforeach; ?>

<?php endif;  ?>

Non-Working PHP

This is the version I am trying to get to work. It is currently one image sub field inside a repeater field.

Fields:

slider_image = field (repeater field)

portfolio_slider = subfield (image field)

        <?php
        //Image Slider
        //slider_image = field (repeater field)
        //portfolio_slider = subfield (image field)

        function agero_slider() {

          if( have_rows('slider_image') ):
              echo '
';
             // loop through the rows of data

          while ( have_rows('slider_image') ) : the_row();

             // display a sub field value
             //vars
             $image = get_sub_field('portfolio_slider');
          ?>

<img src="<?php echo $image['url']; ?>"/>

        <?php

          endwhile;
            echo '

';
             // loop through the rows of data
          while ( have_rows('slider_image') ) : the_row();
             // display a sub field value
             //vars
          $image = get_sub_field('portfolio_slider');

        ?>

<img src="<?php echo $image['url']; ?>"/>

        <?php
          endwhile;
            echo '
';
          else :
             // no rows found
          endif;
        }

        ?>

JS Code
This works, even though I need to build on it.

jQuery(document).ready(function($){
$('.slider-for').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   dots: true,
   arrows: false,
   asNavFor: '.slider-for',
   focusOnSelect: true,
   fade: true,
   autoplay: false
  });
});

I'm not sure why the first code is working but the second is not.

Relevant links:

ACF - https://www.advancedcustomfields.com/resources/code-examples/

Slick - http://kenwheeler.github.io/slick/

The Tutorial that I am using as a rough guide to get started -
 http://wpbeaches.com/coding-a-slider-with-slick-and-acf-pro-in-wordpress/

If anyone can suggest what I am doing wrong or maybe suggest a concrete way to display multiple custom fields within a multi slide carousel where the text fields change with each slide image. Once I get this working I can expand it by making each repeater field a slide that can be updated through the UI.

I think maybe I am going about this wrong. Maybe I need to add everything inside a flexible content field or something? Not sure right now, but the second example seems like it should work.

Body:
Ok I figured it out! The setup is a little different but it works great.

PHP / HTML Working Code

<section class="dev-slider-wrppr">
  <div class="dev-slider-row">
    <div class="slider-for">
      <?php if( have_rows('slider_content') ): ?>
        <?php while( have_rows('slider_content') ): the_row(); ?>
           <?php
            $slideimage = get_sub_field('slider_image');
            $slidetitle = get_sub_field('slider_title');
            $slidebdycpy = get_sub_field('slider_body_copy');
            ?>
            <div class="slick-container">
              <h4 class="info-title text-center"><?php echo $slidetitle; ?></h4>
              <p class="description"><?php echo $slidebdycpy; ?></p>
              <img src="<?php echo $slideimage['url']; ?>" alt="<?php echo $slideimage['alt']; ?>" />
            </div>
        <?php endwhile; ?>
    <?php endif; ?>
  </div>
</section>

JS Working Code

jQuery(document).ready(function($){
$('.slider-for').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   dots: true,
   arrows: false,
   asNavFor: '.slider-for',
   focusOnSelect: true,
   fade: true,
   autoplay: false
   });
});

My ACF Setup

Now this is just the basic functionality. If anyone wants to use this they will still have to do some extra CSS & JS.


问:
UIPickerView data
I have a uipickerview which is used to displays names in a uitextfield, any ideas on how I would pass a value that is hidden from the user into a variable. Can I somehow associate the value with the name in the NSArray while not displaying it.
Thank you

Trying a dictionary but am stuck on something that is probably pretty simple, I have a dictionary

```<code>    NSArray *keys = [NSArray arrayWithObjects:@"1", @"2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"3", @"4", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
</code>```

and in didSelectRow I have

```<code>    NSString *itemKey = [NSString stringWithFormat:@"%f", row];
    survonemd.text = [dictionary objectForKey:itemKey];
</code>```

which seems ok

but am stuck on titleForRow

any help or tips would be much appreciated.

I now have -

```<code>@property (nonatomic, retain) NSArray *keys;
@property (nonatomic, retain) NSArray *objects;

@synthesize keys;
@synthesize objects;

self.keys = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
self.objects = [NSArray arrayWithObjects:@"4", @"5", @"6", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *itemKey = [keys objectAtIndex:row];
return [dictionary objectForKey:itemKey];
}

- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSString *itemKey = [keys objectAtIndex:row];
survonemd.text = [dictionary objectForKey:itemKey];
}
</code>```

It runs and the picker view gets called from the textfield but no data is displayed in the picker. Please help.

答:
Instead of generating the key string from the row number (for which you would use %i instead of %f by the way), use the row as the index into the keys array:

```<code>- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSString *itemKey = [keys objectAtIndex:row];
    survonemd.text = [dictionary objectForKey:itemKey];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *itemKey = [keys objectAtIndex:row];
    return [dictionary objectForKey:itemKey];
}
</code>```

This way, the key values also don't have to be numbers-as-strings.

Define your keys and dictionary objects as properties and set them using self.keys = ... so you can access them properly.

Title: UIPickerView data

Body:
I have a uipickerview which is used to displays names in a uitextfield, any ideas on how I would pass a value that is hidden from the user into a variable. Can I somehow associate the value with the name in the NSArray while not displaying it.
Thank you

Trying a dictionary but am stuck on something that is probably pretty simple, I have a dictionary

    NSArray *keys = [NSArray arrayWithObjects:@"1", @"2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"3", @"4", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

and in didSelectRow I have

    NSString *itemKey = [NSString stringWithFormat:@"%f", row];
    survonemd.text = [dictionary objectForKey:itemKey];

which seems ok

but am stuck on titleForRow

any help or tips would be much appreciated.

I now have -

@property (nonatomic, retain) NSArray *keys;
@property (nonatomic, retain) NSArray *objects;

@synthesize keys;
@synthesize objects;

self.keys = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
self.objects = [NSArray arrayWithObjects:@"4", @"5", @"6", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *itemKey = [keys objectAtIndex:row];
return [dictionary objectForKey:itemKey];
}

- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSString *itemKey = [keys objectAtIndex:row];
survonemd.text = [dictionary objectForKey:itemKey];
}

It runs and the picker view gets called from the textfield but no data is displayed in the picker. Please help.

Body:
Instead of generating the key string from the row number (for which you would use %i instead of %f by the way), use the row as the index into the keys array:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSString *itemKey = [keys objectAtIndex:row];
    survonemd.text = [dictionary objectForKey:itemKey];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *itemKey = [keys objectAtIndex:row];
    return [dictionary objectForKey:itemKey];
}

This way, the key values also don't have to be numbers-as-strings.

Define your keys and dictionary objects as properties and set them using self.keys = ... so you can access them properly.


问:
how can I store my data in a global variable?
```<code>$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});
</code>```

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

答:
Here you must understand one thing that getJSON is 'async'. Your alert method trying to show the data which gonna come in future. In order to solve this problem, you must use 'then', 'done' or 'fail' like below.

$(function(){

  var astronautsData;

  //Assign your getjson request
  var jsonRequest = $.getJSON('http://api.open-notify.org/astros.json');

  //This function runs once the getJSON method is success
  jsonRequest.done(function(data){
    astronautsData = data;
  });

   //This function runs after the success of getJSON
  jsonRequest.then(function(){
      //Here you have to do your alert ( This alert will give data )
      alert(astronautsData);
  });

  //This alert will give undefined value as this line of code and getjson request runs parallelly
  alert(astronautsData);
});```

Body:
$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.


问:
What is the difference between template pattern and strategy pattern?
The two patterns (template and strategy) seem similar. The template method has an abstract base class with a skeletal method that drives the processing that needs to vary. The processing is done by calling abstract methods that are supplied by the concrete classes. We select the variation that we want by picking the concrete classes.

For example, we have a Report class, and an HTMLReport class that inherits from Report. Our Report class could look like this:

```<code>class Report
def initialize
@title = 'Monthly Report'
@text = ['Things are going', 'really really well']
end

def output_report
output_start
output_head
output_body_start
output_body
output_body_end
output_end
end

def output_body
@text.each do |line|
output_line(line)
end

def output_start
raise StandardError
end

def output_head
raise 'This needs to be implemented by the concrete class'
end
...
end
</code>```

and our actual concrete class:

```<code>class HTMLReport < Report
def output_start
puts('<html>')
end

def output_head
puts('    <head>')
...
end

...
end
</code>```

Actual use:

```<code>report = HTMLReport.new
report.output_report
</code>```

The key thing is that the abstract class calls other methods for the variable parts of the algorithm, which we can then subclass (in this case through Ruby inheritance) and then work on the actual implementation.

However, some drawbacks (according to Russ Olsen):
- uses inheritance
- limits runtime flexibility... once we select a particular version of the algo, changing our mind is hard.

So, the strategy pattern:
- take out the annoyingly varying chunk of code and isolate it in its own class. Then create a whole family of classes, one for each variation.

Example:

```<code>class Formatter
def output_report(title, text)
raise 'Abstract Method called'
end
end

class HTMLFormatter < Formatter
def output_report(title, text)
puts('<html>')
puts('   <head>')
puts("   <title>#{title}</title>")
puts('    </head>')
...
end
</code>```

Now our Report class looks like this:

```<code>class Report
attr_reader :title, :text
attr_accessor :formatter

def initialize(formatter)
@title = 'Monthly Report'
@text = ['Things are going', 'really, really well.']
@formatter = formatter
end

def output_report
@formatter.output_report(@title, @text)
end
end
</code>```

So, correct me if I'm wrong, it looks like since the strategies all have the same interface, we can just delegate to them in the Report class. The Report class is called the context by those GOF people.

but how does this allow us to switch strategies at runtime? We still call them like this right?

```<code>report = Report.new(HTMLFormatter.new)
report.output_report
</code>```

What are the main differences?

答:
A template pattern isn't much of a pattern.  It simply describes what we all know to be the fundamentals of polymorphism.  The Strategy Pattern on the other hand defines a common interface for "functions"/"strategies" which can be swapped out at run time.  Here's an example of the Strategy Pattern in Java (sorry, not well versed in Ruby):

Disclaimer: Not my code, great example.

```<code>public interface Strategy {
   public int doOperation(int num1, int num2);
}

public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
     return num1 + num2;
   }
}

public class OperationSubstract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}

// Using this Context and common Strategy interface, we can utilize any operation
// we want.
public class Context {
   private Strategy strategy;

   public Context(Strategy strategy){
       this.strategy = strategy;
   }

   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

public class StrategyPatternDemo {

    public static void main(String[] args) {

       // Implement any Operation that implements Strategy interface
       Context context = new Context(new OperationAdd());
       System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

       context = new Context(new OperationSubstract());
       System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

       context = new Context(new OperationMultiply());
       System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
   }
}
</code>```

Body:
The two patterns (template and strategy) seem similar. The template method has an abstract base class with a skeletal method that drives the processing that needs to vary. The processing is done by calling abstract methods that are supplied by the concrete classes. We select the variation that we want by picking the concrete classes.

For example, we have a Report class, and an HTMLReport class that inherits from Report. Our Report class could look like this:

class Report
def initialize
@title = 'Monthly Report'
@text = ['Things are going', 'really really well']
end

def output_report
output_start
output_head
output_body_start
output_body
output_body_end
output_end
end

def output_body
@text.each do |line|
output_line(line)
end

def output_start
raise StandardError
end

def output_head
raise 'This needs to be implemented by the concrete class'
end
...
end

and our actual concrete class:

class HTMLReport < Report
def output_start
puts('')
end

def output_head
puts('    ')
...
end

...
end

Actual use:

report = HTMLReport.new
report.output_report

The key thing is that the abstract class calls other methods for the variable parts of the algorithm, which we can then subclass (in this case through Ruby inheritance) and then work on the actual implementation.

However, some drawbacks (according to Russ Olsen):
- uses inheritance
- limits runtime flexibility... once we select a particular version of the algo, changing our mind is hard.

So, the strategy pattern:
- take out the annoyingly varying chunk of code and isolate it in its own class. Then create a whole family of classes, one for each variation.

Example:

class Formatter
def output_report(title, text)
raise 'Abstract Method called'
end
end

class HTMLFormatter < Formatter
def output_report(title, text)
puts('')
puts('   ')
puts("   <title>#{title}</title>")
puts('    ')
...
end

Now our Report class looks like this:

class Report
attr_reader :title, :text
attr_accessor :formatter

def initialize(formatter)
@title = 'Monthly Report'
@text = ['Things are going', 'really, really well.']
@formatter = formatter
end

def output_report
@formatter.output_report(@title, @text)
end
end

So, correct me if I'm wrong, it looks like since the strategies all have the same interface, we can just delegate to them in the Report class. The Report class is called the context by those GOF people.

but how does this allow us to switch strategies at runtime? We still call them like this right?

report = Report.new(HTMLFormatter.new)
report.output_report

What are the main differences?

Body:
A template pattern isn't much of a pattern.  It simply describes what we all know to be the fundamentals of polymorphism.  The Strategy Pattern on the other hand defines a common interface for "functions"/"strategies" which can be swapped out at run time.  Here's an example of the Strategy Pattern in Java (sorry, not well versed in Ruby):

Disclaimer: Not my code, great example.

public interface Strategy {
   public int doOperation(int num1, int num2);
}

public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
     return num1 + num2;
   }
}

public class OperationSubstract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}

// Using this Context and common Strategy interface, we can utilize any operation
// we want.
public class Context {
   private Strategy strategy;

   public Context(Strategy strategy){
       this.strategy = strategy;
   }

   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

public class StrategyPatternDemo {

    public static void main(String[] args) {

       // Implement any Operation that implements Strategy interface
       Context context = new Context(new OperationAdd());
       System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

       context = new Context(new OperationSubstract());
       System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

       context = new Context(new OperationMultiply());
       System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
   }
}


问:
comparing filenames with .bat and writing missing entries into .txt
i want to compare some files in a folder and then write missing ones into a text file.

i've got a folder

c:\sessions\

with files in it. those files are looking like:

```<code>Blabla-1111-FOO
Blabla-1111-BAR1
Bleble-2222-FOO
Bleble-2222-BAR1
Bleble-2222-BAR2
Bleble-2222-BAR3
Bleble-2222-BAR4
Blublu-5678-FOO
Blublu-5678-BAR1
Blublu-5678-BAR2
Blublu-5678-BAR3
Blublu-5678-BAR4
Blublu-5678-BAR5
Bleble-6666-FOO
Bloblo-7777-FOO
Bloblo-8888-FOO
Bloblo-9999-FOO
</code>```

i need a .bat file which writes down all files ending with -FOO where no matching -BAR exists into a noBARs.txt. So in this case the noBARs.txt should look like this:

```<code>Bleble-6666-FOO
Bloblo-7777-FOO
Bloblo-8888-FOO
Bloblo-9999-FOO
</code>```

There can be multiple -BAR files that belong to one -FOO file.
Thanks in advance guys.

答:
You could try the following:

```<code>@echo off

setlocal enabledelayedexpansion
set "source=c:\sessions"
set "output=noBARs.txt"
set "find=*foo"
set "repl=bar*"

1>"%output%" (
  for %%e in ("%source%\%find%") do (
    set "file=%%e"
    if not exist "!file:~0,-3!%repl%" (
      echo %%~ne
    )
  )
)
</code>```

This will iterate through all the files that contain *foo within their filename.  Then it replaces the last 3 characters of the filename with bar* and checks for the existence of the file. If the corresponding bar file doesn't exist it will write the original filename to the output file noBARs.txt.

I've added an alternative version of the script based on the last comment of dEEkAy in which he states that files ending with FOO followed by a numerical constant should be tested as well. I'm still quite uncertain what the exact intention of dEEkAy is but I'm assuming that the file names *FOO* should be handled the same as *FOO.

The following input:

```<code>Blabla-1111-FOO
Blabla-1111-BAR1
Bleble-2222-FOO
Bleble-2222-BAR1
Bleble-2222-BAR5
Blublu-3333-FOO6
Blublu-3333-BAR1
Blublu-5678-FOO
Blublu-5678-FOO1
Blublu-5678-BAR2
Blublu-5678-BAR4
Bleble-6666-FOO
Bloblo-7777-FOO5
Bloblo-7777-BAR8
Bloblo-9999-FOO
Blublu-9999-FOO9
Bloblo-!^^!-FOO
</code>```

Will produce the following output:

```<code>Bleble-6666-FOO
Bloblo-!^^!-FOO
Bloblo-9999-FOO
Blublu-9999-FOO9
</code>```

The alternative version of the script is also more robust than the original. It should now be capable of handling file names and paths that contain exclamation marks and carets appropriately. Unfortunately, it does come with a cost. Due to the call command which will be executed for each iteration of the for-loop, the script has become a lot slower. Perhaps someone with more batch-file scripting experience can come up with a better solution.

```<code>@echo off

setlocal disabledelayedexpansion
set "source=c:\sessions"
set "output=noBARs.txt"
set "find=foo"
set "repl=bar"

1>"%output%" (
  for %%e in ("%source%\*%find%*") do (
    set "path=%%~dpe"
    set "file=%%~ne"

    setlocal enabledelayedexpansion
    call :ReplaceEndOfString file match "%find%" "%repl%"

    if not exist "!path!!match!*" (
      echo !file!
    )
    endlocal
  )
)
exit /b

:ReplaceEndOfString (__in *source, __out *dest, __in find, __in repl) {
  set "temp=!%1:*%~3=%~3!"
  set "%2=!%1:%temp%=%~4!"
  exit /b
}
</code>```

Keep in mind that "%source%\*%find%*" will match any file that contains %find% within its file name, whereas "%source%\*%find%?" only matches file names that end with %find% including one optional character that could be anything.

I just happened to need some code similar to this and decided to take another look. The main bottleneck of the code seems to be the invocation of the call command. While I don't see a way around this (other than using macros), the execution time of the call command can be greatly improved (with a factor of 2, roughly).

Calling a function by its label seems to be a lot slower than calling the set command. I'm not entirely sure but I can remember something about calling labels being slow due to requiring a rescan of the entire script file. Carets and exclamation marks within file names also appear to remain intact because the delayed expansion phase seems to occur before the set command is called.

```<code>@echo off

setlocal DisableDelayedExpansion
set "source=c:\sessions"
set "output=nobars.txt"
set "find=foo"
set "repl=bar"

1>"%output%" (
  for %%e in ("%source%\*%find%*") do (
    set "path=%%~dpe"
    set "file=%%~ne"

    setlocal EnableDelayedExpansion
    set "end=!file:*%find%=%find%!"
    call set "match=%%file:!end!=%repl%%%"

    if not exist "!path!!match!*" (
      echo !file!
    )
    endlocal
  )
)
exit /b
</code>```

Body:
i want to compare some files in a folder and then write missing ones into a text file.

i've got a folder

c:\sessions\

with files in it. those files are looking like:

Blabla-1111-FOO
Blabla-1111-BAR1
Bleble-2222-FOO
Bleble-2222-BAR1
Bleble-2222-BAR2
Bleble-2222-BAR3
Bleble-2222-BAR4
Blublu-5678-FOO
Blublu-5678-BAR1
Blublu-5678-BAR2
Blublu-5678-BAR3
Blublu-5678-BAR4
Blublu-5678-BAR5
Bleble-6666-FOO
Bloblo-7777-FOO
Bloblo-8888-FOO
Bloblo-9999-FOO

i need a .bat file which writes down all files ending with -FOO where no matching -BAR exists into a noBARs.txt. So in this case the noBARs.txt should look like this:

Bleble-6666-FOO
Bloblo-7777-FOO
Bloblo-8888-FOO
Bloblo-9999-FOO

There can be multiple -BAR files that belong to one -FOO file.
Thanks in advance guys.

Body:
You could try the following:

@echo off

setlocal enabledelayedexpansion
set "source=c:\sessions"
set "output=noBARs.txt"
set "find=*foo"
set "repl=bar*"

1>"%output%" (
  for %%e in ("%source%\%find%") do (
    set "file=%%e"
    if not exist "!file:~0,-3!%repl%" (
      echo %%~ne
    )
  )
)

This will iterate through all the files that contain *foo within their filename.  Then it replaces the last 3 characters of the filename with bar* and checks for the existence of the file. If the corresponding bar file doesn't exist it will write the original filename to the output file noBARs.txt.

I've added an alternative version of the script based on the last comment of dEEkAy in which he states that files ending with FOO followed by a numerical constant should be tested as well. I'm still quite uncertain what the exact intention of dEEkAy is but I'm assuming that the file names *FOO* should be handled the same as *FOO.

The following input:

Blabla-1111-FOO
Blabla-1111-BAR1
Bleble-2222-FOO
Bleble-2222-BAR1
Bleble-2222-BAR5
Blublu-3333-FOO6
Blublu-3333-BAR1
Blublu-5678-FOO
Blublu-5678-FOO1
Blublu-5678-BAR2
Blublu-5678-BAR4
Bleble-6666-FOO
Bloblo-7777-FOO5
Bloblo-7777-BAR8
Bloblo-9999-FOO
Blublu-9999-FOO9
Bloblo-!^^!-FOO

Will produce the following output:

Bleble-6666-FOO
Bloblo-!^^!-FOO
Bloblo-9999-FOO
Blublu-9999-FOO9

The alternative version of the script is also more robust than the original. It should now be capable of handling file names and paths that contain exclamation marks and carets appropriately. Unfortunately, it does come with a cost. Due to the call command which will be executed for each iteration of the for-loop, the script has become a lot slower. Perhaps someone with more batch-file scripting experience can come up with a better solution.

@echo off

setlocal disabledelayedexpansion
set "source=c:\sessions"
set "output=noBARs.txt"
set "find=foo"
set "repl=bar"

1>"%output%" (
  for %%e in ("%source%\*%find%*") do (
    set "path=%%~dpe"
    set "file=%%~ne"

    setlocal enabledelayedexpansion
    call :ReplaceEndOfString file match "%find%" "%repl%"

    if not exist "!path!!match!*" (
      echo !file!
    )
    endlocal
  )
)
exit /b

:ReplaceEndOfString (__in *source, __out *dest, __in find, __in repl) {
  set "temp=!%1:*%~3=%~3!"
  set "%2=!%1:%temp%=%~4!"
  exit /b
}

Keep in mind that "%source%\*%find%*" will match any file that contains %find% within its file name, whereas "%source%\*%find%?" only matches file names that end with %find% including one optional character that could be anything.

I just happened to need some code similar to this and decided to take another look. The main bottleneck of the code seems to be the invocation of the call command. While I don't see a way around this (other than using macros), the execution time of the call command can be greatly improved (with a factor of 2, roughly).

Calling a function by its label seems to be a lot slower than calling the set command. I'm not entirely sure but I can remember something about calling labels being slow due to requiring a rescan of the entire script file. Carets and exclamation marks within file names also appear to remain intact because the delayed expansion phase seems to occur before the set command is called.

@echo off

setlocal DisableDelayedExpansion
set "source=c:\sessions"
set "output=nobars.txt"
set "find=foo"
set "repl=bar"

1>"%output%" (
  for %%e in ("%source%\*%find%*") do (
    set "path=%%~dpe"
    set "file=%%~ne"

    setlocal EnableDelayedExpansion
    set "end=!file:*%find%=%find%!"
    call set "match=%%file:!end!=%repl%%%"

    if not exist "!path!!match!*" (
      echo !file!
    )
    endlocal
  )
)
exit /b


问:
How to get rid of unwanted space in a Chromium Flexbox?

I'm quite new to html 5 and css 3 but I wanted to make project page with flexbox and ran into a problem:

The site looks good in desktop mode but when it switches to the mobile view and "flex-flow: column" there is way too much space between the items as you can see in the pictures below.

Desktop version

Smartphones

The problem only occurs in chromium based browsers (Google Chrome, Vivaldi, Iron, Opera) Firefox, IE and Edge work well.

I'm not allowed to post images yet so I just put the links here.

Down there you can see my CSS code. I hope some can help me with this!

```<code>body {
display: flex;
flex-flow: row wrap;
margin: 0 auto;
background-color: f4f4f4;
font-family: Hind, Sans-serif;
justify-content: space-between;
}
header,
nav,
nav a,
article,
aside,
footer {
border-radius: 0px 0,5em 0em;
padding: 15px;
margin: 0.5em;
flex: 1 100%;
}
header {
background: var(--color-primary);
display: flex;
flex-flow: column;
align-items: center;
}
header * {
flex: 1 1 0%;
}
header nav {
flex: 1 1 100%;
}
nav,
nav ul,
nav li {
margin: 0;
padding: 0;
border: none;
}
nav ul {
display: flex;
flex-direction: column;
}
nav li {
list-style-type: none;
margin: 1.3em 0;
flex: 1 1 100%;
}
nav a {
display: inline-block;
width: 95%;
/*background: #fffbf0;*/
border-bottom: solid 0.1em;
border-color: var(--color-primary);
margin: 0;
font-weight: bold;
text-decoration: none;
text-align: center;
color: var(--color-secondary-2);
}
@media all and (min-width: 35em) {
header {
flex-flow: row wrap;
}
nav ul {
flex-direction: row;
}
nav li {
margin: 0 0.5em;
flex: 1 1 0%;
}
</code>```

Now for the essential HTML part:

```<code><header>
 <nav>
  <ul>
   <li><a href="item1.html">item1</a></li>
   <li><a href="item2.html">item2</a></li>
   <li><a href="item3.html">item3</a></li>
   <li><a href="item4.html">item4</a></li>
   <li><a href="item5.html">item5</a></li>
   <li><a href="item6.html">item6</a></li>
   <li><a href="item7.html">item7</a></li>
  </ul>
 </nav>
</header>
</code>```

答:
It will work if you remove align-items: center; from the header rule

```<code>header {
  background: var(--color-primary);
  display: flex;
  flex-flow: column;
  /*  align-items: center;              commented out */
}
</code>```

and change to flex: 1 1 0%; instead of flex: 1 1 100%; in your nav li rule

```<code>nav li {
  list-style-type: none;
  margin: 1.3em 0;
  flex: 1 1 0%;               /*  change basis to 0%  */
}
</code>```

You also need to close your media query properly by adding its missing end bracket }

Body:
I'm quite new to html 5 and css 3 but I wanted to make project page with flexbox and ran into a problem:

The site looks good in desktop mode but when it switches to the mobile view and "flex-flow: column" there is way too much space between the items as you can see in the pictures below.

Desktop version

Smartphones

The problem only occurs in chromium based browsers (Google Chrome, Vivaldi, Iron, Opera) Firefox, IE and Edge work well.

I'm not allowed to post images yet so I just put the links here.

Down there you can see my CSS code. I hope some can help me with this!

body {
display: flex;
flex-flow: row wrap;
margin: 0 auto;
background-color: f4f4f4;
font-family: Hind, Sans-serif;
justify-content: space-between;
}
header,
nav,
nav a,
article,
aside,
footer {
border-radius: 0px 0,5em 0em;
padding: 15px;
margin: 0.5em;
flex: 1 100%;
}
header {
background: var(--color-primary);
display: flex;
flex-flow: column;
align-items: center;
}
header * {
flex: 1 1 0%;
}
header nav {
flex: 1 1 100%;
}
nav,
nav ul,
nav li {
margin: 0;
padding: 0;
border: none;
}
nav ul {
display: flex;
flex-direction: column;
}
nav li {
list-style-type: none;
margin: 1.3em 0;
flex: 1 1 100%;
}
nav a {
display: inline-block;
width: 95%;
/*background: #fffbf0;*/
border-bottom: solid 0.1em;
border-color: var(--color-primary);
margin: 0;
font-weight: bold;
text-decoration: none;
text-align: center;
color: var(--color-secondary-2);
}
@media all and (min-width: 35em) {
header {
flex-flow: row wrap;
}
nav ul {
flex-direction: row;
}
nav li {
margin: 0 0.5em;
flex: 1 1 0%;
}

Now for the essential HTML part:

item1

item2

item3

item4

item5

item6

item7

Body:
It will work if you remove align-items: center; from the header rule

header {
  background: var(--color-primary);
  display: flex;
  flex-flow: column;
  /*  align-items: center;              commented out */
}

and change to flex: 1 1 0%; instead of flex: 1 1 100%; in your nav li rule

nav li {
  list-style-type: none;
  margin: 1.3em 0;
  flex: 1 1 0%;               /*  change basis to 0%  */
}

You also need to close your media query properly by adding its missing end bracket }


问:
Converting Java Parcel creator code to Kotlin
I'm trying to convert my Parcel Creator code from Java to Kotlin. The auto code converter fails at this and I'm not sure how to resolve it. The code I'm converting is:

```<code>public static final Creator<Save> CREATOR = new Creator<Save>() {

    @Override
    public Save[] newArray(int size) {
        return new Save[size];
    }

    @Override
    public Save createFromParcel(Parcel incoming) {
        return new Save(incoming);
    }
};
</code>```

I end up with this:

```<code>val CREATOR: Parcelable.Creator<Save> = object : Parcelable.Creator<Save> {

    override fun newArray(size: Int): Array<Save> {
        return arrayOfNulls(size)
    }

    override fun createFromParcel(incoming: Parcel): Save {
        return Save(incoming)
    }
}
</code>```

which gives an error saying 'Type inference failed' for arrayOfNulls(size). I have tried changing it to Save(size) but that doesn't work either. Any Ideas?

答:
arrayOfNulls will return an array of nullable elements, Array<Save?> in this case. You should change your function's return type to match that.

```<code>override fun newArray(size: Int): Array<Save?> {
    return arrayOfNulls(size)
}
</code>```

Body:
I'm trying to convert my Parcel Creator code from Java to Kotlin. The auto code converter fails at this and I'm not sure how to resolve it. The code I'm converting is:

public static final Creator<Save> CREATOR = new Creator<Save>() {

    @Override
    public Save[] newArray(int size) {
        return new Save[size];
    }

    @Override
    public Save createFromParcel(Parcel incoming) {
        return new Save(incoming);
    }
};

I end up with this:

val CREATOR: Parcelable.Creator<Save> = object : Parcelable.Creator<Save> {

    override fun newArray(size: Int): Array<Save> {
        return arrayOfNulls(size)
    }

    override fun createFromParcel(incoming: Parcel): Save {
        return Save(incoming)
    }
}

which gives an error saying 'Type inference failed' for arrayOfNulls(size). I have tried changing it to Save(size) but that doesn't work either. Any Ideas?

Body:
arrayOfNulls will return an array of nullable elements, Array<Save?> in this case. You should change your function's return type to match that.

override fun newArray(size: Int): Array<Save?> {
    return arrayOfNulls(size)
}


问:
How can I compute simple addition on multiple .xyz files?
I am currently trying to write a Python program that will take 2 existing .xyz files (containing 3 columns of values separated by spaces), loop through them, add numbers from equivalent positions in each column of the list, then write those values to a separate .txt file in the same position.

For example, if I have the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 1 1 1
(atom symbol) 2 2 2
(atom symbol) 3 3 3
```

<p>and the list:</p>

<pre class="lang-none prettyprint-override"><code>(line denoting number of atoms)
(comment line)
(atom symbol) 3 3 3
(atom symbol) 2 2 2
(atom symbol) 1 1 1
</code>```

I want to make python create a new file in the form:

(line denoting number of atoms)
(comment line)
(atom symbol) 4 4 4
(atom symbol) 4 4 4
(atom symbol) 4 4 4
```

<p>Currently my is giving me the error:</p>

<pre class="lang-none prettyprint-override"><code>TypeError: float() argument must be a string or a number
</code>```

and my code is:

```<code>def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
        for line1 in myfile_1.readlines():
            parts1 = line1.split('\n')
        for line2 in myfile_2.readlines():
            parts2 = line2.split('\n')

    with open(outfile, 'w') as outputfile:
        totalenergy = float(parts1) + float(parts2)

    print("The output was printed to:", outfile)

sumen()
</code>```

答:
Here's how I would do it:

```<code>def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, \
         open(infile_2, 'r') as myfile_2, \
         open(outfile, 'w') as outputfile:

        for _ in range(2):  # copy first two lines of first file (and advance second)
            outputfile.write(next(myfile_1))
            next(myfile_2)

        for (line1, line2) in zip(myfile_1, myfile_2):
            parts1 = line1.split()
            parts2 = line2.split()
            totalenergy = [float(parts1[i]) + float(parts2[i]) for i in range(1, len(parts1))]
            outputfile.write('{} {}\n'.format(parts1[0], ' '.join(map(str, totalenergy))))

    print("The output was printed to:", outfile)

sumen()
</code>```

For your sample input files, this will produce an output file that looks something like this:

(line denoting number of atoms)
(comment line)
(atom symbol) 4.0 4.0 4.0
(atom symbol) 4.0 4.0 4.0
(atom symbol) 4.0 4.0 4.0
```

Body:
I am currently trying to write a Python program that will take 2 existing .xyz files (containing 3 columns of values separated by spaces), loop through them, add numbers from equivalent positions in each column of the list, then write those values to a separate .txt file in the same position.

For example, if I have the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 1 1 1
(atom symbol) 2 2 2
(atom symbol) 3 3 3

and the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 3 3 3
(atom symbol) 2 2 2
(atom symbol) 1 1 1

I want to make python create a new file in the form:

(line denoting number of atoms)
(comment line)
(atom symbol) 4 4 4
(atom symbol) 4 4 4
(atom symbol) 4 4 4

Currently my is giving me the error:

TypeError: float() argument must be a string or a number

and my code is:

def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
        for line1 in myfile_1.readlines():
            parts1 = line1.split('\n')
        for line2 in myfile_2.readlines():
            parts2 = line2.split('\n')

    with open(outfile, 'w') as outputfile:
        totalenergy = float(parts1) + float(parts2)

    print("The output was printed to:", outfile)

sumen()

Body:
Here's how I would do it:

def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, \
         open(infile_2, 'r') as myfile_2, \
         open(outfile, 'w') as outputfile:

        for _ in range(2):  # copy first two lines of first file (and advance second)
            outputfile.write(next(myfile_1))
            next(myfile_2)

        for (line1, line2) in zip(myfile_1, myfile_2):
            parts1 = line1.split()
            parts2 = line2.split()
            totalenergy = [float(parts1[i]) + float(parts2[i]) for i in range(1, len(parts1))]
            outputfile.write('{} {}\n'.format(parts1[0], ' '.join(map(str, totalenergy))))

    print("The output was printed to:", outfile)

sumen()

For your sample input files, this will produce an output file that looks something like this:

(line denoting number of atoms)
(comment line)
(atom symbol) 4.0 4.0 4.0
(atom symbol) 4.0 4.0 4.0
(atom symbol) 4.0 4.0 4.0


问:
Why does calling GetDlgItem cause an access violation?
I am trying to access one of my MFC view's dialog elements. To do this, I run the following line of code:

```<code>    ((CButton*)GetDlgItem( IDC_RADIO_VIEW2 ))->SetCheck( 0 );
</code>```

This causes the following exception:

Exception thrown at 0x53072844 (mfc140ud.dll) in NameOfMyApplication.exe: 0xC0000005: Access violation reading location 0x00000020.

What's strange about this is that the line above it does not cause an access violation, despite being basically the same thing. The line above it is:

```<code>    ((CButton*)GetDlgItem( IDC_RADIO_VIEW1 ))->SetCheck( 1 );
</code>```

Does anyone know why this is happening?

答:
Obviously, the item with the ID IDC_RADIO_VIEW1 exists, but the item with the ID IDC_RADIO_VIEW2 does not exist. So when you try to retrieve that dialog item, you get a NULL pointer. Yet you cast it to a CButton pointer and then attempt to dereference it without validating the pointer. Right there, you've invoked undefined behavior. Your program has a serious bug, and anything could happen. Luckily, the runtime environment jumped in and issued an access violation before the nasal demons could be unleashed.

The correct way to write the code would be to validate functions' return values. If nothing else, use an assertion:

```<code>CButton* pBtn = ((CButton*)GetDlgItem(IDC_RADIO_VIEW2));
ASSERT(pBtn != NULL);
pBtn->SetCheck(0);
</code>```

This would have given you a very readable (and debuggable) error message.

Note that it would also be more readable to use symbolic constants, rather than magic numbers. So you should be writing SetCheck(BST_UNCHECKED) (or BST CHECKED or BST_INDETERMINATE).

Body:
I am trying to access one of my MFC view's dialog elements. To do this, I run the following line of code:

    ((CButton*)GetDlgItem( IDC_RADIO_VIEW2 ))->SetCheck( 0 );

This causes the following exception:

Exception thrown at 0x53072844 (mfc140ud.dll) in NameOfMyApplication.exe: 0xC0000005: Access violation reading location 0x00000020.

What's strange about this is that the line above it does not cause an access violation, despite being basically the same thing. The line above it is:

    ((CButton*)GetDlgItem( IDC_RADIO_VIEW1 ))->SetCheck( 1 );

Does anyone know why this is happening?

Body:
Obviously, the item with the ID IDC_RADIO_VIEW1 exists, but the item with the ID IDC_RADIO_VIEW2 does not exist. So when you try to retrieve that dialog item, you get a NULL pointer. Yet you cast it to a CButton pointer and then attempt to dereference it without validating the pointer. Right there, you've invoked undefined behavior. Your program has a serious bug, and anything could happen. Luckily, the runtime environment jumped in and issued an access violation before the nasal demons could be unleashed.

The correct way to write the code would be to validate functions' return values. If nothing else, use an assertion:

CButton* pBtn = ((CButton*)GetDlgItem(IDC_RADIO_VIEW2));
ASSERT(pBtn != NULL);
pBtn->SetCheck(0);

This would have given you a very readable (and debuggable) error message.

Note that it would also be more readable to use symbolic constants, rather than magic numbers. So you should be writing SetCheck(BST_UNCHECKED) (or BST CHECKED or BST_INDETERMINATE).


问:
Setting up ProGuard with Android Library Projects
I'm trying to setup proguard for my Android project. My application project has very little code in it, but references a library project which has the vast majority of the code and any other external jars. That being said, I'm not sure how to setup proguard to take this into account. Right now my proguard config file is just the Android example from the ProGuard site. I've been searching around, but haven't found a lot or any documentation on using proguard with library projects, just jars. I'm new to proguard, so any push in the right direction would be great. Thanks.</p>

答:
It makes sense to me to specify proguard settings for a library (like which library files shouldn't be obfuscated) in the library project. I've found that I also need to include proguard configurations from my library modules in my application. To do this, I added the following to the defaultConfig section in my library's build.gradle

apply plugin: 'com.android.library'

android {
    defaultConfig {
        consumerProguardFiles 'proguard-rules.pro'
    }
}
```

and then configured the proguard-rules.pro file in my library module to keep the names of important serialized classes.

See also consumerProguardFiles gradle reference

Body:
It makes sense to me to specify proguard settings for a library (like which library files shouldn't be obfuscated) in the library project. I've found that I also need to include proguard configurations from my library modules in my application. To do this, I added the following to the defaultConfig section in my library's build.gradle

apply plugin: 'com.android.library'

android {
    defaultConfig {
        consumerProguardFiles 'proguard-rules.pro'
    }
}

and then configured the proguard-rules.pro file in my library module to keep the names of important serialized classes.

See also consumerProguardFiles gradle reference


问:
API Route available with Any token JWT+PASSPORT
I'm building api for my app and trying to use passport jwt.
I can register new users and login(get the token back) but when I use the Postman to check the "protected" route I can use Any Token like this 'any any'
Pasport.js

```<code>const   JwtStrategy = require('passport-jwt').Strategy,
        ExtractJwt = require('passport-jwt').ExtractJwt;

const   User = require('../api/models/user/userModel'),// load up the user model
        config = require('../config/database'); // get db config file

module.exports = (passport)=> {
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findOne({id: jwt_payload.id}, (err, user)=> {
            if (err) {
                return done(err, false);
            }
            if (user) {
                done(null, user);
            } else {
                done(null, false);
            }
        });
    }));
};
</code>```

Server.js

```<code>const   express = require('express'),
        app = express(),
        port = process.env.PORT || 3000,
        mongoose = require('mongoose'),
        morgan = require('morgan'),
        passport = require('passport'),
        bodyParser = require('body-parser'),
        jwt = require('jsonwebtoken'),
        config = require('./config/database'),
        Event = require('./api/models/event/eventModel'),
        User = require('./api/models/user/userModel');

mongoose.Promise = global.Promise;

mongoose.connect(config.database);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(passport.initialize());

/* Routers registration */

const routesEvent = require('./api/routes/event/eventRoutes');
routesEvent(app);

const routesUser = require('./api/routes/user/userRoutes');
routesUser(app);

/* END Routers registration */

/* Express middleware
 * which used to return more interactive messages */

app.use((req, res, next)=>{
    res.status(404).send({url: req.originalUrl + ' not found'});
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

/* END Express middleware */

// Launch the server on port 3000
const server = app.listen(3000, () => {
    const { address, port } = server.address();
    console.log(`RESTful API server Listening at http://${address}:${port}`);
});
</code>```

EventRouter.js

```<code>const   jwt = require('jsonwebtoken'),
    passport = require('passport');

require('../../../config/passport')(passport); // as strategy in ./passport.js needs passport object

module.exports = (app)=> {
    const event = require('../../controllers/event/eventController');

    // Routes
    app.route('/events' )
        .get( event.list_all_events, passport.authenticate('jwt', { session: false}));

};
</code>```

EventController

```<code>const   mongoose = require('mongoose'),
        Event = mongoose.model('Events'),
        getToken = require('../../../config/getToken');

exports.list_all_events = (req, res)=> {
    let token = getToken(req.headers);
    if(token){
        Event.find({}, (err, event)=> {
            if (err)
                res.send(err);
            res.json(event);
        });
    } else {
        return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }

};
</code>```

I'm definitely doing something wrong in controller or in this file

GetToken.js

```<code>module.exports = getToken = (headers)=> {
    console.log(headers);
    if (headers && headers.authorization) {
        let parted = headers.authorization.split(' ');
//Here I can see my Token from the Postman
        if (parted.length === 2) {
            return parted[1];
        } else {
            return null;
        }
    } else {
        return null;
    }
};
</code>```

Please, any ideas about a mistake that I'm making above?

答:
Below line act as an middle ware. It is validating JWT token, once token is validated it will call JwtStrategy and setting user object in request and then it will call the actual function which is suppose to be executed.

```<code>passport.authenticate('jwt', { session: false})
</code>```

You really do not need getToken function. It will be taken care by above line. If token is not validated then above line automatically returns 401.

Body:
I'm building api for my app and trying to use passport jwt.
I can register new users and login(get the token back) but when I use the Postman to check the "protected" route I can use Any Token like this 'any any'
Pasport.js

const   JwtStrategy = require('passport-jwt').Strategy,
        ExtractJwt = require('passport-jwt').ExtractJwt;

const   User = require('../api/models/user/userModel'),// load up the user model
        config = require('../config/database'); // get db config file

module.exports = (passport)=> {
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findOne({id: jwt_payload.id}, (err, user)=> {
            if (err) {
                return done(err, false);
            }
            if (user) {
                done(null, user);
            } else {
                done(null, false);
            }
        });
    }));
};

Server.js

const   express = require('express'),
        app = express(),
        port = process.env.PORT || 3000,
        mongoose = require('mongoose'),
        morgan = require('morgan'),
        passport = require('passport'),
        bodyParser = require('body-parser'),
        jwt = require('jsonwebtoken'),
        config = require('./config/database'),
        Event = require('./api/models/event/eventModel'),
        User = require('./api/models/user/userModel');

mongoose.Promise = global.Promise;

mongoose.connect(config.database);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(passport.initialize());

/* Routers registration */

const routesEvent = require('./api/routes/event/eventRoutes');
routesEvent(app);

const routesUser = require('./api/routes/user/userRoutes');
routesUser(app);

/* END Routers registration */

/* Express middleware
 * which used to return more interactive messages */

app.use((req, res, next)=>{
    res.status(404).send({url: req.originalUrl + ' not found'});
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

/* END Express middleware */

// Launch the server on port 3000
const server = app.listen(3000, () => {
    const { address, port } = server.address();
    console.log(`RESTful API server Listening at http://${address}:${port}`);
});

EventRouter.js

const   jwt = require('jsonwebtoken'),
    passport = require('passport');

require('../../../config/passport')(passport); // as strategy in ./passport.js needs passport object

module.exports = (app)=> {
    const event = require('../../controllers/event/eventController');

    // Routes
    app.route('/events' )
        .get( event.list_all_events, passport.authenticate('jwt', { session: false}));

};

EventController

const   mongoose = require('mongoose'),
        Event = mongoose.model('Events'),
        getToken = require('../../../config/getToken');

exports.list_all_events = (req, res)=> {
    let token = getToken(req.headers);
    if(token){
        Event.find({}, (err, event)=> {
            if (err)
                res.send(err);
            res.json(event);
        });
    } else {
        return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }

};

I'm definitely doing something wrong in controller or in this file

GetToken.js

module.exports = getToken = (headers)=> {
    console.log(headers);
    if (headers && headers.authorization) {
        let parted = headers.authorization.split(' ');
//Here I can see my Token from the Postman
        if (parted.length === 2) {
            return parted[1];
        } else {
            return null;
        }
    } else {
        return null;
    }
};

Please, any ideas about a mistake that I'm making above?

Body:
Below line act as an middle ware. It is validating JWT token, once token is validated it will call JwtStrategy and setting user object in request and then it will call the actual function which is suppose to be executed.

passport.authenticate('jwt', { session: false})

You really do not need getToken function. It will be taken care by above line. If token is not validated then above line automatically returns 401.


问:
c# aforge simulate webcam ISP RGB Gain register change
I'm developing a program which can simulate a webcam's ISP RGB gain register value. The simulated value will be sent to the vender to be hard coded to the device AP.

I noticed there are many filters inside Aforge, and even without it, I can use the newFrame() method to apply other filters to be displayed.

But, what filter( or algorithm ) should I use to simulate this ISP RGB gain register value? As far as I know there was no property simular to it inside

```<code>                videoDevice.DisplayPropertyPage(IntPtr.Zero);
</code>```

.

答:
There are indeed a handful of filters, and I find the best one for your intended use to be the GammaCorrection filter:

```<code>GammaCorrection _filtroGamma = new GammaCorrection();
double _gamma = 1;  // should be between 0.1 and 5.0, 1.0 is the neutral value (does nothing)

void NewFrameHandler(object sender, NewFrameEventArgs eventArgs)
{
    var bitmap = eventArgs.Frame;
    _filtroGamma.Gamma = _gamma;
    _filtroGamma.ApplyInPlace(bitmap);
    DoSomething(bitmap);
}
</code>```

Body:
I'm developing a program which can simulate a webcam's ISP RGB gain register value. The simulated value will be sent to the vender to be hard coded to the device AP.

I noticed there are many filters inside Aforge, and even without it, I can use the newFrame() method to apply other filters to be displayed.

But, what filter( or algorithm ) should I use to simulate this ISP RGB gain register value? As far as I know there was no property simular to it inside

                videoDevice.DisplayPropertyPage(IntPtr.Zero);

.

Body:
There are indeed a handful of filters, and I find the best one for your intended use to be the GammaCorrection filter:

GammaCorrection _filtroGamma = new GammaCorrection();
double _gamma = 1;  // should be between 0.1 and 5.0, 1.0 is the neutral value (does nothing)

void NewFrameHandler(object sender, NewFrameEventArgs eventArgs)
{
    var bitmap = eventArgs.Frame;
    _filtroGamma.Gamma = _gamma;
    _filtroGamma.ApplyInPlace(bitmap);
    DoSomething(bitmap);
}


问:
React toolbox deletable chips
I try to add many chips (http://react-toolbox.com/#/components/chip) but I really fail with React...

The exemples in the link only show a single deletable chip. As long as there is a single Deletable Chip, it works, but I can't make it works with more chips.

Here's my code :

```<code>import React, { PropTypes } from 'react';
import Chip from 'react-toolbox/lib/chip';

var Chiplist = [
    {'id': 1, 'title': 'Keyword 1'},
    {'id': 2, 'title': 'Keyword 2'},
    {'id': 3, 'title': 'Keyword 3'},
    {'id': 4, 'title': 'Keyword 4'}
 ];

class ChipsList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {deleted : {1: false, 2: false, 3: false, 4: false}};
    /*for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
    }*/
  }

 /* for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
  }*/

  handleDeleteClick(index) {
    /*this.setState({
      deleted : {1: false, 2: true, 3: false, 4: false}
    });
    console.log(this);*/
    console.log(index);
  };

  render () {
    const mychips = Chiplist.map((chip, index) =>
      this.state.deleted[index] ? null : ( <Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>{chip.title}</Chip> )
    );
    return (
      <div className="chips-list">
        { mychips }
      </div>
    );
  }
}

export default ChipsList;
</code>```

Why, when I want to pass the index value to the function, the function is called all the time, I don't know why...

答:
Because you're calling the function:

```<code><Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>
</code>```

The correct way to pass a function is by not invoking it, ie:

```<code><Chip deletable onDeleteClick={this.handleDeleteClick}>
</code>```

However, since you need the index, you'll need to save that somehow. Enter closures. What you need to do is have a function that returns a function, like this:

```<code>handleDeleteClick(index) {
  return () => {
    console.log(index);
  }
};
</code>```

Then, you can create a chip using your original method:

```<code><Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>
</code>```

Title: React toolbox deletable chips

Body:
I try to add many chips (http://react-toolbox.com/#/components/chip) but I really fail with React...

The exemples in the link only show a single deletable chip. As long as there is a single Deletable Chip, it works, but I can't make it works with more chips.

Here's my code :

import React, { PropTypes } from 'react';
import Chip from 'react-toolbox/lib/chip';

var Chiplist = [
    {'id': 1, 'title': 'Keyword 1'},
    {'id': 2, 'title': 'Keyword 2'},
    {'id': 3, 'title': 'Keyword 3'},
    {'id': 4, 'title': 'Keyword 4'}
 ];

class ChipsList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {deleted : {1: false, 2: false, 3: false, 4: false}};
    /*for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
    }*/
  }

 /* for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
  }*/

  handleDeleteClick(index) {
    /*this.setState({
      deleted : {1: false, 2: true, 3: false, 4: false}
    });
    console.log(this);*/
    console.log(index);
  };

  render () {
    const mychips = Chiplist.map((chip, index) =>
      this.state.deleted[index] ? null : ( <Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>{chip.title}</Chip> )
    );
    return (

        { mychips }

    );
  }
}

export default ChipsList;

Why, when I want to pass the index value to the function, the function is called all the time, I don't know why...

Body:
Because you're calling the function:

<Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>

The correct way to pass a function is by not invoking it, ie:

<Chip deletable onDeleteClick={this.handleDeleteClick}>

However, since you need the index, you'll need to save that somehow. Enter closures. What you need to do is have a function that returns a function, like this:

handleDeleteClick(index) {
  return () => {
    console.log(index);
  }
};

Then, you can create a chip using your original method:

<Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>


问:
Using File.Copy to send PDF to Printer by Printer Name
I am trying to send an PDF file to a printer using the File.Copy method in C#.  When I reference the printer by name however, it always responds with

'Could not find a part of the path'

The printer name is fully qualified.  The user is selecting from a combo box that displays all the systems printers using the PrinterSettings.InstalledPrinters values.

Am I missing something simple?

Example:

```<code>File.Copy(FileInfo.FullName, "\\\\ServerName\\PrinterName", true);
</code>```

The "\\\\ServerName\\PrinterName" is directly one of the names from PrinterSettings.InstalledPrinters collection.

答:
Use one of the printer names that comes out of the printer classes.

```<code>foreach (String printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
     textBox1.Text += printer.ToString() + System.Environment.NewLine;
 }
</code>```

See all the printers that are listed in this text box, copy and paste the printer name in the file.copy method.

```<code>File.Copy(FileInfo.FullName, **Printer name here**, true);
</code>```

Body:
I am trying to send an PDF file to a printer using the File.Copy method in C#.  When I reference the printer by name however, it always responds with

'Could not find a part of the path'

The printer name is fully qualified.  The user is selecting from a combo box that displays all the systems printers using the PrinterSettings.InstalledPrinters values.

Am I missing something simple?

Example:

File.Copy(FileInfo.FullName, "\\\\ServerName\\PrinterName", true);

The "\\\\ServerName\\PrinterName" is directly one of the names from PrinterSettings.InstalledPrinters collection.

Body:
Use one of the printer names that comes out of the printer classes.

foreach (String printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
     textBox1.Text += printer.ToString() + System.Environment.NewLine;
 }

See all the printers that are listed in this text box, copy and paste the printer name in the file.copy method.

File.Copy(FileInfo.FullName, **Printer name here**, true);


问:
NodeJs websocket client for Custom Speech Service
I would like to create a websocket client for the Custom Speech service using a programming language such as Java, NodeJs, Go. Where can I find some technical information on how to consume that websocket from scratch (the expected message, fields, etc)?. I already read the CSS documentation but it focuses on how to use the SDK libraries for C#, javaScript, Android. What should I take into account if wanted to create my own SDK for a different language?

Thanks in advance.

答:
Custom Speech Service uses the same API interface as the Bing Speech API, so you can use the Speech Protocol documentation at https://learn.microsoft.com/en-us/azure/cognitive-services/Speech/API-Reference-REST/websocketprotocol. </p>

<p>You can also start with the Websocket Javascript implementation sample at https://github.com/Azure-Samples/SpeechToText-WebSockets-Javascript. </p>

Body:
Custom Speech Service uses the same API interface as the Bing Speech API, so you can use the Speech Protocol documentation at https://learn.microsoft.com/en-us/azure/cognitive-services/Speech/API-Reference-REST/websocketprotocol.

You can also start with the Websocket Javascript implementation sample at https://github.com/Azure-Samples/SpeechToText-WebSockets-Javascript.


问:
How to call an apollo client query from a redux action
If I'm using redux and the apollo client in my app, what's the best way to trigger a query from an action outside of a component.

For example, if I have a standard app, with redux and apollo client configured, how should I trigger a "refresh" list.  I can trigger a function on the component itself which has the gql, but how would I do it from an action which would be more in line with flux.

```<code>import React, { Component, PropTypes } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { connect } from 'react-redux';
import { refreshProfile } from './actions';

class Profile extends Component { ... }
Profile.propTypes = {
  data: PropTypes.shape({
    loading: PropTypes.bool.isRequired,
    user: PropTypes.object,
  }).isRequired,
};

const UserQuery = gql`
  query getUser {
    user {
      id
      name
    }
  }
`;

const ProfileWithData = graphql(UserQuery)(Profile);
const ProfileWithDataAndState = connect(
 (state) => ({ user: state.user })),
 )(ProfileWithData);
</code>```

And, say I want to trigger an action to refresh that user data?  Since the logic is in the component itself, I'm not sure how I would trigger that gql query from the action itself.

答:
I would need to use the ApolloClient in my actions.js.  e.g.</p>

```<code>import ApolloClient, { createNetworkInterface } from 'apollo-client';
const networkInterface = createNetworkInterface({
  uri: config.graphCoolUri,
});

const client = new ApolloClient({
  networkInterface,
  dataIdFromObject: r => r.id,
});

const { data } = await client.query({
   query: UserQuery
});
</code>```

Body:
If I'm using redux and the apollo client in my app, what's the best way to trigger a query from an action outside of a component.

For example, if I have a standard app, with redux and apollo client configured, how should I trigger a "refresh" list.  I can trigger a function on the component itself which has the gql, but how would I do it from an action which would be more in line with flux.

import React, { Component, PropTypes } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { connect } from 'react-redux';
import { refreshProfile } from './actions';

class Profile extends Component { ... }
Profile.propTypes = {
  data: PropTypes.shape({
    loading: PropTypes.bool.isRequired,
    user: PropTypes.object,
  }).isRequired,
};

const UserQuery = gql`
  query getUser {
    user {
      id
      name
    }
  }
`;

const ProfileWithData = graphql(UserQuery)(Profile);
const ProfileWithDataAndState = connect(
 (state) => ({ user: state.user })),
 )(ProfileWithData);

And, say I want to trigger an action to refresh that user data?  Since the logic is in the component itself, I'm not sure how I would trigger that gql query from the action itself.

Body:
I would need to use the ApolloClient in my actions.js.  e.g.

import ApolloClient, { createNetworkInterface } from 'apollo-client';
const networkInterface = createNetworkInterface({
  uri: config.graphCoolUri,
});

const client = new ApolloClient({
  networkInterface,
  dataIdFromObject: r => r.id,
});

const { data } = await client.query({
   query: UserQuery
});


答: You can try this plugin to do Parcelable, just suggestion, I never tried but come across while googling.</p>

Title: Converting Java Parcel creator code to Kotlin

Body:
I'm trying to convert my Parcel Creator code from Java to Kotlin. The auto code converter fails at this and I'm not sure how to resolve it. The code I'm converting is:

public static final Creator<Save> CREATOR = new Creator<Save>() {

    @Override
    public Save[] newArray(int size) {
        return new Save[size];
    }

    @Override
    public Save createFromParcel(Parcel incoming) {
        return new Save(incoming);
    }
};

I end up with this:

val CREATOR: Parcelable.Creator<Save> = object : Parcelable.Creator<Save> {

    override fun newArray(size: Int): Array<Save> {
        return arrayOfNulls(size)
    }

    override fun createFromParcel(incoming: Parcel): Save {
        return Save(incoming)
    }
}

which gives an error saying 'Type inference failed' for arrayOfNulls(size). I have tried changing it to Save(size) but that doesn't work either. Any Ideas?


问:
Elixir Ecto get all records between two unix epochs
I am trying to to what I thought was a pretty basic ecto query to get the records from between two unix timestamps. Something along the lines of:

```<code>b = Ecto.DateTime.from_unix!(begin_utc_epoch, :second)  |> DateTime.to_naive
e = Ecto.DateTime.from_unix!(end_utc_epoch, :second)  |> DateTime.to_naive
query = from r in MyModel,
where r.inserted_at > ^b and r.inserted_at < ^e
</code>```

I am getting nothing but errors. At the moment it is:

(FunctionClauseError) no function clause matching in DateTime.to_naive/1

I read somewhere that I should be using NaiveDateTime so have been trying to convert to naive time stamps. Any help would be appreciated. I am sure I am doing something wrong because it seems too complicated.  Obviously, I am very new to Elixir.  Thanks in advance.

答:
I found a way to do it in a relatively clean way:

```<code>b = NaiveDateTime.add(~N[1970-01-01 00:00:00], begin_utc_epoch)
e = NaiveDateTime.add(~N[1970-01-01 00:00:00], end_utc_epoch)
query = from r in MyModel,
    where r.inserted_at > ^b and r.inserted_at < ^e
</code>```

what was messing me up is that I thought the timestamps in the query results where Ecto.DateTimes (did not know what the sigils ~N[blah blah] where. They are NaiveTimeStamps. I was comparing apples to oranges. Doh!

Body:
I am trying to to what I thought was a pretty basic ecto query to get the records from between two unix timestamps. Something along the lines of:

b = Ecto.DateTime.from_unix!(begin_utc_epoch, :second)  |> DateTime.to_naive
e = Ecto.DateTime.from_unix!(end_utc_epoch, :second)  |> DateTime.to_naive
query = from r in MyModel,
where r.inserted_at > ^b and r.inserted_at < ^e

I am getting nothing but errors. At the moment it is:

(FunctionClauseError) no function clause matching in DateTime.to_naive/1

I read somewhere that I should be using NaiveDateTime so have been trying to convert to naive time stamps. Any help would be appreciated. I am sure I am doing something wrong because it seems too complicated.  Obviously, I am very new to Elixir.  Thanks in advance.

Body:
I found a way to do it in a relatively clean way:

b = NaiveDateTime.add(~N[1970-01-01 00:00:00], begin_utc_epoch)
e = NaiveDateTime.add(~N[1970-01-01 00:00:00], end_utc_epoch)
query = from r in MyModel,
    where r.inserted_at > ^b and r.inserted_at < ^e

what was messing me up is that I thought the timestamps in the query results where Ecto.DateTimes (did not know what the sigils ~N[blah blah] where. They are NaiveTimeStamps. I was comparing apples to oranges. Doh!