答: You can have variable for the time in timeout. Set its value to 120000 when your counter reaches 10. And make sure that you are enclosing settimeout inside IIFE (immediately invoked function expression). So for that time for particular index it'll wait for 2 minutes & then continues the loop with next indexes.</p>

Body:
How can I wait for 1 or 2 minute for every 10 loop?

For instance, this is my working code:

var dates = ["2016-08-31T23:00:00.000Z","2016-09-01T23:00:00.000Z","2016-09-02T23:00:00.000Z","2016-09-03T23:00:00.000Z","2016-09-04T23:00:00.000Z","2016-09-05T23:00:00.000Z","2016-09-06T23:00:00.000Z","2016-09-07T23:00:00.000Z","2016-09-08T23:00:00.000Z","2016-09-09T23:00:00.000Z","2016-09-10T23:00:00.000Z","2016-09-11T23:00:00.000Z","2016-09-12T23:00:00.000Z","2016-09-13T23:00:00.000Z","2016-09-14T23:00:00.000Z","2016-09-15T23:00:00.000Z","2016-09-16T23:00:00.000Z","2016-09-17T23:00:00.000Z","2016-09-18T23:00:00.000Z","2016-09-19T23:00:00.000Z","2016-09-20T23:00:00.000Z","2016-09-21T23:00:00.000Z","2016-09-22T23:00:00.000Z","2016-09-23T23:00:00.000Z","2016-09-24T23:00:00.000Z","2016-09-25T23:00:00.000Z","2016-09-26T23:00:00.000Z","2016-09-27T23:00:00.000Z","2016-09-28T23:00:00.000Z","2016-09-29T23:00:00.000Z","2016-09-30T23:00:00.000Z","2016-10-01T23:00:00.000Z"];

var counter = 0;

// Loop the dates and convert them to this format: yyyy-m-d
dates.forEach(function(date, index) {
    counter ++;

    console.log(date);

    // Reset when you reach 10 counts.
    if (counter === 10) {
        counter = 0;
    }

    // Wait for 2 minute before the next 10 loop.
    setTimeout( function() {
       //
    }, 120000);
});

Is it possible? Any ideas?

EDIT:

What I am after:

2016-08-31T23:00:00.000Z
2016-09-01T23:00:00.000Z
2016-09-02T23:00:00.000Z
2016-09-03T23:00:00.000Z
2016-09-04T23:00:00.000Z
2016-09-05T23:00:00.000Z
2016-09-06T23:00:00.000Z
2016-09-07T23:00:00.000Z
2016-09-08T23:00:00.000Z
2016-09-09T23:00:00.000Z

(wait for 2 minute here)

2016-09-10T23:00:00.000Z
2016-09-11T23:00:00.000Z
2016-09-12T23:00:00.000Z
2016-09-13T23:00:00.000Z
2016-09-14T23:00:00.000Z
2016-09-15T23:00:00.000Z
2016-09-16T23:00:00.000Z
2016-09-17T23:00:00.000Z
2016-09-18T23:00:00.000Z
2016-09-19T23:00:00.000Z

(wait for 2 minute here)

2016-09-20T23:00:00.000Z
2016-09-21T23:00:00.000Z
2016-09-22T23:00:00.000Z
2016-09-23T23:00:00.000Z
2016-09-24T23:00:00.000Z
2016-09-25T23:00:00.000Z
2016-09-26T23:00:00.000Z
2016-09-27T23:00:00.000Z
2016-09-28T23:00:00.000Z
2016-09-29T23:00:00.000Z

(wait for 2 minute here)

2016-09-30T23:00:00.000Z
2016-10-01T23:00:00.000Z


来源: stackexchange

问:
Encountered - "raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden"
```<code>import urllib2

import BeautifulSoup

request = urllib2.Request("https://adexchanger.com/searchresults/?q=digital%20marketing")

response = urllib2.urlopen(request)

soup = BeautifulSoup.BeautifulSoup(response)

for a in soup.findAll('a'):

  if 'digital marketing' in a['href']:

    print a
</code>```

答:
The site apparently blocks the robots and bots so you have to add chrome/ Mozzila headers to act like a browser. Try the code below.</p>

```<code>>>> headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
>>> req = urllib2.Request('https://adexchanger.com/searchresults/?q=digital%20marketing', None, headers)
>>> urllib2.urlopen(req)
<addinfourl at 140245639765816 whose fp = <socket._fileobject object at 0x7f8d7b865250>>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The site apparently blocks the robots and bots so you have to add chrome/ Mozzila headers to act like a browser. Try the code below.

>>> headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
>>> req = urllib2.Request('https://adexchanger.com/searchresults/?q=digital%20marketing', None, headers)
>>> urllib2.urlopen(req)
<addinfourl at 140245639765816 whose fp = <socket._fileobject object at 0x7f8d7b865250>>


问:
Transform a list into a map - foreach or streams?
I want to transform a List<String> into a Map<String, Integer>. The lists' values should serve as keys, and the map value will be statically initialized.

I want to keep the order of the list, thus using a LinkedHashMap, and ignore duplicates.

Question: is there any advantage using the java8 stream API? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop:

```<code>    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));
</code>```

Would you stick to the old approach or go with new lambda expressions?

答:
For this simple case I would stick to the for loop. It is faster too by the way (besides being more readable), Streams do have a cost of the infrastructure that has to be used. This new API is just a tool and as every tool is has pros/cons.

Generally I tent to used stream api only when I have to - let's say that the List needs filtered or mapped to something else, etc - then the Stream usage would make sense. If there are multiple operations that have to be done, it would make code way more readable then doing the same thing with a loop; but that's not always the case - as in your example.

Parallelization (in case you really need it is another aspect). Simple for loops are not easily parallelized, but with streams this is a breeze.

Body:
I want to transform a List<String> into a Map<String, Integer>. The lists' values should serve as keys, and the map value will be statically initialized.

I want to keep the order of the list, thus using a LinkedHashMap, and ignore duplicates.

Question: is there any advantage using the java8 stream API? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop:

    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));

Would you stick to the old approach or go with new lambda expressions?


问:
jQuery function stops working after opening and closing modal window
I have this script which is currently working to turn off and on "likes" on my page:

```<code><script>
$(document).ready(function() {
    $('.like').click(function () {
        $(this).not(this).removeClass('click');
        $(this).toggleClass("click");
    });
});
</script>
</code>```

But when I open a modal window that contains html (with the same script on this page currently), and then close it, the function has stopped working on the underlying page. The "like" buttons no longer work.

One more bit of info, this is an AngularJS app with (currently) very simple modules. I'm sure the problem can be solved in Angular (any solutions are welcome), but I wanted to at least get the jQuery working first before translating it.

Here is the modal window HTML:

```<code><div class="popup-input">
    <div class="feed-box">
        <div class="photo-submit">
            <a href="#" id="photo"><img src="images/pic1-large.jpg"></a>
        </div>
        <div class="comments">
          <div class="comment">
            <a class="avatar">
                <div class="center">
                    <img src="images/meg.jpg">
                </div>
            </a>
            <div class="post-content">
              <a class="author">Meg Robichaud</a>
              <div class="metadata pull-right">
                <div class="date">
                  <ul class="margin-zero">
                    <li><a href=""><img src="images/reply.png" alt="Add Photo" id="reply"></a></li>
                    <li><div class="like"></div></li>
                    <li class="time-posted">25m</li>
                </ul>
            </div>
        </div>
        <div class="text">
            My view this morning is simply beautiful... <a href="">instagram.com/p/mV0PUrHRwQ/</a>
        </div>
    </div>
</div>
<div class="col-wrapper">
    <input type="text" placeholder="Reply..." class="reply" maxlength="30">
</div>
</div>
</div>
</div>

<!--  TOGGLE FUNCTION LIKE BUTTON -->
<script>
$(document).ready(function() {
    $('.like').click(function () {
        $(this).not(this).removeClass('click');
        $(this).toggleClass("click");
    });
});
</script>
</code>```

If I don't have the script in this separate html file it won't load when I open the modal (I know there must be a better solution than doubling up on the script).

Here is the script that loads the modal window:

```<code><!-- MODAL IMAGE POPUP -->
<script>
$(document).ready(function() {
    $('#photo').click(function(e) {
        e.stopPropagation();
        $.get('image.html', function(data){
            modal.open({content: data});
        });
    });
});
</script>
</code>```

And lastly, here is the pop-up window modal script file being referenced:

```<code>var modal = (function(){
  var
  method = {},
  $overlay,
  $modal,
  $content,
  $close;

        // Center the modal in the viewport
        method.center = function () {
          var top, left;

          top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2;
          left = Math.max($(window).width() - $modal.outerWidth(), 0) / 2;

          $modal.css({
            top:top + $(window).scrollTop(),
            left:left + $(window).scrollLeft()
          });
        };

        // Open the modal
        method.open = function (settings) {
          $content.empty().append(settings.content);

          $modal.css({
            width: settings.width || 'auto',
            height: settings.height || 'auto'
          });

          method.center();
          $(window).bind('resize.modal', method.center);
          $modal.show();
          $overlay.show();
        };

        // Close the modal
        method.close = function () {
          $modal.hide();
          $overlay.hide();
          $content.empty();
          $(window).unbind('resize.modal');
        };

        // Generate the HTML and add it to the document
        $overlay = $('<div id="overlay"></div>');
        $modal = $('<div id="modal"></div>');
        $content = $('<div id="content"></div>');
        $close = $('<a id="close" href="#">close</a>');

        $modal.hide();
        $overlay.hide();
        $modal.append($content, $close);

        $(document).ready(function(){
          $('body').append($overlay, $modal);
        });

        $close.click(function(e){
          e.preventDefault();
          method.close();
        });

        return method;
      }());

      // Calls
      $(document).ready(function() {

        $('#message').click(function(e) {
          $.get('popup-form.html', function(data){
            modal.open({content: data});
          });
        });

        $('#test').click(function(e) {
          $.get('popup-form.html', function(data){
            modal.open({content: data});
          });
        });

        $('a#photo').click(function(e){
          modal.open({content: "Hows it going?"});
          e.preventDefault();
        });

      });
</code>```

答:
I just passes event to click function, and use event.preventDefault(). for stop the current event propogation.

```<code>$(document).ready(function() {
        $('.like').click(function (event) {
            $(this).not(this).removeClass('click');
            $(this).toggleClass("click");
    event.preventDefault();
        });
    });
</code>```

Body:
I have this script which is currently working to turn off and on "likes" on my page:

But when I open a modal window that contains html (with the same script on this page currently), and then close it, the function has stopped working on the underlying page. The "like" buttons no longer work.

One more bit of info, this is an AngularJS app with (currently) very simple modules. I'm sure the problem can be solved in Angular (any solutions are welcome), but I wanted to at least get the jQuery working first before translating it.

Here is the modal window HTML:

              Meg Robichaud

25m

            My view this morning is simply beautiful... instagram.com/p/mV0PUrHRwQ/

    <input type="text" placeholder="Reply..." class="reply" maxlength="30">

If I don't have the script in this separate html file it won't load when I open the modal (I know there must be a better solution than doubling up on the script).

Here is the script that loads the modal window:

And lastly, here is the pop-up window modal script file being referenced:

var modal = (function(){
  var
  method = {},
  $overlay,
  $modal,
  $content,
  $close;

        // Center the modal in the viewport
        method.center = function () {
          var top, left;

          top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2;
          left = Math.max($(window).width() - $modal.outerWidth(), 0) / 2;

          $modal.css({
            top:top + $(window).scrollTop(),
            left:left + $(window).scrollLeft()
          });
        };

        // Open the modal
        method.open = function (settings) {
          $content.empty().append(settings.content);

          $modal.css({
            width: settings.width || 'auto',
            height: settings.height || 'auto'
          });

          method.center();
          $(window).bind('resize.modal', method.center);
          $modal.show();
          $overlay.show();
        };

        // Close the modal
        method.close = function () {
          $modal.hide();
          $overlay.hide();
          $content.empty();
          $(window).unbind('resize.modal');
        };

        // Generate the HTML and add it to the document
        $overlay = $('

');
        $modal = $('

');
        $content = $('

');
        $close = $('close');

        $modal.hide();
        $overlay.hide();
        $modal.append($content, $close);

        $(document).ready(function(){
          $('body').append($overlay, $modal);
        });

        $close.click(function(e){
          e.preventDefault();
          method.close();
        });

        return method;
      }());

      // Calls
      $(document).ready(function() {

        $('#message').click(function(e) {
          $.get('popup-form.html', function(data){
            modal.open({content: data});
          });
        });

        $('#test').click(function(e) {
          $.get('popup-form.html', function(data){
            modal.open({content: data});
          });
        });

        $('a#photo').click(function(e){
          modal.open({content: "Hows it going?"});
          e.preventDefault();
        });

      });

Body:
I just passes event to click function, and use event.preventDefault(). for stop the current event propogation.

$(document).ready(function() {
        $('.like').click(function (event) {
            $(this).not(this).removeClass('click');
            $(this).toggleClass("click");
    event.preventDefault();
        });
    });


问:
Has anybody been able to install PyWeka?
I need to install in python 2.6 or 2.7 for windows the library PyWeka0.3dev, It says it requires setuptools, which I installed but then they told me it was a deprecated instalation library and I installed distribute, then I downloaded the PyWeka compressed package and each time I try to install it neither with setup.py nor with easy_install (where it says something like no module ez_setup). Can anybody give me a clue about how to do this?</p>

答:
As mentioned to you via Aardvark (yes, I am omnipresent), the module in question is broken. You can't easy_install it. It's a bug in PyWeka.

You can download the file from PyPI, http://pypi.python.org/pypi/PyWeka/0.3dev, and unpack it.

In the file setup.py, remove the following two lines:

```<code>from ez_setup import use_setuptools
use_setuptools()
</code>```

And install it by running

```<code>python setup.py install
</code>```

You need to have installed numpy and NamedMatrix (which has the same bug as PyWeka) first.

However, you mentioned you are on Windows. I strongly doubt that PyWeka will work on Windows. There are some Unix specific code in it.

And I still really want to know why the authors are reading files by calling cat from subprocess. That seems pretty pointless and is  together with the broken install, good enough reason for me to keep far away from that module. I suspect it's authors simply have no idea what they are doing.

That, or they are geniuses.

ContentLicense: CC BY-SA 2.5

Body:
As mentioned to you via Aardvark (yes, I am omnipresent), the module in question is broken. You can't easy_install it. It's a bug in PyWeka.

You can download the file from PyPI, http://pypi.python.org/pypi/PyWeka/0.3dev, and unpack it.

In the file setup.py, remove the following two lines:

from ez_setup import use_setuptools
use_setuptools()

And install it by running

python setup.py install

You need to have installed numpy and NamedMatrix (which has the same bug as PyWeka) first.

However, you mentioned you are on Windows. I strongly doubt that PyWeka will work on Windows. There are some Unix specific code in it.

And I still really want to know why the authors are reading files by calling cat from subprocess. That seems pretty pointless and is  together with the broken install, good enough reason for me to keep far away from that module. I suspect it's authors simply have no idea what they are doing.

That, or they are geniuses.


问:
Insert using LINQ to SQL in ASP.NET - Error
I want to insert data by using LINQ to SQL in ASP.NET. My codes is shown below. But when i click the 'Kaydet' button then the error occurred. how can i fix it ?

```<code> protected void btnKaydet_Click(object sender, EventArgs e)
    {
            DBDataContext dbnew = new DBDataContext();
            tbl_Kullanicilar user = new tbl_Kullanicilar();

            user.Kullanici_adi = txtKullaniciAdi.Text;
            user.Profil_isim = txtİsim.Text;
            user.Mail = txtEmail.Text;
            user.Kullanici_soyisim = txtSoyisim.Text;
            user.Kullanici_Sifre = txtSifre.Text;
            user.Durum = drpDurum.Text;
            user.Tur = drpTür.Text;
            user.Telefon = txtTelefon.Text;

        dbnew.tbl_Kullanicilars.InsertOnSubmit(user);
        dbnew.SubmitChanges();
    }
</code>```

Error with English :
  Invalid postback or recall independent variable. Event validation was enabled using  or <% @ Page EnableEventValidation = "true"%> in the configuration. This feature verifies that, for security reasons, the return or recall events arguments result from the server control handling them at startup. If the data is valid and as expected, use the ClientScriptManager.RegisterForEventValidation method to save the return or recall data for validation.
  Explanation: An unhandled exception occurred while executing the current web request. Please observe the stack trace to find out more about the error and where it originates in the code.
  Exception Details: System.ArgumentException: Invalid postback or recall independent variable. Event validation was enabled using  or <% @ Page EnableEventValidation = "true"%> in the configuration. This feature verifies that, for security reasons, the return or recall events arguments result from the server control handling them at startup. If the data is valid and as expected, use the ClientScriptManager.RegisterForEventValidation method to save the return or recall data for validation.
  Source Error:
  An exception was thrown when the current web request was executed. Information about the source and location of the exception can be determined using the following exception stack trace.

答:
I solved this error and i want to share the solution to being helpful other people. the solution is that ;

if you get this error, you should add this attribute begin of the example.aspx

```<code>enableEventValidation="false"
</code>```

As a result, it should be

```<code><%@ Page Title=""  enableEventValidation="false" Language="C#" MasterPageFile="~/ProjectMenagement.Master" AutoEventWireup="true" CodeBehind="Kişiler_kişiekle.aspx.cs" Inherits="WebApplication1.Kişiler_kişiekle" %>
</code>```

Body:
I want to insert data by using LINQ to SQL in ASP.NET. My codes is shown below. But when i click the 'Kaydet' button then the error occurred. how can i fix it ?

 protected void btnKaydet_Click(object sender, EventArgs e)
    {
            DBDataContext dbnew = new DBDataContext();
            tbl_Kullanicilar user = new tbl_Kullanicilar();

            user.Kullanici_adi = txtKullaniciAdi.Text;
            user.Profil_isim = txtİsim.Text;
            user.Mail = txtEmail.Text;
            user.Kullanici_soyisim = txtSoyisim.Text;
            user.Kullanici_Sifre = txtSifre.Text;
            user.Durum = drpDurum.Text;
            user.Tur = drpTür.Text;
            user.Telefon = txtTelefon.Text;

        dbnew.tbl_Kullanicilars.InsertOnSubmit(user);
        dbnew.SubmitChanges();
    }

Error with English :
  Invalid postback or recall independent variable. Event validation was enabled using  or <% @ Page EnableEventValidation = "true"%> in the configuration. This feature verifies that, for security reasons, the return or recall events arguments result from the server control handling them at startup. If the data is valid and as expected, use the ClientScriptManager.RegisterForEventValidation method to save the return or recall data for validation.
  Explanation: An unhandled exception occurred while executing the current web request. Please observe the stack trace to find out more about the error and where it originates in the code.
  Exception Details: System.ArgumentException: Invalid postback or recall independent variable. Event validation was enabled using  or <% @ Page EnableEventValidation = "true"%> in the configuration. This feature verifies that, for security reasons, the return or recall events arguments result from the server control handling them at startup. If the data is valid and as expected, use the ClientScriptManager.RegisterForEventValidation method to save the return or recall data for validation.
  Source Error:
  An exception was thrown when the current web request was executed. Information about the source and location of the exception can be determined using the following exception stack trace.

Body:
I solved this error and i want to share the solution to being helpful other people. the solution is that ;

if you get this error, you should add this attribute begin of the example.aspx

enableEventValidation="false"

As a result, it should be

<%@ Page Title=""  enableEventValidation="false" Language="C#" MasterPageFile="~/ProjectMenagement.Master" AutoEventWireup="true" CodeBehind="Kişiler_kişiekle.aspx.cs" Inherits="WebApplication1.Kişiler_kişiekle" %>


问:
Image GD Resizing Issue
So I'm trying to take two large images (but later I'll be combinging 6 images in total), resize them to the x, y width, height I have taken from photoshop, and combine them into one 460 x 230 sized image.

This is the code I'm using

```<code><?php

$dest = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/hero/ana/career-portrait.png');
$src = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-6.png');

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagealphablending($src, false);
imagesavealpha($src, true);

//imagescale($dest, 396, 161.92);
$some = imagecreate(460, 230);

$dest2 = resize($dest, 396, 162);
$src2 = resize($src, 79.19, 79.19);

//imagecopyresized($dest, $dest, 0, 0, 0, 0, 396, 161.92, 1098, 449);
imagecopyresized($src, $src, 10, 10, 0, 0, 79.19, 79.19, 256, 256);
//$img2 = imagecopymerge($dest, $src, 0, 0, 0, 0, 256, 256, 100); //have to play with these numbers for it to work for you, etc.
imagecopymerge($dest2, $src2, 0, 0, 0, 0, 460, 230, 50);

header('Content-Type: image/png');
imagepng($dest, 'merged2.png');
imagepng($dest2);
//file_put_contents('merged.png', $contents);
imagedestroy($dest);
imagedestroy($src);
imagedestroy($some);
imagedestroy($dest2);
imagedestroy($src2);
imagedestroy($img2);
//imagedestroy($then);

function resize($img, $width, $height, $stretch = false)
    {
        $temp = imagecreatetruecolor($width, $height);
        imagealphablending($temp, true);
        imagesavealpha($temp, true);

        $bg = imagecolorallocatealpha($temp, 0, 0, 0, 0); // Background color
        imagefill($temp, 0, 0, $bg);

        if ($stretch)
        {
            imagecopyresampled($temp, img, 0, 0, 0, 0, $width, $height, imagesx($img), imagesy($img));
        }
        else
        {
            if (imagesx($img) <= $width && imagesy($img) <= $height)
            {
                $fwidth = imagesx($img);
                $fheight = imagesy($img);
            }
            else
            {
                $wscale = $width / imagesx($img);
                $hscale = $height / imagesy($img);
                $scale = min($wscale, $hscale);
                $fwidth = $scale * imagesx($img);
                $fheight = $scale * imagesy($img);
            }
            imagecopyresampled($temp,
                $img,
                ($width - $fwidth) / 2, ($height - $fheight) / 2,
                0, 0,
                $fwidth, $fheight,
                imagesx($img), imagesy($img)
            );
        }
        return $temp;
    }
</code>```

The issue is that the image rendered is very faded
because of this line:

imagecopymerge($dest2, $src2, 0, 0, 0, 0, 460, 230, 50);

If I change the 50, which is the PCT value to 100, it shows one image with a black background (masking the other image), but if I change it to 0, it shows only the other image with a black background (masking the other image)
If the value is either 0 or 100, the image shown is at its full color though. How do I merge these 2 images together while preserving their transparency and vibrancy of color?

答:
Instead of imagecopymerge use imagecopy. You also always need to correctly specify the dimensions of the source image when copying:

```<code>$dest = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/hero/ana/career-portrait.png');
$src = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-6.png');

$dest2 = resize($dest, 396, 162);
imagedestroy($dest);
$src2 = resize($src, 79, 79); // should be int not float.
imagedestroy($src);

// the last 2 params must match the width/height of the $src2 image.
imagecopy($dest2, $src2, 0, 0, 0, 0, 79, 79);
imagedestroy($src2);

header('Content-Type: image/png');
imagepng($dest2);

imagedestroy($dest2);
</code>```

You don't need to change the alpha settings on $dest or $src because they aren't being rendered - you render the new image resource created in, and returned by, your resize function. Because of this you do need to slightly change the function:

```<code>function resize($img, $width, $height, $stretch = false)
{
    $temp = imagecreatetruecolor($width, $height);
    imagealphablending($temp, false); // changed to false.
    imagesavealpha($temp, true);
    ...
</code>```

Edit:

You might be better off simply using the imagescale function instead of using your own resize function:

```<code>$dest = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/hero/ana/career-portrait.png');
$src = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-6.png');

$dest2 = imagescale($dest, 396);
imagealphablending($dest2, false);
imagesavealpha($dest2, true);
$src2 = imagescale($src, 79);

imagecopy($dest2, $src2, 0, 0, 0, 0, 79, 79);

header('Content-Type: image/png');
imagepng($dest2);

imagedestroy($dest);
imagedestroy($src);
imagedestroy($dest2);
imagedestroy($src2);
</code>```

Title: Image GD Resizing Issue

Body:
So I'm trying to take two large images (but later I'll be combinging 6 images in total), resize them to the x, y width, height I have taken from photoshop, and combine them into one 460 x 230 sized image.

This is the code I'm using

<?php

$dest = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/hero/ana/career-portrait.png');
$src = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-6.png');

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagealphablending($src, false);
imagesavealpha($src, true);

//imagescale($dest, 396, 161.92);
$some = imagecreate(460, 230);

$dest2 = resize($dest, 396, 162);
$src2 = resize($src, 79.19, 79.19);

//imagecopyresized($dest, $dest, 0, 0, 0, 0, 396, 161.92, 1098, 449);
imagecopyresized($src, $src, 10, 10, 0, 0, 79.19, 79.19, 256, 256);
//$img2 = imagecopymerge($dest, $src, 0, 0, 0, 0, 256, 256, 100); //have to play with these numbers for it to work for you, etc.
imagecopymerge($dest2, $src2, 0, 0, 0, 0, 460, 230, 50);

header('Content-Type: image/png');
imagepng($dest, 'merged2.png');
imagepng($dest2);
//file_put_contents('merged.png', $contents);
imagedestroy($dest);
imagedestroy($src);
imagedestroy($some);
imagedestroy($dest2);
imagedestroy($src2);
imagedestroy($img2);
//imagedestroy($then);

function resize($img, $width, $height, $stretch = false)
    {
        $temp = imagecreatetruecolor($width, $height);
        imagealphablending($temp, true);
        imagesavealpha($temp, true);

        $bg = imagecolorallocatealpha($temp, 0, 0, 0, 0); // Background color
        imagefill($temp, 0, 0, $bg);

        if ($stretch)
        {
            imagecopyresampled($temp, img, 0, 0, 0, 0, $width, $height, imagesx($img), imagesy($img));
        }
        else
        {
            if (imagesx($img) <= $width && imagesy($img) <= $height)
            {
                $fwidth = imagesx($img);
                $fheight = imagesy($img);
            }
            else
            {
                $wscale = $width / imagesx($img);
                $hscale = $height / imagesy($img);
                $scale = min($wscale, $hscale);
                $fwidth = $scale * imagesx($img);
                $fheight = $scale * imagesy($img);
            }
            imagecopyresampled($temp,
                $img,
                ($width - $fwidth) / 2, ($height - $fheight) / 2,
                0, 0,
                $fwidth, $fheight,
                imagesx($img), imagesy($img)
            );
        }
        return $temp;
    }

The issue is that the image rendered is very faded
because of this line:

imagecopymerge($dest2, $src2, 0, 0, 0, 0, 460, 230, 50);

If I change the 50, which is the PCT value to 100, it shows one image with a black background (masking the other image), but if I change it to 0, it shows only the other image with a black background (masking the other image)
If the value is either 0 or 100, the image shown is at its full color though. How do I merge these 2 images together while preserving their transparency and vibrancy of color?

Body:
Instead of imagecopymerge use imagecopy. You also always need to correctly specify the dimensions of the source image when copying:

$dest = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/hero/ana/career-portrait.png');
$src = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-6.png');

$dest2 = resize($dest, 396, 162);
imagedestroy($dest);
$src2 = resize($src, 79, 79); // should be int not float.
imagedestroy($src);

// the last 2 params must match the width/height of the $src2 image.
imagecopy($dest2, $src2, 0, 0, 0, 0, 79, 79);
imagedestroy($src2);

header('Content-Type: image/png');
imagepng($dest2);

imagedestroy($dest2);

You don't need to change the alpha settings on $dest or $src because they aren't being rendered - you render the new image resource created in, and returned by, your resize function. Because of this you do need to slightly change the function:

function resize($img, $width, $height, $stretch = false)
{
    $temp = imagecreatetruecolor($width, $height);
    imagealphablending($temp, false); // changed to false.
    imagesavealpha($temp, true);
    ...

Edit:

You might be better off simply using the imagescale function instead of using your own resize function:

$dest = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/hero/ana/career-portrait.png');
$src = imagecreatefrompng('https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-6.png');

$dest2 = imagescale($dest, 396);
imagealphablending($dest2, false);
imagesavealpha($dest2, true);
$src2 = imagescale($src, 79);

imagecopy($dest2, $src2, 0, 0, 0, 0, 79, 79);

header('Content-Type: image/png');
imagepng($dest2);

imagedestroy($dest);
imagedestroy($src);
imagedestroy($dest2);
imagedestroy($src2);


问:
YoctoProject: change ownership of all files in a recipe
For the YoctoProject (v2.0, Jethro) the ownership of files inside the image defaults to user and group root unless I do explicitly change them by chown and chgrp in the do_install step for the given recipe.

I have a few recipes for which all files should be owned by another group and user than root. Is there a (cleaner/smarter) way to achieve this without calling chown and chgrp in do_install?

答:
You can easily add user adding the following to your recipe.</p>

```<code>inherit extrausers
EXTRA_USERS_PARAMS = " useradd user1; \
                       useradd user2; \
                       useradd user3; \
                       usermod  -p 'user1_psw' user1; \
                       usermod  -p 'user2_psw' user2; \
                       usermod  -p 'user3_psw' user3;\
                       usermod  -a -G sudo user1; \
                       usermod  -a -G sudo user2; \
                       usermod  -a -G sudo user3; "
</code>```

Body:
You can easily add user adding the following to your recipe.

inherit extrausers
EXTRA_USERS_PARAMS = " useradd user1; \
                       useradd user2; \
                       useradd user3; \
                       usermod  -p 'user1_psw' user1; \
                       usermod  -p 'user2_psw' user2; \
                       usermod  -p 'user3_psw' user3;\
                       usermod  -a -G sudo user1; \
                       usermod  -a -G sudo user2; \
                       usermod  -a -G sudo user3; "


问:
Java-based workflow solutions
We currently use a sequential workflow to process documents. We have a total of 10 distinct workflow steps. We have re-analyzed the workflow and realized that we could restructure the workflow to process in parallel a number of the workflow steps. Basically we are able to process steps 1,2,3,4 in parallel, wait until steps 1-4 are completed and then process step 5, then process steps 6,7,8,9 in parallel wait until steps 6-9 are completed and then finally process step 10. If we were able to implement this new workflow we could boost our processing throughput dramatically.

My question is: What java-based open-source workflow projects would you recommend? Do they typically support what I outlined above?

Thanks for all the replies. After taking a quick look at the the websites you all have listed I think I have more than enough to chew on for a while.

答:
There is a commercial one called Appian in case you are interested in.

http://www.appian.com/

Title: Java-based workflow solutions


问:
Extracting data from social media networks
I am trying to create a Web application which will be able to analyze social media profiles. The social networking sites I want to analyze are Facebook, Twitter and YouTube.

I would like to use Data Extraction tool APIs as my back-end. Many of the tools I have found are either expensive or do not work.

I have researched on the Facebook, Twitter and YouTube API among others such as NodeXL.

Would anyone suggest any free available APIs which I could use please? Preferably ones which would not be too difficult to implement.

答:
I think Tiny's answer could answer your question.

But I have another advice if you are asking how to extract data from social networks. You could try some web scraping tools to do that. Most of web scraping tools like Octoparse enable you to log in the targeted social network and extract data from these social networks.
If you are interested, you could refer to Top 30 Free Web Scraping Software to learn more.

ContentLicense: CC BY-SA 4.0


问:
C# Automapper 6.1.1 - Collection/List destination properties loses values Entity Framework 6
I have a problem when mapping collections with Automapper 6 and I can't find a solution. In the updatedArticle object below I have the old Created and Updated values left after mapping since they do not exist on the view model. However the values for Created and Updated in Descriptions are lost. The values that do come in via the view model are all updated correctly. What am I doing wrong? Automapper also loses Entity Framework 6 mapping for Article since those values are lost as well.

Controller method:

```<code>public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
    Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
    Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
    return Ok();
}
</code>```

Mapping:

```<code>Mapper.Initialize(cfg =>
{
    cfg.CreateMap<ArticleViewModel, Article>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore());

    cfg.CreateMap<DescriptionViewModel, Description>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore())
        .ForMember(x => x.ArticleId, opt => opt.Ignore())
        .ForMember(x => x.Article, opt => opt.Ignore());
}
Mapper.AssertConfigurationIsValid();
</code>```

Viewmodels:

```<code>public class ArticleViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<DescriptionViewModel> Descriptions { get; set; }
}

public class DescriptionViewModel
{
    public int Id { get; set; }

    public string Heading { get; set; }
}
</code>```

Models:

```<code>public class Article : IEntity<int>
{
    public Article()
    {
        Descriptions = new List<Description>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Name { get; set; }

    public virtual ICollection<Description> Descriptions { get; set; }
}

public class Description: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}
</code>```

答:
Have you tried this without lazy loading? I had some issues with EF Lazy Loading and AutoMapper myself. First of all it is very inefficient.

See related
Answer.

Body:
I have a problem when mapping collections with Automapper 6 and I can't find a solution. In the updatedArticle object below I have the old Created and Updated values left after mapping since they do not exist on the view model. However the values for Created and Updated in Descriptions are lost. The values that do come in via the view model are all updated correctly. What am I doing wrong? Automapper also loses Entity Framework 6 mapping for Article since those values are lost as well.

Controller method:

public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
    Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
    Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
    return Ok();
}

Mapping:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<ArticleViewModel, Article>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore());

    cfg.CreateMap<DescriptionViewModel, Description>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore())
        .ForMember(x => x.ArticleId, opt => opt.Ignore())
        .ForMember(x => x.Article, opt => opt.Ignore());
}
Mapper.AssertConfigurationIsValid();

Viewmodels:

public class ArticleViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<DescriptionViewModel> Descriptions { get; set; }
}

public class DescriptionViewModel
{
    public int Id { get; set; }

    public string Heading { get; set; }
}

Models:

public class Article : IEntity<int>
{
    public Article()
    {
        Descriptions = new List<Description>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Name { get; set; }

    public virtual ICollection<Description> Descriptions { get; set; }
}

public class Description: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}


问:
Python 2.7 - Raw_input and If and else
raw_input('What are you doing?     ')

a = 'nothing'
if type(a):
    print 'That seems boring'
else:
    print 'Nice'

The meaning of this code, is that if a person answers the raw_input with 'nothing'. It should print that seems boring. And if a person writes something else it should print ok.

I am new to programming so please help me :)

答:
You can also do it like this, it will take input during run time in more oriented way</p>

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

def user_input():

    print "What are you doing?"
    # takes user input
    a = raw_input()
    # if user enter "Nothing" or "nothing"
    if (a == "Nothing") or (a == "nothing"):
        print "boring"
    # if he enters anything else
    else:
        print "nice"

if __name__ == '__main__':
    user_input()
</code>```

Title: Python 2.7 - Raw_input and If and else

Body:
You can also do it like this, it will take input during run time in more oriented way

#!/usr/bin/env python

def user_input():

    print "What are you doing?"
    # takes user input
    a = raw_input()
    # if user enter "Nothing" or "nothing"
    if (a == "Nothing") or (a == "nothing"):
        print "boring"
    # if he enters anything else
    else:
        print "nice"

if __name__ == '__main__':
    user_input()


问:
iTextSharp: Tile Image in Table Cell
I'm trying to tile an image or background image in a table cell in iTextSharp. The closest I have gotten is to attach an image directly to the cell using a PdfPTable and PdfPCell.

```<code>tempCell = new PdfPCell();
tempCell.Image = iTextSharp.text.Image.GetInstance(Path.Combine(GetImageDirectory(), "my_image.gif"));
table.AddCell(tempCell);
</code>```

This has its issues, though. The cells are never the same size in my tables, so the images are scaled automatically by width. This can make some of the cells extra tall comparatively to other cells, or only half full of the image if they are narrow.

Any suggestions on how to get the images tiling, if it is even possible with iTextSharp? Thanks!

答:
If all else fails, you can create a pattern fill and set that in the cell event (or fill in behind the entire table).

You'll draw your image into a PdfPatternPainter template with the bounds you want for the repeating pattern.  You then draw your image into this template at whatever scale you want.

```<code>PdfPatternPainter patternPainter = someContent.createPattern(width, height);
patternPainter.addImage( image, desiredImgSizeX, 0, 0, desiredImgSizeY, 0, 0 );

someContent.saveState();
someContent.setPatternFill( patternPainter );

someContent.rectangle( llx, lly, wid, hei );
someContent.fill();

someContent.restoreState();
</code>```

Your PdfPCellEvent will be given everything you need in the cellLayout override.  You'll probably want to use canvases[PdfPTable.BASECANVAS] in place of someContent above.

You'll want to stash and reuse your patternPainter so you don't get a duplicate for each cell you use it in.  That could cause some pretty horrific file bloat.  No beuno.

Title: iTextSharp: Tile Image in Table Cell

Body:
I'm trying to tile an image or background image in a table cell in iTextSharp. The closest I have gotten is to attach an image directly to the cell using a PdfPTable and PdfPCell.

tempCell = new PdfPCell();
tempCell.Image = iTextSharp.text.Image.GetInstance(Path.Combine(GetImageDirectory(), "my_image.gif"));
table.AddCell(tempCell);

This has its issues, though. The cells are never the same size in my tables, so the images are scaled automatically by width. This can make some of the cells extra tall comparatively to other cells, or only half full of the image if they are narrow.

Any suggestions on how to get the images tiling, if it is even possible with iTextSharp? Thanks!

Body:
If all else fails, you can create a pattern fill and set that in the cell event (or fill in behind the entire table).

You'll draw your image into a PdfPatternPainter template with the bounds you want for the repeating pattern.  You then draw your image into this template at whatever scale you want.

PdfPatternPainter patternPainter = someContent.createPattern(width, height);
patternPainter.addImage( image, desiredImgSizeX, 0, 0, desiredImgSizeY, 0, 0 );

someContent.saveState();
someContent.setPatternFill( patternPainter );

someContent.rectangle( llx, lly, wid, hei );
someContent.fill();

someContent.restoreState();

Your PdfPCellEvent will be given everything you need in the cellLayout override.  You'll probably want to use canvases[PdfPTable.BASECANVAS] in place of someContent above.

You'll want to stash and reuse your patternPainter so you don't get a duplicate for each cell you use it in.  That could cause some pretty horrific file bloat.  No beuno.


问:
CSV Help | Text Delimiter | Use of LibreOffice
I need help with something I'm not quite sure on how to do. Here in the image are data fields (i.e. age) and their values (i.e. 62)
I was wondering how to take age and turn it into a column category and the age values as column entries?

enter image description here

答:
From the image, it looks like after the import there will be a string in cell N2 that starts with {"age":"62".  Find an empty column in the spreadsheet and enter "age" in the first row.  In the second row, enter the following formula.

```<code>=MID(N2,9,2)
</code>```

This produces 62.  See MID for documentation.

Body:
From the image, it looks like after the import there will be a string in cell N2 that starts with {"age":"62".  Find an empty column in the spreadsheet and enter "age" in the first row.  In the second row, enter the following formula.

=MID(N2,9,2)

This produces 62.  See MID for documentation.


问:
Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development
I am rather new to Rails, and I am attempting to run an app from my console. When I open up the site, however, I see this error message. Does anyone have any insight on what it means?

When I try running "rails db:migrate RAILS_ENV=development" I just get:

```<code>Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development
</code>```

When I try running just "rails db:migrate" or "rake db:migrate" I get:

```<code>ArgumentError: wrong number of arguments (0 for 1)
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:600:in `migrate'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:573:in `check_pending!'
</code>```

Thank you so much!

答:
To resolve this issue, run: bin/rails rake db:migrate RAILS_ENV=development

And the issue was raised due to pending migrations, which are created migration files at /db/migrate directory by doing add/remove fields to the existing active record or relation(table) in database.

Migrations are stored as files in the db/migrate directory, one for each migration class. The name of the file is of the form YYYYMMDDHHMMSS_create_products.rb, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example 20080906120000_create_products.rb should define class CreateProducts and 20080906120001_add_details_to_products.rb should define AddDetailsToProducts. Rails uses this timestamp to determine which migration should be run and in what order, so if you're copying a migration from another application or generate a file yourself, be aware of its position in the order.

Example:
        $bin/rails generate migration AddPartNumberToProducts

This will create an empty but appropriately named migration:

```<code>  class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
    def change
    end
  end
</code>```

If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate add_column and remove_column statements will be created.

```<code>   $ bin/rails generate migration AddPartNumberToProducts part_number:string
</code>```

will generate

```<code>   class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
     def change
       add_column :products, :part_number, :string
     end
   end
</code>```

Referred at: http://guides.rubyonrails.org/active_record_migrations.html

Body:
I am rather new to Rails, and I am attempting to run an app from my console. When I open up the site, however, I see this error message. Does anyone have any insight on what it means?

When I try running "rails db:migrate RAILS_ENV=development" I just get:

Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development

When I try running just "rails db:migrate" or "rake db:migrate" I get:

ArgumentError: wrong number of arguments (0 for 1)
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:600:in `migrate'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:573:in `check_pending!'

Thank you so much!

Body:
To resolve this issue, run: bin/rails rake db:migrate RAILS_ENV=development

And the issue was raised due to pending migrations, which are created migration files at /db/migrate directory by doing add/remove fields to the existing active record or relation(table) in database.

Migrations are stored as files in the db/migrate directory, one for each migration class. The name of the file is of the form YYYYMMDDHHMMSS_create_products.rb, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example 20080906120000_create_products.rb should define class CreateProducts and 20080906120001_add_details_to_products.rb should define AddDetailsToProducts. Rails uses this timestamp to determine which migration should be run and in what order, so if you're copying a migration from another application or generate a file yourself, be aware of its position in the order.

Example:
        $bin/rails generate migration AddPartNumberToProducts

This will create an empty but appropriately named migration:

  class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
    def change
    end
  end

If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate add_column and remove_column statements will be created.

   $ bin/rails generate migration AddPartNumberToProducts part_number:string

will generate

   class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
     def change
       add_column :products, :part_number, :string
     end
   end

Referred at: http://guides.rubyonrails.org/active_record_migrations.html


问:
SQL query to fetch rows from one table which are not present in other 3 tables
I have 4 tables,

A, B , C , D

A has column Aid,
B has column Aid,
C has column Aid,
D has column Aid

(Aid is common column in all the 4 tables)

now i want to fetch rows from A table which are not present in B or C or D
can anyone please let me know the SQL query for this.

答:
Please use the following query and it will work perfectly.</p>

```<code>select *  from #A  where  Aid  not in (select Aid   From #B
    UNION
    select Aid   From #C
    Union
    select Aid   From #D)
</code>```

Body:
Please use the following query and it will work perfectly.

select *  from #A  where  Aid  not in (select Aid   From #B
    UNION
    select Aid   From #C
    Union
    select Aid   From #D)


问:
React Router - Stay at the same page after refresh
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

```<code><Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')
</code>```

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

```<code>class App extends Component {

render() {
    return (
        <div className="app-comp">
            <Navigation />
            <div> {this.props.children}</div>
        </div>
    )
  }
}
</code>```

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

答:
Check that firebase does not interfares with the client side routes :P

You can use Index routes to achieve this.

You have your navigation i.e the layout of all pages in your app component so make it the root route.

Then you want your home route to be your default route so make it your Index route.

You need to import IndexRoute from react-router package (from which you import Route).

Add this-

```<code>import { Router, Route, IndexRoute } from 'react-router';
</code>```

and then make your routes like below.

Use this-

```<code><Provider store={store}>
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="/home" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')
</code>```

Body:
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

<Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

class App extends Component {

render() {
    return (

            <Navigation />

 {this.props.children}

    )
  }
}

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

Body:
Check that firebase does not interfares with the client side routes :P

You can use Index routes to achieve this.

You have your navigation i.e the layout of all pages in your app component so make it the root route.

Then you want your home route to be your default route so make it your Index route.

You need to import IndexRoute from react-router package (from which you import Route).

Add this-

import { Router, Route, IndexRoute } from 'react-router';

and then make your routes like below.

Use this-

<Provider store={store}>
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="/home" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')


问:
What iOS supports tel:// file handling?
What was the earliest iOS which supported the tel:// file handler to launch the phone application?

答: tel has been supported since iOS 1.0. At least in Safari. There was no public SDK yet.</p>

Title: What iOS supports tel:// file handling?


问:
How to convert String to BLOB in ESQL?
It should be as simple as

```<code>  SET OutputRoot.BLOB.BLOB = CAST(MYSTRING AS BLOB);
</code>```

But when I do that IIB Throws an error

An attempt was made to cast the character string ''ABC'' to a byte string, but the string was of the wrong format.  There must be an even number of hexadecimal digits (0-9, a-f, A-F).

答:
As you figured out, the Syntax of the CAST-function you need here is

```<code>CAST( <source_expression> AS <DataType> CCSID <expression> )
</code>```

so in your code it is

```<code>CAST( MYSTRING AS BLOB CCSID 1208 )
</code>```

The CCSID parameter is used only for conversions to or from one of the string data types. Use the CCSID parameter to specify the code page of the source or target string. [Source]

So with the Coded character set identifiers (CCSID) you define the code page. For example 1208 is the CCSID for UTF-8 with IBM PUA. You can see a list of IBMs CCSIDs here.

If you want to get informations on this topic in more detail you can check the IIB documentation for Version 9.0.0 or Version 10.0.0.

Title: How to convert String to BLOB in ESQL?

Body:
It should be as simple as

  SET OutputRoot.BLOB.BLOB = CAST(MYSTRING AS BLOB);

But when I do that IIB Throws an error

An attempt was made to cast the character string ''ABC'' to a byte string, but the string was of the wrong format.  There must be an even number of hexadecimal digits (0-9, a-f, A-F).

Body:
As you figured out, the Syntax of the CAST-function you need here is

CAST( <source_expression> AS <DataType> CCSID <expression> )

so in your code it is

CAST( MYSTRING AS BLOB CCSID 1208 )

The CCSID parameter is used only for conversions to or from one of the string data types. Use the CCSID parameter to specify the code page of the source or target string. [Source]

So with the Coded character set identifiers (CCSID) you define the code page. For example 1208 is the CCSID for UTF-8 with IBM PUA. You can see a list of IBMs CCSIDs here.

If you want to get informations on this topic in more detail you can check the IIB documentation for Version 9.0.0 or Version 10.0.0.


问:
CSC : error CS0009: Metadata file '.....\v8-x64.dll' could not be opened -- PE image doesn't contain managed metadata
We got this error on the Jenkins server after we updated our target framework from .NET v4.5.1 to v4.5.2:

Up in the build output we have also warnings like:

(GetReferenceAssemblyPaths target) ->    C:\Program Files
  (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1097,5):
  warning MSB3644: The reference assemblies for framework
  ".NETFramework,Version=v4.5.2" were not found. To resolve this,
  install the SDK or Targeting Pack for this framework version or
  retarget your application to a version of the framework for which you
  have the SDK or Targeting Pack installed. Note that assemblies will be
  resolved from the Global Assembly Cache (GAC) and will be used in
  place of reference assemblies. Therefore your assembly may not be
  correctly targeted for the framework you intend.

When we try to remove ClearScriptV8-32.dll, ClearScriptV8-64.dll, v8-ia32.dll, v8-x64.dll it is compiling with no problem but unfortunately as we use them in the solution the site is not loading.

答:
Installing on Jenkins server .NET v.4.5.2 (link here) resolved the problem.

However if the SDK installer gives you info that v4.5.2 cannot be installed because newer version is already present you can just copy paste the whole from another machine where it is present to c\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5.2

More info:
The problem was that on the Jenkins server we didn't had .NET v4.5.2 but we had .NET v.4.6.
As v.4.6 is claimed to be compatible with 4.5.2 msbuild is using it and giving the warning that was mentioned in the question and at the end CSC  was failing to open v8 Dlls.


问:
Using Dynamic Memory Allocation for strings Arrays
I'm just starting to learn C, so if you can, please don't be so hard on me.
I'm trying to learn how to allocate memory for arrays, so i started with someting like this. I just wanna dynamicly allocate memory for array of strings, and then display it.

```<code>int main( )
{
    int number, i;
    scanf ("%d", &number);
    char **table =(char **) malloc(number*sizeof(char*));
    for(i=0; i<number; i++)
    {
        table[i] = (char *)malloc(6);
    }

    for(i=0; i<number; i++)
    {
        scanf("%s", &table[i]);
    }

    for(i=0; i<number; i++)
    {
        printf("Person nr %d : %s ", i+1, &table[i]);
    }

    for(i=0; i<number; i++)
    {
         free(table[i]);
    }
    free(table);
    return 0;
}
</code>```

But program only works when i type words with 3 or less letters. So, I don't know if i have a problem with memory allocation, or maybe i i just can't print with %s for **char? Maybe someone could tell me where I'm doing wrong and explain why?

Thank you for taking the time to read it :)

答:
&table[i] is of the type char** and table[i] is the type char*.
table[i] is the pointer for your string.
You should change the &table[i] to table[i].

Body:
I'm just starting to learn C, so if you can, please don't be so hard on me.
I'm trying to learn how to allocate memory for arrays, so i started with someting like this. I just wanna dynamicly allocate memory for array of strings, and then display it.

int main( )
{
    int number, i;
    scanf ("%d", &number);
    char **table =(char **) malloc(number*sizeof(char*));
    for(i=0; i<number; i++)
    {
        table[i] = (char *)malloc(6);
    }

    for(i=0; i<number; i++)
    {
        scanf("%s", &table[i]);
    }

    for(i=0; i<number; i++)
    {
        printf("Person nr %d : %s ", i+1, &table[i]);
    }

    for(i=0; i<number; i++)
    {
         free(table[i]);
    }
    free(table);
    return 0;
}

But program only works when i type words with 3 or less letters. So, I don't know if i have a problem with memory allocation, or maybe i i just can't print with %s for **char? Maybe someone could tell me where I'm doing wrong and explain why?

Thank you for taking the time to read it :)


问:
Django Debug Toolbar shows 404 on panel
My Django-Debug-Toolbar results in a Http404 as soon as I click on a Panel like "Requests". I checked my config multiple times but can't find whats wrong.

Versions:

django-debug-toolbar == 1.8

django == 1.11.1

settings.py

```<code># DEBUG TOOLBAR

if DEBUG:

    def custom_show_toolbar(request):
        """ Only show the debug toolbar to users with the superuser flag. """
        #return request.user.is_superuser
        if request.is_ajax():
            return False
        return True

    MIDDLEWARE += (
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    )
    INSTALLED_APPS += (
        'debug_toolbar',
    )
    INTERNAL_IPS = ('127.0.0.1', )
    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
        'SHOW_TOOLBAR_CALLBACK': 'core.settings.custom_show_toolbar',
        'HIDE_DJANGO_SQL': True,
        'TAG': 'body',
        'SHOW_TEMPLATE_CONTEXT': True,
        'ENABLE_STACKTRACES': True,
    }
</code>```

urls.py

```<code>urlpatterns = [
    url(r'^$', core_views.home, name='home'),
    #url(r'^login/$', auth_views.login, name='login'),
    #url(r'^logout/$', auth_views.logout, name='logout'),
    #url(r'^oauth/', include('social_django.urls', namespace='social')),
    url(r'^admin/', admin.site.urls),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns
</code>```

Screenshot

答:
The problem is your custom_show_toolbar method. You are explicitly disabling the toolbar for ajax requests. Since the debug toolbar loads the panel using ajax requests, you get a 404.

```<code>def custom_show_toolbar(request):
    ...
    if request.is_ajax():
        return False
    return True
</code>```

Title: Django Debug Toolbar shows 404 on panel

Body:
My Django-Debug-Toolbar results in a Http404 as soon as I click on a Panel like "Requests". I checked my config multiple times but can't find whats wrong.

Versions:

django-debug-toolbar == 1.8

django == 1.11.1

settings.py

# DEBUG TOOLBAR

if DEBUG:

    def custom_show_toolbar(request):
        """ Only show the debug toolbar to users with the superuser flag. """
        #return request.user.is_superuser
        if request.is_ajax():
            return False
        return True

    MIDDLEWARE += (
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    )
    INSTALLED_APPS += (
        'debug_toolbar',
    )
    INTERNAL_IPS = ('127.0.0.1', )
    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
        'SHOW_TOOLBAR_CALLBACK': 'core.settings.custom_show_toolbar',
        'HIDE_DJANGO_SQL': True,
        'TAG': 'body',
        'SHOW_TEMPLATE_CONTEXT': True,
        'ENABLE_STACKTRACES': True,
    }

urls.py

urlpatterns = [
    url(r'^$', core_views.home, name='home'),
    #url(r'^login/$', auth_views.login, name='login'),
    #url(r'^logout/$', auth_views.logout, name='logout'),
    #url(r'^oauth/', include('social_django.urls', namespace='social')),
    url(r'^admin/', admin.site.urls),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

Screenshot

Body:
The problem is your custom_show_toolbar method. You are explicitly disabling the toolbar for ajax requests. Since the debug toolbar loads the panel using ajax requests, you get a 404.

def custom_show_toolbar(request):
    ...
    if request.is_ajax():
        return False
    return True


问:
Selenium Webdriver - The entered text is vanished when jumping to the next field
I am trying to enter the text and ensure it gets saved. In my project, there is no save button, as soon as it entered it gets saved. Only few fields that cracks me when entering the text.

Note: I'm using the latest version of Chrome and passing the numeric values as text.

I referred to below pages and updated my code accordingly, then also this issue persists:

Selenium Webdriver: Entering text into text field

Selenium send_keys doesn't work if input type="number"

Below is the code that I used,

```<code> public void EnterValuesByIndex(String locator, String locatorValue, String text, int indexvalue) throws InterruptedException
      {
        WebElement element = null;

        if (locator.equalsIgnoreCase("cssSelector")) {
          element = (WebElement)driver.findElements(By.cssSelector(locatorValue)).get(indexvalue - 1);

        } else if (locator.equalsIgnoreCase("xpath")) {
          element = (WebElement)driver.findElements(By.xpath(locatorValue)).get(indexvalue - 1);

        } else if (locator.equalsIgnoreCase("id")) {
          element = (WebElement)driver.findElements(By.id(locatorValue)).get(indexvalue - 1);
        }
        //element.clear();
        element.sendKeys(text);
        Thread.sleep(2000);
        element.sendKeys(Keys.ENTER);
        System.out.println("Enter key is pressed");
      }
</code>```

Below code also used to enter character by character, same issue persists,

```<code>public void EnterTextbyChar(String locator, String locatorValue, String text, int indexvalue) throws InterruptedException
        {
            String value = text;
            WebElement element = null;

            if (locator.equalsIgnoreCase("cssSelector")) {
            element = (WebElement)driver.findElements(By.cssSelector(locatorValue)).get(indexvalue - 1);
            } else if (locator.equalsIgnoreCase("xpath")) {
                element = (WebElement)driver.findElements(By.xpath(locatorValue)).get(indexvalue - 1);

            } else if (locator.equalsIgnoreCase("id")){
              element = (WebElement)driver.findElements(By.id(locatorValue)).get(indexvalue - 1);               }
            element.clear();
            for (int i = 0; i < value.length(); i++)
            {
              char c = value.charAt(i);
              String s = new StringBuilder().append(c).toString();
              element.sendKeys(s);
              element.sendKeys(Keys.RETURN);
              element.click();
              Thread.sleep(2000);
              System.out.println("Return key is pressed in EnterTextByChar method");
              System.out.println(c);
             }
         }
</code>```

答:
Finally a solution found. After entering the text, sending the upwards key that worked perfectly.</p>

```<code>    element.sendKeys(text);
    element.sendKeys(Keys.UP);
</code>```

Body:
I am trying to enter the text and ensure it gets saved. In my project, there is no save button, as soon as it entered it gets saved. Only few fields that cracks me when entering the text.

Note: I'm using the latest version of Chrome and passing the numeric values as text.

I referred to below pages and updated my code accordingly, then also this issue persists:

Selenium Webdriver: Entering text into text field

Selenium send_keys doesn't work if input type="number"

Below is the code that I used,

 public void EnterValuesByIndex(String locator, String locatorValue, String text, int indexvalue) throws InterruptedException
      {
        WebElement element = null;

        if (locator.equalsIgnoreCase("cssSelector")) {
          element = (WebElement)driver.findElements(By.cssSelector(locatorValue)).get(indexvalue - 1);

        } else if (locator.equalsIgnoreCase("xpath")) {
          element = (WebElement)driver.findElements(By.xpath(locatorValue)).get(indexvalue - 1);

        } else if (locator.equalsIgnoreCase("id")) {
          element = (WebElement)driver.findElements(By.id(locatorValue)).get(indexvalue - 1);
        }
        //element.clear();
        element.sendKeys(text);
        Thread.sleep(2000);
        element.sendKeys(Keys.ENTER);
        System.out.println("Enter key is pressed");
      }

Below code also used to enter character by character, same issue persists,

public void EnterTextbyChar(String locator, String locatorValue, String text, int indexvalue) throws InterruptedException
        {
            String value = text;
            WebElement element = null;

            if (locator.equalsIgnoreCase("cssSelector")) {
            element = (WebElement)driver.findElements(By.cssSelector(locatorValue)).get(indexvalue - 1);
            } else if (locator.equalsIgnoreCase("xpath")) {
                element = (WebElement)driver.findElements(By.xpath(locatorValue)).get(indexvalue - 1);

            } else if (locator.equalsIgnoreCase("id")){
              element = (WebElement)driver.findElements(By.id(locatorValue)).get(indexvalue - 1);               }
            element.clear();
            for (int i = 0; i < value.length(); i++)
            {
              char c = value.charAt(i);
              String s = new StringBuilder().append(c).toString();
              element.sendKeys(s);
              element.sendKeys(Keys.RETURN);
              element.click();
              Thread.sleep(2000);
              System.out.println("Return key is pressed in EnterTextByChar method");
              System.out.println(c);
             }
         }

Body:
Finally a solution found. After entering the text, sending the upwards key that worked perfectly.

    element.sendKeys(text);
    element.sendKeys(Keys.UP);


问:
Temporarily Storing Decrypted Data in Memory
Background

I am working on a simple application in native C++11 which uses Microsoft's Cassablanca REST framework to communicate with various remote endpoints.  To do this, I have to cryptographically sign the various requests with some secret provided by whichever API is being targeted.  By linking Cassablanca I already have OpenSSL so the actual crypto is reasonably straight-forward.

Now, the tricky part is how to store the secrets themselves.  My plan is to AES encrypt a JSON file with all of the goodies using a symmetric key from the user's brain (read: password) so that it does not have to be stored on disk.

The Question

What is a secure way to store the decrypted secrets in memory during the execution of the application?  This is not another "how do I store secrets on disk so the user doesn't have to do anything" question.

My big concern is that someone will be able to examine my application's memory externally and find the appropriate regions containing the goodies.  I know Windows provides credstores and protected memory however I am on Linux and would prefer a platform-agnostic solution if possible.  There is also a significant chance that this will be deployed to a VM cluster so protected memory may only buy limited assurances (though, still better than nothing).

Finally, I know that any cryptographic system can be overcome with sufficiently large amount of money+time or a large enough rubber hose.  That being said, I would still like to be as secure as possible as an exercise in Good™ coding practice.

My constraints are:

Must be able to access secrets for signing the various requests quickly.  Milliseconds count here but I am willing to accept a slowdown if security is truly improved.

I would prefer a minimum of external libraries and to use native C++11 where possible.  I feel like this should be doable with what I already have (Cassablanca which requires OpenSSL, Boost, libcrypt).

Finally, it should be able to accommodate a reasonably large number of secrets / requests.  My application domain is basically a giant parallelization problem and scalability is key.

What I already know to do:

Never ever store sensitive material on disk unencrypted.  This includes usage of disk-backed containers and whatnot.

An old but useful trick: attach a debugger instance to prevent remote debugging from external process.

Build without debug symbols and strip final executable.

Minimize in-application access to data to only the parts which truly need it.

Destroy sensitive information as soon as it is no longer needed (Ex. NULL out user password as soon as decryption is finished, etc).

Do not trust anybody to sanitize memory for me.  Manually overwrite areas with NULL / garbage.

Similar Questions

Storing sensitive data in memory

PHP specific and advises writing something not in PHP to store the credentials...which is exactly the problem I am trying to solve.

Store password temporarily in memory

Android application lifecycle specific.  I already know the storage duration for my secrets will be the lifetime of the application.

答:
LibSodium is the library you need: https://download.libsodium.org/doc/helpers/memory_management.html

Don't know if this will be available on every possible platform, but in most cases this should help you with your objectives.


问:
"Driver is not defined" Python/Selenium
I want to use Selenium on Python but I have an alert message:

driver-webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe") NameError: name 'driver' is not defined

I have installed the Chrome Driver, what else must I do ?

答: chromedriver.exe must be in python path, probably now python expects that driver exists in "D:\Selenium\Chrome\chromedriver.exe" but it does not. You could try add chromedriver.exe path to windows enviroment path variable, or add path to os.path in python, or add driver to folder of python script.</p>

Title: "Driver is not defined" Python/Selenium


问:
Unable to download Library using cocoaPods
I am new in swift programming . I  am trying to download libraries for the project . I have installed  cocoa pods : sudo gem install cocoa pods, created pod file with all libraries which I need : pod 'GoogleMaps'.  After pod install I got an error:

```<code> Unable to satisfy the following requirements:

 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps (= 2.3.1)` required by `Podfile.lock`

 Specs satisfying the `GoogleMaps, GoogleMaps (= 2.3.1)` dependency
 were found, but they required a higher minimum deployment target.

 [!] Automatically assigning platform ios with version 7.0 on target
  Taxi for rider because no platform was specified. Please specify a
 platform    for this target in your Podfile. See
 `https://guides.cocoapods.org/syntax/podfile.html#platform`.
</code>```

My pod file:

```<code>  # Uncomment the next line to define a global platform for your
  project
  # platform :ios, '9.0'

  target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to
  use dynamic frameworks
  use_frameworks!

  # Pods for Taxi for rider
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'

  end
</code>```

答:
You should define a platform for your project in your Podfile. Append this to the beginning of your Podfile:

```<code>platform :<ios, macos, tvos etc.>, '<version of the OS>'
</code>```

Example:

```<code>platform :ios, '9.0'
</code>```

Body:
I am new in swift programming . I  am trying to download libraries for the project . I have installed  cocoa pods : sudo gem install cocoa pods, created pod file with all libraries which I need : pod 'GoogleMaps'.  After pod install I got an error:

 Unable to satisfy the following requirements:

 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps (= 2.3.1)` required by `Podfile.lock`

 Specs satisfying the `GoogleMaps, GoogleMaps (= 2.3.1)` dependency
 were found, but they required a higher minimum deployment target.

 [!] Automatically assigning platform ios with version 7.0 on target
  Taxi for rider because no platform was specified. Please specify a
 platform    for this target in your Podfile. See
 `https://guides.cocoapods.org/syntax/podfile.html#platform`.

My pod file:

  # Uncomment the next line to define a global platform for your
  project
  # platform :ios, '9.0'

  target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to
  use dynamic frameworks
  use_frameworks!

  # Pods for Taxi for rider
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'

  end

Body:
You should define a platform for your project in your Podfile. Append this to the beginning of your Podfile:

platform :<ios, macos, tvos etc.>, '<version of the OS>'

Example:

platform :ios, '9.0'


问:
ConstraintLayout margins not working
Using the xml below the marginTop is getting ignored if the view's visibility that I'm constrained to is gone.

This happens with the latest layout lib version at this time com.android.support.constraint:constraint-layout:1.0.0-beta4

Example:

tvMessage and ivCommentImage are visible - the 16dp top margin on llLeftActions and llRightActions is working fine. If the ivCommentImage is gone the margin is ignored.

```<code><android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp">

<!-- some more views here -->

    <TextView
        android:id="@+id/tvMessage"
        style="@style/SocialFeed.Description"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ivProfile"
        app:layout_goneMarginTop="0dp"
        tools:text="@string/lorem_ipsum_140chars"/>

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/ivCommentImage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:adjustViewBounds="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvMessage"
        app:layout_goneMarginTop="0dp"
        />

    <android.support.constraint.Guideline
        android:id="@+id/gCenter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"/>

    <LinearLayout
        android:id="@+id/llLeftActions"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center_vertical|left"
        android:orientation="horizontal"
        app:layout_constraintLeft_toLeftOf="@+id/tvMessage"
        app:layout_constraintRight_toLeftOf="@+id/gCenter"
        app:layout_constraintTop_toBottomOf="@+id/ivCommentImage"
        app:layout_goneMarginTop="0dp"
        />

    <LinearLayout
        android:id="@+id/llRightActions"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center_vertical|right"
        android:orientation="horizontal"
        app:layout_constraintLeft_toLeftOf="@+id/gCenter"
        app:layout_constraintRight_toRightOf="@+id/tvMessage"
        app:layout_constraintTop_toBottomOf="@+id/ivCommentImage"
        app:layout_goneMarginTop="0dp"/>

</android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>
</code>```

答:
```<code><TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Available chats"
    tools:layout_editor_absoluteX="1dp"
    tools:layout_editor_absoluteY="1dp" />

<ListView
    android:id="@+id/listChats"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@+id/textView"/>
</code>```

Please notice the last line, adding constraints around the edges makes the constraint work.

You can also use the design view in Studio, and drag and drop the constraints between objects.

Title: ConstraintLayout margins not working

Body:
Using the xml below the marginTop is getting ignored if the view's visibility that I'm constrained to is gone.

This happens with the latest layout lib version at this time com.android.support.constraint:constraint-layout:1.0.0-beta4

Example:

tvMessage and ivCommentImage are visible - the 16dp top margin on llLeftActions and llRightActions is working fine. If the ivCommentImage is gone the margin is ignored.

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp">

    <TextView
        android:id="@+id/tvMessage"
        style="@style/SocialFeed.Description"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ivProfile"
        app:layout_goneMarginTop="0dp"
        tools:text="@string/lorem_ipsum_140chars"/>

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/ivCommentImage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:adjustViewBounds="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvMessage"
        app:layout_goneMarginTop="0dp"
        />

    <android.support.constraint.Guideline
        android:id="@+id/gCenter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"/>

    <LinearLayout
        android:id="@+id/llLeftActions"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center_vertical|left"
        android:orientation="horizontal"
        app:layout_constraintLeft_toLeftOf="@+id/tvMessage"
        app:layout_constraintRight_toLeftOf="@+id/gCenter"
        app:layout_constraintTop_toBottomOf="@+id/ivCommentImage"
        app:layout_goneMarginTop="0dp"
        />

    <LinearLayout
        android:id="@+id/llRightActions"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center_vertical|right"
        android:orientation="horizontal"
        app:layout_constraintLeft_toLeftOf="@+id/gCenter"
        app:layout_constraintRight_toRightOf="@+id/tvMessage"
        app:layout_constraintTop_toBottomOf="@+id/ivCommentImage"
        app:layout_goneMarginTop="0dp"/>

</android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>

Body:
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Available chats"
    tools:layout_editor_absoluteX="1dp"
    tools:layout_editor_absoluteY="1dp" />

<ListView
    android:id="@+id/listChats"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@+id/textView"/>

Please notice the last line, adding constraints around the edges makes the constraint work.

You can also use the design view in Studio, and drag and drop the constraints between objects.


问:
How to monitor my network connection with Java?
Is there any sample code that can report the url that my PC is connecting with Java?

While I use my browser to connect to different sites and watch video online, it should capture the urls. Is it doable in Java?

I don't want detailed traffic, just record the urls.

答:
The fastest way is probably going to be to capture the output of the command-line tshark program (for at least windows and linux). This works on my linux box:

```<code>sudo tshark -f 'port 80' -R 'http' -V | grep -A 1 '^Hypertext Transfer Protocol'
</code>```

And produces output like:

```<code>Running as user "root" and group "root". This could be dangerous.
Capturing on eth0
Hypertext Transfer Protocol
    GET /questions/4494294/r-gplots-barplots-how-to-fix-bar-width-independent-of-paper-setting HTTP/1.1\r\n
--
Hypertext Transfer Protocol
    HTTP/1.1 200 OK\r\n
--
Hypertext Transfer Protocol
    GET /posts/4494294/ivc/086e HTTP/1.1\r\n
--
Hypertext Transfer Protocol
    HTTP/1.1 204 No Content\r\n
--
Hypertext Transfer Protocol
    [truncated] GET /__utm.gif?utmwv=4.8.6&utmn=20455052&utmhn=stackoverflow.com&utmcs=UTF-8&utmsr=1600x1200&utmsc=24-bit&utmul=en-us&utmje=1&utmfl=10.1%20r102&utmdt=graph%20-%20R%3A%20gplots%2C%20barplots%3A%20how%20to%20fix%20bar%20width%20i
--
Hypertext Transfer Protocol
    HTTP/1.1 200 OK\r\n
--
</code>```

You should get something similar for Windows. Experiment. How you get the output of tshark into java is up to you.

If you want an all-java solution, how about http://jnetpcap.com/ ?

You're going to have to write (or use a library that provides) some platform specific JNI code.

libpcap/WinPcap that jNetPcap uses provides this reliably on at least Windows and Linux from my experience. I have experience with libpcap/WinPcap but not with jNetPcap.

tshark also uses libpcap/WinPcap actually.

Either way, you're going to see very many false positives. Opening a HTML page requires getting many, many images, style sheets, javascript libraries etc. The snippet above is from opening a stackoverflow.com page.

Body:
The fastest way is probably going to be to capture the output of the command-line tshark program (for at least windows and linux). This works on my linux box:

sudo tshark -f 'port 80' -R 'http' -V | grep -A 1 '^Hypertext Transfer Protocol'

And produces output like:

Running as user "root" and group "root". This could be dangerous.
Capturing on eth0
Hypertext Transfer Protocol
    GET /questions/4494294/r-gplots-barplots-how-to-fix-bar-width-independent-of-paper-setting HTTP/1.1\r\n
--
Hypertext Transfer Protocol
    HTTP/1.1 200 OK\r\n
--
Hypertext Transfer Protocol
    GET /posts/4494294/ivc/086e HTTP/1.1\r\n
--
Hypertext Transfer Protocol
    HTTP/1.1 204 No Content\r\n
--
Hypertext Transfer Protocol
    [truncated] GET /__utm.gif?utmwv=4.8.6&utmn=20455052&utmhn=stackoverflow.com&utmcs=UTF-8&utmsr=1600x1200&utmsc=24-bit&utmul=en-us&utmje=1&utmfl=10.1%20r102&utmdt=graph%20-%20R%3A%20gplots%2C%20barplots%3A%20how%20to%20fix%20bar%20width%20i
--
Hypertext Transfer Protocol
    HTTP/1.1 200 OK\r\n
--

You should get something similar for Windows. Experiment. How you get the output of tshark into java is up to you.

If you want an all-java solution, how about http://jnetpcap.com/ ?

You're going to have to write (or use a library that provides) some platform specific JNI code.

libpcap/WinPcap that jNetPcap uses provides this reliably on at least Windows and Linux from my experience. I have experience with libpcap/WinPcap but not with jNetPcap.

tshark also uses libpcap/WinPcap actually.

Either way, you're going to see very many false positives. Opening a HTML page requires getting many, many images, style sheets, javascript libraries etc. The snippet above is from opening a stackoverflow.com page.


问:
How to connect ImageJ to python?
I am using Python to design a software, and the image processing is one of the steps. I am using ImageJ to realize this.

Since there is a Jython interpreter within ImageJ, which can be opened within ImageJ software, there must be a way to connect ImageJ to Python and call all the functions within Python.

I wonder how I can do that to finish all the processing in Python rather than open the interpreter in ImageJ?

答:
The imglib2-imglyb project allows to access numpy arrays from Java with ImgLib2 and vice versa.

Some illustrating examples can be found on imglyb-examples.

Title: How to connect ImageJ to python?


问:
Redim array after it is filled
Before filling my array I don't know how big it's going to get, but at a certain point (after all data has been inserted) I want to redim the array so there are no empty values in the end of the array. If I dim it as

```<code>valuesForSix() As Double
</code>```

I cannot add values with

```<code>valuesForSix(0) = 9.654
</code>```

Can somebody help me?

答:
ReDim it!

```<code>Dim valuesForSix() As Double
ReDim valuesForSix(1) As Double
valuesForSix(0) = 9.654
valuesForSix(1) = 10.25
ReDim Preserve valuesForSix(10) As Double
Debug.Print valuesForSix(0)
Debug.Print valuesForSix(1)
</code>```

The "Preserve" Keyword means that existing data is kept if the array size is increased.

Title: Redim array after it is filled

Body:
Before filling my array I don't know how big it's going to get, but at a certain point (after all data has been inserted) I want to redim the array so there are no empty values in the end of the array. If I dim it as

valuesForSix() As Double

I cannot add values with

valuesForSix(0) = 9.654

Can somebody help me?

Body:
ReDim it!

Dim valuesForSix() As Double
ReDim valuesForSix(1) As Double
valuesForSix(0) = 9.654
valuesForSix(1) = 10.25
ReDim Preserve valuesForSix(10) As Double
Debug.Print valuesForSix(0)
Debug.Print valuesForSix(1)

The "Preserve" Keyword means that existing data is kept if the array size is increased.


问:
Remove field from redux store
Is there a way to unset/remove a variable set with change method?
In my code I programmatically set a field this way

```<code>this.props.change('extraBedChildrenNum', 1);
</code>```

but I would like to unset this field so it is removed from the store. Any idea how to do this?

答:
There is not action creator to remove a field from a form provided to the decorated for component as a prop, but there is one exported by redux-form called unregisterField.

So you should be able to do something like this:

```<code>store.dispatch(unregisterField('MyFormName', 'extraBedChildrenNum'))
</code>```

Hope this helps!

Title: Remove field from redux store

Body:
Is there a way to unset/remove a variable set with change method?
In my code I programmatically set a field this way

this.props.change('extraBedChildrenNum', 1);

but I would like to unset this field so it is removed from the store. Any idea how to do this?

Body:
There is not action creator to remove a field from a form provided to the decorated for component as a prop, but there is one exported by redux-form called unregisterField.

So you should be able to do something like this:

store.dispatch(unregisterField('MyFormName', 'extraBedChildrenNum'))

Hope this helps!


问:
Get a list of duplicates from list based on properties comparison
I have a List<Demo>

```<code>public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}
</code>```

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

```<code>List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});
</code>```

and then i am doing:

```<code>var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();
</code>```

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.

答:
Below code can help you ,

List duplicates = demo.GroupBy(grp => new { grp.Name, grp.Title }).SelectMany(selm => selm.Skip(1)).Distinct().ToList();

It is working fine as per your expected answer.

Body:
I have a List<Demo>

public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});

and then i am doing:

var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.