问:
ngx-bootstrap ProgressBar - use of template is depricated
The latest version of ngx-bootstrap still returns the ProgressBar component using the depricated 'template' element. This gives warnings in the console. But according to the source code in GitHub, the component html uses 'ng-template'. How is this not getting carried over into the latest release? Or is this an ongoing bug?

Regards
JD

答: For Angular 4+, use ngx-bootstrap@next - its latest version is 2.0.0-beta.8</p>


来源: stackexchange

问:
How to redirect to url within same context
I have /logout action, that should redirect to /login. /login renders template, where I read flash message from context. This works, but url in browser is still remains "/logout":

```<code>router.get("/logout").handler((ctx) => {
  if (ctx.user()!=null) {
    ctx.clearUser()
    //flash message
    ctx.put("msg", "Logout succeed")
  }
  ctx.reroute("/login")
})
</code>```

What I want, but url should be "/login":

Better to use(?):

```<code>ctx.response.putHeader("location", "/login").setStatusCode(302).end()
</code>```

But there is different context. So I haven't flash message.

How to redirect to /login within same context?

Upd.
Question related to this issue

答:
In order to work with flash messages you should add a cookie to the redirect with the content:

```<code>// this makes the message available to the client
ctx
  .addCookie(Cookie.cookie("flashMessage", "Logout succeed"));
// configure where to redirect
ctx.response()
  .putHeader("location", "/login");
// perform the redirect
ctx.end(302);
</code>```

Then on the client side you need a bit of JavaScript to read the message and
perform the display as you wish. Since there is no simple way to read cookies on the browser if you're using jQuery with the cookie plugin you can do something like:

```<code>$.fn.flashMessage = function (options) {
    var target = this;
    options = $.extend({}, options, { timeout: 3000 });
    if (!options.message) {
        options.message = getFlashMessageFromCookie();
        deleteFlashMessageCookie();
    }
    if (options.message) {
        if (typeof options.message === "string") {
            target.html("<span>" + options.message + "</span>");
        } else {
            target.empty().append(options.message);
        }
    }

    if (target.children().length === 0) return;

    target.fadeIn().one("click", function () {
        $(this).fadeOut();
    });

    if (options.timeout > 0) {
        setTimeout(function () { target.fadeOut(); }, options.timeout);
    }

    return this;

    function getFlashMessageFromCookie() {
        return $.cookie("FlashMessage");
    }

    function deleteFlashMessageCookie() {
        $.cookie("FlashMessage", null, { path: '/' });
    }
};
</code>```

And add a placeholder in your HTML like:

```<code><div id="flash-message"></div>
</code>```

And trigger it like:

```<code>$(function() {
  $("#flash-message").flashMessage();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have /logout action, that should redirect to /login. /login renders template, where I read flash message from context. This works, but url in browser is still remains "/logout":

router.get("/logout").handler((ctx) => {
  if (ctx.user()!=null) {
    ctx.clearUser()
    //flash message
    ctx.put("msg", "Logout succeed")
  }
  ctx.reroute("/login")
})

What I want, but url should be "/login":

Better to use(?):

ctx.response.putHeader("location", "/login").setStatusCode(302).end()

But there is different context. So I haven't flash message.

How to redirect to /login within same context?

Upd.
Question related to this issue

Body:
In order to work with flash messages you should add a cookie to the redirect with the content:

// this makes the message available to the client
ctx
  .addCookie(Cookie.cookie("flashMessage", "Logout succeed"));
// configure where to redirect
ctx.response()
  .putHeader("location", "/login");
// perform the redirect
ctx.end(302);

Then on the client side you need a bit of JavaScript to read the message and
perform the display as you wish. Since there is no simple way to read cookies on the browser if you're using jQuery with the cookie plugin you can do something like:

$.fn.flashMessage = function (options) {
    var target = this;
    options = $.extend({}, options, { timeout: 3000 });
    if (!options.message) {
        options.message = getFlashMessageFromCookie();
        deleteFlashMessageCookie();
    }
    if (options.message) {
        if (typeof options.message === "string") {
            target.html("<span>" + options.message + "</span>");
        } else {
            target.empty().append(options.message);
        }
    }

    if (target.children().length === 0) return;

    target.fadeIn().one("click", function () {
        $(this).fadeOut();
    });

    if (options.timeout > 0) {
        setTimeout(function () { target.fadeOut(); }, options.timeout);
    }

    return this;

    function getFlashMessageFromCookie() {
        return $.cookie("FlashMessage");
    }

    function deleteFlashMessageCookie() {
        $.cookie("FlashMessage", null, { path: '/' });
    }
};

And add a placeholder in your HTML like:

<div id="flash-message"></div>

And trigger it like:

$(function() {
  $("#flash-message").flashMessage();
});


问:
Prevent stretching of an image while keeping dimensions
Is there a way to prevent the stretching of an image, to crop it somehow but keep the dimensions..?

img {
  width: 90px;
  height: 120px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://i.pinimg.com/736x/d4/c3/dc/d4c3dc946ae1e087d24def574215e266--image-search-google-search.jpg" alt=""></code>```

答:
Instead of using width and height, use max-width and max-height.

```<code>img {
  max-width:90px;
  max-height:120px;
}
</code>```

DEMO

Body:
Instead of using width and height, use max-width and max-height.

img {
  max-width:90px;
  max-height:120px;
}

DEMO


问:
Oracle SQL Count Grouping by without repeating records in previous days
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

```<code>DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1
</code>```

RESULTS

```<code>DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1
</code>```

Thanks a lot for your help

答:
Here is the query with LAG. The idea is to see whether there is an older entry for a wo and only count it in case there is none.

```<code>select day, count(case when prev_day is null then 1 end) as wos, sum(labor) as labor
from
(
  select mytable.*, lag(day) over (partition by wo order by day) as prev_day
  from mytable
)
group by day
order by day;
</code>```

(In case there can be multiple entries per wo and day, you'd have to alter the query slightly. One way would be: partition by wo order by day, rowid.)

Body:
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1

RESULTS

DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1

Thanks a lot for your help

Body:
Here is the query with LAG. The idea is to see whether there is an older entry for a wo and only count it in case there is none.

select day, count(case when prev_day is null then 1 end) as wos, sum(labor) as labor
from
(
  select mytable.*, lag(day) over (partition by wo order by day) as prev_day
  from mytable
)
group by day
order by day;

(In case there can be multiple entries per wo and day, you'd have to alter the query slightly. One way would be: partition by wo order by day, rowid.)


问:
Regular expression string search in Java
I know this can be done in many ways but im curious as to what the regex would be to pick out all strings not containing a particular substring, say GDA from
strings like GADSA, GDSARTCC, , THGDAERY. </p>

答:
Give this a shot:</p>

```<code>java.util.regex.Pattern p = java.util.regex.Pattern.compile("(?!\\w*GDA\\w*)\\b\\w+\\b");
java.util.regex.Matcher m = p.matcher("GADSA, GDSARTCC, , THGDAERY");
while (m.find()) {
    System.out.println("Found: " + m.group());
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Give this a shot:

java.util.regex.Pattern p = java.util.regex.Pattern.compile("(?!\\w*GDA\\w*)\\b\\w+\\b");
java.util.regex.Matcher m = p.matcher("GADSA, GDSARTCC, , THGDAERY");
while (m.find()) {
    System.out.println("Found: " + m.group());
}


问:
PHP Display Values from Object within an Array Based on Key
I have the following array which contains both objects and arrays. How do I get only the specific values (for each object)  based on their keys?
I've tested and the array is displaying (see below) but I cannot isolate the 'name" value as needed.

I have tried the following code to get the name value:

```<code>case 'field_prgm_housing' :
$node = 'field_color';
$tids =  field_get_items('node', $node, $key, $node->language);
$terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));
$nameonly = $terms->[0]->name[0];
return = $nameonly;
break;
Colors (Array, 2 elements)
    12 (Object) stdClass
      tid (String, 2 characters ) 12
      vid (String, 1 characters ) 3
      name (String, 9 characters ) Blue
      description (String, 0 characters )
      format (String, 13 characters ) filtered_html
      weight (String, 1 characters ) 0
      vocabulary_machine_name (String, 15 characters ) colors
      rdf_mapping (Array, 5 elements)
      path (Array, 1 element)
    13 (Object) stdClass
      tid (String, 2 characters ) 13
      vid (String, 1 characters ) 3
      name (String, 8 characters ) Green
      description (String, 0 characters )
      format (String, 13 characters ) filtered_html
      weight (String, 1 characters ) 0
      vocabulary_machine_name (String, 15 characters ) colors
      rdf_mapping (Array, 5 elements)
      path (Array, 1 element)
</code>```

答:
```<code>Try this

    $node = 'field_color';
    $tids =  field_get_items('node', $node, $key, $node->language);
    $terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));

    //loop all the values and get the require value
   $name = array();
    foreach($terms as $term){
          $name[] = $term->name;
    }
    return $name;
</code>```

Body:
I have the following array which contains both objects and arrays. How do I get only the specific values (for each object)  based on their keys?
I've tested and the array is displaying (see below) but I cannot isolate the 'name" value as needed.

I have tried the following code to get the name value:

case 'field_prgm_housing' :
$node = 'field_color';
$tids =  field_get_items('node', $node, $key, $node->language);
$terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));
$nameonly = $terms->[0]->name[0];
return = $nameonly;
break;
Colors (Array, 2 elements)
    12 (Object) stdClass
      tid (String, 2 characters ) 12
      vid (String, 1 characters ) 3
      name (String, 9 characters ) Blue
      description (String, 0 characters )
      format (String, 13 characters ) filtered_html
      weight (String, 1 characters ) 0
      vocabulary_machine_name (String, 15 characters ) colors
      rdf_mapping (Array, 5 elements)
      path (Array, 1 element)
    13 (Object) stdClass
      tid (String, 2 characters ) 13
      vid (String, 1 characters ) 3
      name (String, 8 characters ) Green
      description (String, 0 characters )
      format (String, 13 characters ) filtered_html
      weight (String, 1 characters ) 0
      vocabulary_machine_name (String, 15 characters ) colors
      rdf_mapping (Array, 5 elements)
      path (Array, 1 element)


问:
join function only echoing 1 product of the database
I made a model function so it will echo the products that belong to the profile user I clicked on, the thing is only the first product of that user gets echoed. For example I have an account that uploaded a total of 7 products and the function only shows the first product on the page..

This are the model functions:

```<code>function getdata_aangeboden($user_id){
  $this->db->select("users.*,products.*");
  $this->db->from('users');
  $this->db->join('products','products.user_id = users.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

    // Gets a list of multiple users.
 function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }
</code>```

Controller function:

```<code><?php foreach($products as $product) { ?>
  <div class="main-gifts">
      <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
        <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">
        </a>
        <div class="products_discription">
            <h3><?php echo $product->product_naam; ?></h3>
            <div class="ophaal_plaats">
                <p>Plaats: <?php  echo $product->ophaal_plaats; ?></p>
            </div>
            <div class="aangeboden_door">
            <p> <?php
                    foreach($userdetail_list as $row){ ?>
              <tr>
                  <td><?php echo $row->voornaam;?></td>
               </tr>
                    <?php } ?></p>
          </div>
          <div class="status">
          </div>
      </div>
        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>"><input type="button" class="btn btn-default cb" value="Cadeau bewerken"></input> </a>
  </div>
 <?php } ?>
</code>```

Can someone explain to me why it only shows 1 product and not all the products that belong to the same user_id?
thanks

When I print $products:

```<code>} ?> Array ( [0] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 85 [product_naam] => HIHIHIHI [product_beschrijving] => [ophaal_plaats] => ALLOVER [product_foto] => new_f5cea9c914751e0ad0048800ffec3d05.jpg [product_foto_thumb] => thumb_f5cea9c914751e0ad0048800ffec3d05.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 2 ) [1] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 86 [product_naam] => HUHUUHU [product_beschrijving] => [ophaal_plaats] => NOWHERE [product_foto] => new_ba2430d2b531bc421f27b5f14667cffb.jpg [product_foto_thumb] => thumb_ba2430d2b531bc421f27b5f14667cffb.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 4 ) [2] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 87 [product_naam] => HOHOHO [product_beschrijving] => [ophaal_plaats] => NOIDEA [product_foto] => new_e1dfb9a860859ff882d13435e796578c.jpg [product_foto_thumb] => thumb_e1dfb9a860859ff882d13435e796578c.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 7 ) [3] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 88 [product_naam] => HEHEHE [product_beschrijving] => [ophaal_plaats] => Korea [product_foto] => new_c080495685ed05ab5d4f8a7dcdb8e668.jpg [product_foto_thumb] => thumb_c080495685ed05ab5d4f8a7dcdb8e668.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 8 ) [4] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 89 [product_naam] => ugilh [product_beschrijving] => hjgluhsfkh;sidh fihsdiuhfluisdhauighsudiahguivhadsuihudisahluihvsaduihvluidsahuihv [ophaal_plaats] => Amsterdam [product_foto] => new_c6dd9fa0dc0be0830ed43940b5907115.jpg [product_foto_thumb] => thumb_c6dd9fa0dc0be0830ed43940b5907115.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 1 ) [5] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 93 [product_naam] => 11111 [product_beschrijving] => frfewefwe [ophaal_plaats] => 1111 [product_foto] => new_14de53777d648dcbe31dea26fa031ced.jpg [product_foto_thumb] => thumb_14de53777d648dcbe31dea26fa031ced.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 2 ) [6] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 94 [product_naam] => hiu;ij [product_beschrijving] => hk;h uihucuhsducuisdhuvsdphvjuisjhuvsudih [ophaal_plaats] => Amsterdam [product_foto] => new_f68becfc0741d3a2300f49ed5bcf58a5.jpg [product_foto_thumb] => thumb_f68becfc0741d3a2300f49ed5bcf58a5.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 5 ) )
</code>```

答:
I hope you should declare foreach loop correctly.</p>

```<code><?php foreach($products as $product) {
     // print here the product info
}
?>
</code>```

Body:
I made a model function so it will echo the products that belong to the profile user I clicked on, the thing is only the first product of that user gets echoed. For example I have an account that uploaded a total of 7 products and the function only shows the first product on the page..

This are the model functions:

function getdata_aangeboden($user_id){
  $this->db->select("users.*,products.*");
  $this->db->from('users');
  $this->db->join('products','products.user_id = users.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

    // Gets a list of multiple users.
 function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

Controller function:

<?php foreach($products as $product) { ?>

      <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
        <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">

<?php echo $product->product_naam; ?>

Plaats: <?php  echo $product->ophaal_plaats; ?>

 <?php
                    foreach($userdetail_list as $row){ ?>

                  <?php echo $row->voornaam;?>

                    <?php } ?>

        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>"><input type="button" class="btn btn-default cb" value="Cadeau bewerken"></input>

 <?php } ?>

Can someone explain to me why it only shows 1 product and not all the products that belong to the same user_id?
thanks

When I print $products:

} ?> Array ( [0] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 85 [product_naam] => HIHIHIHI [product_beschrijving] => [ophaal_plaats] => ALLOVER [product_foto] => new_f5cea9c914751e0ad0048800ffec3d05.jpg [product_foto_thumb] => thumb_f5cea9c914751e0ad0048800ffec3d05.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 2 ) [1] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 86 [product_naam] => HUHUUHU [product_beschrijving] => [ophaal_plaats] => NOWHERE [product_foto] => new_ba2430d2b531bc421f27b5f14667cffb.jpg [product_foto_thumb] => thumb_ba2430d2b531bc421f27b5f14667cffb.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 4 ) [2] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 87 [product_naam] => HOHOHO [product_beschrijving] => [ophaal_plaats] => NOIDEA [product_foto] => new_e1dfb9a860859ff882d13435e796578c.jpg [product_foto_thumb] => thumb_e1dfb9a860859ff882d13435e796578c.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 7 ) [3] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 88 [product_naam] => HEHEHE [product_beschrijving] => [ophaal_plaats] => Korea [product_foto] => new_c080495685ed05ab5d4f8a7dcdb8e668.jpg [product_foto_thumb] => thumb_c080495685ed05ab5d4f8a7dcdb8e668.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 8 ) [4] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 89 [product_naam] => ugilh [product_beschrijving] => hjgluhsfkh;sidh fihsdiuhfluisdhauighsudiahguivhadsuihudisahluihvsaduihvluidsahuihv [ophaal_plaats] => Amsterdam [product_foto] => new_c6dd9fa0dc0be0830ed43940b5907115.jpg [product_foto_thumb] => thumb_c6dd9fa0dc0be0830ed43940b5907115.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 1 ) [5] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 93 [product_naam] => 11111 [product_beschrijving] => frfewefwe [ophaal_plaats] => 1111 [product_foto] => new_14de53777d648dcbe31dea26fa031ced.jpg [product_foto_thumb] => thumb_14de53777d648dcbe31dea26fa031ced.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 2 ) [6] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 94 [product_naam] => hiu;ij [product_beschrijving] => hk;h uihucuhsducuisdhuvsdphvjuisjhuvsudih [ophaal_plaats] => Amsterdam [product_foto] => new_f68becfc0741d3a2300f49ed5bcf58a5.jpg [product_foto_thumb] => thumb_f68becfc0741d3a2300f49ed5bcf58a5.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 5 ) )

Body:
I hope you should declare foreach loop correctly.

<?php foreach($products as $product) {
     // print here the product info
}
?>


问:
primeng - Tree - Folders static and not interactive
I'm trying to add primeng Tree to my angular app. I'm using angular 4 (4.0) with webpack.

In webpack, i have added the following:

```<code>'font-awesome/css/font-awesome.css',
'primeng/primeng',
'primeng/resources/themes/omega/theme.css',
'primeng/resources/primeng.min.css',
</code>```

If for example i check the bundled css, it seems like everything is in and working.

I have imported the Tree Menu into my app.module

```<code>import { TreeModule } from "primeng/components/tree/tree";
</code>```

and added it to the imports

```<code>imports: [TreeModule]
</code>```

I'm using lazy loading, so i've added this again to my lazy loaded module.

I'm trying to add the example so in my actual component i've added the following.

```<code>import { TreeNode } from "primeng/primeng";
</code>```

This is my template

```<code><p-tree [value]="files"></p-tree>
</code>```

It shows the following folder structure but if i click on the folder it doesn't expand. It's completely static but i'm guessing that it must be working in some way as it displaying the top level items.

答: Updated all angular packages to 4.4.5 and everything started working</p>

Body:
I'm trying to add primeng Tree to my angular app. I'm using angular 4 (4.0) with webpack.

In webpack, i have added the following:

'font-awesome/css/font-awesome.css',
'primeng/primeng',
'primeng/resources/themes/omega/theme.css',
'primeng/resources/primeng.min.css',

If for example i check the bundled css, it seems like everything is in and working.

I have imported the Tree Menu into my app.module

import { TreeModule } from "primeng/components/tree/tree";

and added it to the imports

imports: [TreeModule]

I'm using lazy loading, so i've added this again to my lazy loaded module.

I'm trying to add the example so in my actual component i've added the following.

import { TreeNode } from "primeng/primeng";

This is my template

It shows the following folder structure but if i click on the folder it doesn't expand. It's completely static but i'm guessing that it must be working in some way as it displaying the top level items.


问:
What are the alternatives for high order component in react?
Coming with php background not sure how to implement a design with reusable code,

the problem:
we are creating a react/redux app with a lot of similar components that share a lot of functionality... I've read about HOC but was wondering if there are another solutions that would help in this situation!?

答:
There is something called function as child components (not sure if that's an official name but anyways)

The basic idea is that react accepts functions as child components, so for example instead of the react redux's connect HOC component you could do something like this

```<code><Connect mapStateToProps={myMapper}>
  {({ users, isLoading })} => {
    //renders the user
}}
</code>```

and the connect implementation is quite simple compared to a HOC.

```<code>render() {
  return this.props.children(
    this.props.mapStateToProps(this.state)
  )
}
</code>```

You can check a pretty interesting video about it here: https://www.youtube.com/watch?v=BcVAq3YFiuc

Body:
There is something called function as child components (not sure if that's an official name but anyways)

The basic idea is that react accepts functions as child components, so for example instead of the react redux's connect HOC component you could do something like this

<Connect mapStateToProps={myMapper}>
  {({ users, isLoading })} => {
    //renders the user
}}

and the connect implementation is quite simple compared to a HOC.

render() {
  return this.props.children(
    this.props.mapStateToProps(this.state)
  )
}

You can check a pretty interesting video about it here: https://www.youtube.com/watch?v=BcVAq3YFiuc


问:
Keytool error java.io.FileNotFoundException(the system cannot find the file specified)

keytool error: java.io.FileNotFoundException: api.sepa.express.crt (The system cannot find the file specified)

I tried various examples which I found in stackoverflow.

```<code>keytool -importcert -file certificate.cer -keystore keystore.jks -alias "Alias"
</code>```

and

```<code>    keytool -import -alias susan
   -file Example.cer -keystore exampleraystore
</code>```

Tried using cmd as admin. I have placed my certificate file in Desktop. When I'm trying to copy in:

C:\Program Files\Java\jdk1.8.0_60\jre\lib\security

It's not accepting the certificate file.

What would be the preferred way to complete this command?

答: Try adding the ssl file using command promt. It worked for me</p>

Body:
keytool error: java.io.FileNotFoundException: api.sepa.express.crt (The system cannot find the file specified)

I tried various examples which I found in stackoverflow.

keytool -importcert -file certificate.cer -keystore keystore.jks -alias "Alias"

and

    keytool -import -alias susan
   -file Example.cer -keystore exampleraystore

Tried using cmd as admin. I have placed my certificate file in Desktop. When I'm trying to copy in:

C:\Program Files\Java\jdk1.8.0_60\jre\lib\security

It's not accepting the certificate file.

What would be the preferred way to complete this command?


问:
Sitemap lastmod date in Javascript
I need to the date format that is shown in <lastmod></lastmod> tags in sitemap.xml. How can I achieve that?

Output like:

```<code><lastmod>2016-01-21EEST18:01:18+03:00</lastmod>
</code>```

Where 'EEST' is probably timezone offset.

I have seen this question and the answers in php:

Google Sitemap Date Format

but don't know how to achieve it in Javascript,

Thanks.

EDIT: the question is not duplicate, since I need the correct time format in JavaScript for this.

答:
The lastmod tag uses YYYY-MM-DDThh:mmTZD format, where TZD is the time zone offset. The W3 date and time format gives you 3 options for how to do the TZD: (Z or +hh:mm or -hh:mm)

This means that in javascript you can just use

```<code>const date = new Date().toISOString();
</code>```

and it'll look like 2017-11-15T11:18:17.266Z, which is correct for a sitemap lastmod.

Title: Sitemap lastmod date in Javascript

Body:
I need to the date format that is shown in <lastmod></lastmod> tags in sitemap.xml. How can I achieve that?

Output like:

<lastmod>2016-01-21EEST18:01:18+03:00</lastmod>

Where 'EEST' is probably timezone offset.

I have seen this question and the answers in php:

Google Sitemap Date Format

but don't know how to achieve it in Javascript,

Thanks.

EDIT: the question is not duplicate, since I need the correct time format in JavaScript for this.

Body:
The lastmod tag uses YYYY-MM-DDThh:mmTZD format, where TZD is the time zone offset. The W3 date and time format gives you 3 options for how to do the TZD: (Z or +hh:mm or -hh:mm)

This means that in javascript you can just use

const date = new Date().toISOString();

and it'll look like 2017-11-15T11:18:17.266Z, which is correct for a sitemap lastmod.


问:
fetch not working in service worker
i tried to use the fetch event in service worker
but he didnt work for me.

```<code>self.addEventListener('activate', function(event) {
  console.log('Activated', event);
  fetch('/embed_testing/notification/main.js').then(response =>
          function () {
              console.log(response)
          });
});

self.addEventListener('fetch', function(event) {
    console.log("heyyyo");
  if (event.request.url === new URL('/', location).href) {
    event.respondWith(
      new Response("<h1>Hello!</h1>", {
        headers: {'Content-Type': 'text/html'}
      })
    )
  }
});
</code>```

any ideas why it is not working ?

答: In case you are testing your app in chrome, try to uncheck flag "bypass for network" in dev tools on the "Application" tab (choose "Service workers" on the left side)</p>

Title: fetch not working in service worker

Body:
i tried to use the fetch event in service worker
but he didnt work for me.

self.addEventListener('activate', function(event) {
  console.log('Activated', event);
  fetch('/embed_testing/notification/main.js').then(response =>
          function () {
              console.log(response)
          });
});

self.addEventListener('fetch', function(event) {
    console.log("heyyyo");
  if (event.request.url === new URL('/', location).href) {
    event.respondWith(
      new Response("
Hello!
", {
        headers: {'Content-Type': 'text/html'}
      })
    )
  }
});

any ideas why it is not working ?


问:
How do you get the number of words in a NSTextStorage/NSString?
So my question is basically how do you get the number of words in a NSTextStorage/NSString?  I don't want the character length but the word length.  Thanks.</p>

答:
If you're on 10.6 or later, the following may be the easiest solution:

```<code>- (NSUInteger)numberOfWordsInString:(NSString *)str {
    __block NSUInteger count = 0;
    [str enumerateSubstringsInRange:NSMakeRange(0, [str length])
                            options:NSStringEnumerationByWords|NSStringEnumerationSubstringNotRequired
                         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        count++;
    }];
    return count;
}
</code>```

If you want to take the current locale into account when doing word-splitting you can also add NSStringEnumerationLocalized to the options.

Body:
If you're on 10.6 or later, the following may be the easiest solution:

- (NSUInteger)numberOfWordsInString:(NSString *)str {
    __block NSUInteger count = 0;
    [str enumerateSubstringsInRange:NSMakeRange(0, [str length])
                            options:NSStringEnumerationByWords|NSStringEnumerationSubstringNotRequired
                         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        count++;
    }];
    return count;
}

If you want to take the current locale into account when doing word-splitting you can also add NSStringEnumerationLocalized to the options.


问:
Relays getting freeze suddenly

Hi all, I'v done a project for a factory which were needing a packing machine,   so I made it with some pneumatic cylinders using arduino, relays, IR sensor.

  I'm attaching my code and a picture how schema looks because  sometimes my   relays are freezing suddenly and they just need to power off then again power on   and its OK.

  Btw; I'm attaching schema only for one relay with all elements, code is for 4

   relays.

  Any idea about this please?

Picture of schema

```<code>int relay1 = 13;
 int relay2 = 12;
 int relay3 = 11;
 int relay4 = 10;

 int sensor1 = 5;
 int sensor2 = 6;
 int sensor3 = 3;
 int sensor4 = 2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(relay1, OUTPUT);
  pinMode(sensor1, INPUT);

  pinMode(relay2, OUTPUT);
  pinMode(sensor2,INPUT);

  pinMode(relay 3, OUTPUT);
  pinMode(sensor3,INPUT);

  pinMode(relay4, OUTPUT);
  pinMode(sensor4,INPUT);
  pinMode(LED_BUILTIN,OUTPUT);
}

void loop() {
  digitalWrite(relay1, LOW);
  delay(2000);
  digitalWrite(relay1, HIGH);
  delay(2000);

  digitalWrite(relay2, LOW);
  delay(2000);
  digitalWrite(relay2, HIGH);
  delay(2000);

  digitalWrite(relay 3, LOW);
  delay(2000);
  digitalWrite(relay3, HIGH);
  delay(2000);

  digitalWrite(relay4, LOW);
  delay(2000);
  digitalWrite(relay4, HIGH);
  delay(2000);

  while(1){
    delay(100);
    if(digitalRead(sensor2) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay1,HIGH);
      delay(350); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No eggs");
      digitalWrite(relay1,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }

    if(digitalRead(sensor1) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay2,HIGH);
      delay(350); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No eggs");
      digitalWrite(relay2,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }

   if(digitalRead(sensor3) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay3,HIGH);
      delay(350); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No egs");
      digitalWrite(relay3 ,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }

   if(digitalRead(sensor4) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay4,HIGH);
      delay(100); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No eggs");
      digitalWrite(relay4 ,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }
 }
</code>```

答:
I design systems with relays operating in production plants. Sticking of the relays is a rare condition, but can occur in certain situations.

Relay Coil Voltage Stability ----
If the relay coil voltage is insufficient then the relays may fail to switch on. I would measure the voltage at coil switch on ensure that the relay coil voltage is stable. For best results I would supply the relay coils from a separately regulated (5 VDC) supply. That ensures that any loading affects of the relay coils on the supply voltage do not cause dropouts on the Arduino supply and stop the program.

Relay Contact Erosion due to inductive loads ----
Relay contacts can become eroded over time, occasionally sticking and eventually welding shut. The damage occurs when switching inductive loads off. The inductive load's energy discharges across the contacts and can generate an arc in the contact gap if the inductively generated voltage is sufficiently high. The plasma then erodes the contacts. A solution is to add a transorb across the contacts that is rated above the normal load voltage (e.g. above 24 VDC). This will absorb the inductive energy harmlessly. Another option is an RC filter. See the relay manufacturer's technical guidelines for more information on this subject.

Some issues that may be present in you system. The details are not apparent from the posted circuit diagram due to absence of some of the circuitry.

Isolation of Earths ----
Ensure that the earth voltages of the Arduino and 24V power are not connected.  Otherwise there may be an Arduino earth voltage spike when you are swuitching on and off the solenoids. This could trip of the Arduino and halt the program. The Arduino power and the 24 VDC power sources should be independent and floating.

Relay Driver Isolation ----
Add optical isolators to the relay driver circuit so that there is at least a 1000 V barrier between the Arduino and the relay driver.

Relay Coil Voltage Suppression ----
Add a reverse polarity diode connected across the coil to absorb the inductive energy when the relay coil discharges. Otherwise that energy may cause damage to the arduino output pin.

Good luck with your system

Title: Relays getting freeze suddenly

Body:
Hi all, I'v done a project for a factory which were needing a packing machine,   so I made it with some pneumatic cylinders using arduino, relays, IR sensor.

  I'm attaching my code and a picture how schema looks because  sometimes my   relays are freezing suddenly and they just need to power off then again power on   and its OK.

  Btw; I'm attaching schema only for one relay with all elements, code is for 4

   relays.

  Any idea about this please?

Picture of schema

int relay1 = 13;
 int relay2 = 12;
 int relay3 = 11;
 int relay4 = 10;

 int sensor1 = 5;
 int sensor2 = 6;
 int sensor3 = 3;
 int sensor4 = 2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(relay1, OUTPUT);
  pinMode(sensor1, INPUT);

  pinMode(relay2, OUTPUT);
  pinMode(sensor2,INPUT);

  pinMode(relay 3, OUTPUT);
  pinMode(sensor3,INPUT);

  pinMode(relay4, OUTPUT);
  pinMode(sensor4,INPUT);
  pinMode(LED_BUILTIN,OUTPUT);
}

void loop() {
  digitalWrite(relay1, LOW);
  delay(2000);
  digitalWrite(relay1, HIGH);
  delay(2000);

  digitalWrite(relay2, LOW);
  delay(2000);
  digitalWrite(relay2, HIGH);
  delay(2000);

  digitalWrite(relay 3, LOW);
  delay(2000);
  digitalWrite(relay3, HIGH);
  delay(2000);

  digitalWrite(relay4, LOW);
  delay(2000);
  digitalWrite(relay4, HIGH);
  delay(2000);

  while(1){
    delay(100);
    if(digitalRead(sensor2) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay1,HIGH);
      delay(350); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No eggs");
      digitalWrite(relay1,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }

    if(digitalRead(sensor1) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay2,HIGH);
      delay(350); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No eggs");
      digitalWrite(relay2,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }

   if(digitalRead(sensor3) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay3,HIGH);
      delay(350); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No egs");
      digitalWrite(relay3 ,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }

   if(digitalRead(sensor4) == LOW)
    {
      Serial.println("Eggs on");
      digitalWrite(relay4,HIGH);
      delay(100); // shpejtesia sensorit // sensor speed
    }
    else
    {
      Serial.println("No eggs");
      digitalWrite(relay4 ,LOW);
      delay(50); // sa mu kthy shpejt klipi mbrapa // speed of cylinder getting back
    }
 }


问:
How to output this 24 bit image in Qt
I have an unsigned char array that is defined like so:

```<code>unsigned char **chars = new unsigned char *[H];
for(int i = 0; i < H; i++)
{

    chars[i] = new unsigned char[W*3];
}
</code>```

Where H is the height of the image, and W is the width, and chars is populated in the rest of that function looping over rows x columns of the input image. Chars is populated in the order Red Green Blue

I am trying to read it with something like this:

```<code>QImage *qi = new QImage(imwidth, imheight, QImage::Format_RGB888);
    for (int i = 0 ; i < imheight ; i++)
        for (int j = 0 ; j < imwidth ; j++)
        {      //not sure why, but have to flip j and i in the index for setPixel
               qi->setPixel(j,i,qRgb(imageData[i][j],imageData[i][j+1],imageData[i][j+2]));
               j+=3;

           }

   QPixmap p(QPixmap::fromImage(*qi,Qt::AutoColor));
   QPixmap p1(p.scaled(ui->menuBar->width(),ui->menuBar->width(), Qt::KeepAspectRatio, Qt::SmoothTransformation ));
   ui->viewLabel->setPixmap(p1);
   ui->viewLabel->setFixedHeight(p1.height());
   ui->viewLabel->setFixedWidth(p1.width());
</code>```

where chars was returned to this calling function in the imageData array.

What am I doing wrong? Should I use a different format, even though I am clearly allocating 3 unsigned chars per pixel (which is why I chose the RGB888 format). This code as posted returns an image, but it is displaying incorrectly - partially scrambled, washed out, etc

Thanks

答:
You can create a QImage directly from a block of data without copying every pixel.

Since your image is stored with separate rows, you need something like

```<code>QImage image = new QImage(width,height,QImage::RGB888)

for (int h=0;h<height;h++) {
    // scanLine returns a ptr to the start of the data for that row
    memcpy(image.scanLine(h),chars[h],width*3);
}
</code>```

if you use RGB32 then you need to manually set the alpha channel for each pixel to 0xff -  just memset() the entire data to 0xff first

Title: How to output this 24 bit image in Qt

Body:
I have an unsigned char array that is defined like so:

unsigned char **chars = new unsigned char *[H];
for(int i = 0; i < H; i++)
{

    chars[i] = new unsigned char[W*3];
}

Where H is the height of the image, and W is the width, and chars is populated in the rest of that function looping over rows x columns of the input image. Chars is populated in the order Red Green Blue

I am trying to read it with something like this:

QImage *qi = new QImage(imwidth, imheight, QImage::Format_RGB888);
    for (int i = 0 ; i < imheight ; i++)
        for (int j = 0 ; j < imwidth ; j++)
        {      //not sure why, but have to flip j and i in the index for setPixel
               qi->setPixel(j,i,qRgb(imageData[i][j],imageData[i][j+1],imageData[i][j+2]));
               j+=3;

           }

   QPixmap p(QPixmap::fromImage(*qi,Qt::AutoColor));
   QPixmap p1(p.scaled(ui->menuBar->width(),ui->menuBar->width(), Qt::KeepAspectRatio, Qt::SmoothTransformation ));
   ui->viewLabel->setPixmap(p1);
   ui->viewLabel->setFixedHeight(p1.height());
   ui->viewLabel->setFixedWidth(p1.width());

where chars was returned to this calling function in the imageData array.

What am I doing wrong? Should I use a different format, even though I am clearly allocating 3 unsigned chars per pixel (which is why I chose the RGB888 format). This code as posted returns an image, but it is displaying incorrectly - partially scrambled, washed out, etc

Thanks

Body:
You can create a QImage directly from a block of data without copying every pixel.

Since your image is stored with separate rows, you need something like

QImage image = new QImage(width,height,QImage::RGB888)

for (int h=0;h<height;h++) {
    // scanLine returns a ptr to the start of the data for that row
    memcpy(image.scanLine(h),chars[h],width*3);
}

if you use RGB32 then you need to manually set the alpha channel for each pixel to 0xff -  just memset() the entire data to 0xff first


问:
Custom button in AlertDialog programmatically
After lots of research on stackoverflow and google, I have really found no issue to my problem.
Well, I'd like to create a button with height = 50 and width = 50 on top right of my dialog.
Well, I can set height without problem, but width doesn't work.
I tried with creating a linearLayout, but params never took in consideration.
Here is my code (height is sets properly) :

```<code>private void hello(){
    Button button = new Button(this);

    button.setMinimumWidth(0);
    button.setWidth(50);
    button.setMinimumHeight(0);
    button.setHeight(50);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v){
            sayHello();
        }
    });

    new AlertDialog.Builder(this)
            .setTitle("Hello world")
            .setView(button)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton){
                    Toast.makeText(getApplicationContext(), "Click !",
                    Toast.LENGTH_SHORT).show();
                    hello();
                }
            })

            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton){
                }
            })
            .show();
}
</code>```

I tried with :

```<code>        button.setLayoutParams(new LinearLayout.LayoutParams(50, 50));
</code>```

Without any success.

And with :

```<code>LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
    rlp.height = 50;
    rlp.width = 50;

    button.setText("i");
    button.setLayoutParams(rlp);
</code>```

And doesn't work either...

I really don't understand what's happening, can you try help me please?

I precise, I don't have any xml, it's only in java.

答:
I finally decided to create my own alert dialog to customize it as I wish.
I had to create a xml file and used an inflater. The reason why setHeight works and not setWidth will forever stays a mystery...

Thank's for your help anyway

Body:
After lots of research on stackoverflow and google, I have really found no issue to my problem.
Well, I'd like to create a button with height = 50 and width = 50 on top right of my dialog.
Well, I can set height without problem, but width doesn't work.
I tried with creating a linearLayout, but params never took in consideration.
Here is my code (height is sets properly) :

private void hello(){
    Button button = new Button(this);

    button.setMinimumWidth(0);
    button.setWidth(50);
    button.setMinimumHeight(0);
    button.setHeight(50);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v){
            sayHello();
        }
    });

    new AlertDialog.Builder(this)
            .setTitle("Hello world")
            .setView(button)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton){
                    Toast.makeText(getApplicationContext(), "Click !",
                    Toast.LENGTH_SHORT).show();
                    hello();
                }
            })

            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton){
                }
            })
            .show();
}

I tried with :

        button.setLayoutParams(new LinearLayout.LayoutParams(50, 50));

Without any success.

And with :

LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
    rlp.height = 50;
    rlp.width = 50;

    button.setText("i");
    button.setLayoutParams(rlp);

And doesn't work either...

I really don't understand what's happening, can you try help me please?

I precise, I don't have any xml, it's only in java.


问:
How to use two versions of the same JAR in two bundles of OSGi?
I have an OSGi setup with maven.
The parent bundle's pom.xml has a dependency on JAR A which is in turn dependant on JAR B(version 1).
The parent has 2 children bundles. Child bundle 1 uses JAR B with version 1.
Child bundle 2 requires JAR B with version 2.
The JARs are not backward compatible. So I cannot upgrade the version of JAR B from 1 to 2.
I need to use version 1 of JAR in bundle 1 and version 2 of the same JAR in bundle 2, without any errors in class loading.

Right now, I get an error in class loading where any one of the bundles fail due to NoClassDefFound error because of using 2 versions.

How do I resolve this dependency using OSGi?

答:
One of the advantages with OSGi (arguably the most important one) is that you can use different versions of the same library in different bundles. In the few cases where that's a problem you would either get a 'loader constraint violation' or a 'ClassCastException'. The OSGi troubleshooting doc for the Vespa search engine shows a few examples. This would happen if one of your bundles calls an api in another bundle involving the classes in JAR B (as argument or return value), and the two bundles use different versions of B.

In your case, the problem is that either the failing bundle is missing an Import-Package, and/or there is no bundle exporting the required version of the package with the missing class. You can examine the bundles' manifest.mf to verify.

The simplest and safest way to solve this is to embed the desired version of B into each of your child bundles. This way, your child bundles will use their own version of B, living in separate class loaders.

You don't mention how you package your bundles, but if you're using the maven-bundle-plugin, it has an Embed-Dependency config option. Please note that you also have to embed the transitive dependencies of B by using the Embed-Transitive directive to ensure that all code used inside B is available at runtime.

Another solution is possible if both versions of B are packaged as OSGi bundles, and each exports the package (of the missing class) with a unique version number. (Again, verify from looking at B's manifest.mf). Then, you can deploy both B bundles, and have each of your child bundles import the correct version.


问:
How to resolve “Error: bad index – Fatal: index file corrupt” when using Git-SVN
i'm currently using git svn in one of my repo and when i do

```<code>git svn fetch
</code>```

i got

```<code>Found possible branch point: coherent tag ref
Initializing parent: ok stuff

error: bad index file sha1 signature
fatal: index file corrupt
command returned error: 128
</code>```

Is ther a way to fix this ? It's a kind of an horrible repo. It take days to synch to that point, i dont want to start from begining :/.

I try the

```<code>rm .git/index
</code>```

from How to resolve "Error: bad index – Fatal: index file corrupt" when using Git but there is no such file.

答:
The solution was to delete the "index" in the refs svn folder (from the root repo):

```<code>rm .git/svn/refs/{path/to/incriminated/ref}/index
</code>```

Then my

```<code>git svn fetch
</code>```

worked again.

Body:
i'm currently using git svn in one of my repo and when i do

git svn fetch

i got

Found possible branch point: coherent tag ref
Initializing parent: ok stuff

error: bad index file sha1 signature
fatal: index file corrupt
command returned error: 128

Is ther a way to fix this ? It's a kind of an horrible repo. It take days to synch to that point, i dont want to start from begining :/.

I try the

rm .git/index

from How to resolve "Error: bad index – Fatal: index file corrupt" when using Git but there is no such file.

Body:
The solution was to delete the "index" in the refs svn folder (from the root repo):

rm .git/svn/refs/{path/to/incriminated/ref}/index

Then my

git svn fetch

worked again.


问:
set jump and long jump codeflow in c
I am trying to learn setjump and longjump in C. Can anyone help me with the output of the following code along with the code flow and the explanation for the the cases.i have called a function funcall() in the code. The alarm is being called for the first iteration but in the subsequent iterations the alarm is not being called. Why is it so? Does alarm(0) prevents any future alarm requests?

EDIT : Even after deleting the "print_T()" line in the signal handler the code doesnot seem to run.

```<code>#include <stdio.h>
#include <setjmp.h>
#include <signal.h>
#include <time.h>

#define LEN 50

jmp_buf po;

void print_T() {
    time_t rawtime;
    struct tm * timeinfo;

    time(&rawtime);
    timeinfo = localtime ( &rawtime );
    printf ( "Current local time and date: %s", asctime (timeinfo) );
}

static void ti() {
    print_T();
    longjmp(po,1);
}
int funcall(int reply) {

    static int p;
    p = 0;
    signal(SIGALRM, ti);
    int q = setjmp(po);
    if(q == 0)
        printf("the value BEFORE setjmp %d for reply %d\n", p, reply);
    else
        printf("the value AFTER setjmp %d for reply %d\n", p, reply);
    alarm(5);

    if(p > 0) {
        printf("INVOKING THE ALARM");
        alarm(0);
        return -1;
    }

    p++;
    for(int i = 0; i < 100000; i++)
        for(int j = 0; j < 100000; j++);
    return 0;

}

int main() {

    int a;
    int reply;
    time_t start, end;
    for(reply=0; ; reply++) {
        printf("~~~~~~~~~~~~~~~~~~~~~~~~~ITERATION NUMBER  %d\n", reply);

        time(&start);
        a = funcall(reply);
        time(&end);
        double tin = difftime(end, start);
        printf("*********************ITERATION END  and a returned is %d after %f\n", a, tin );
        double tidiff = difftime(end, start);
        if(a < 0)
            if(reply == 10) {
                break;
           }

    }

}
</code>```

答:
Since I can't comment on any post other than mine as my reputations are less than 50, here is the output when your code is executed on mac os:

I don't see any problem with your code as alarm(5) is being called as many number of times as funcall() is called.

For each call to funcall(), first call to alarm(5) sets the SIGALRM signal to be delivered to the calling process (which is nothing but the function being executed/thread executing the function) after 5 seconds while the remaining part of the code executes.

Since in each call to funcall() static variable p is set to 0, if(p > 0){...} block will not be executed until p is greater than 0 which happens only if the next statement following the body of this block, p++ incrementing p and making it greater than zero, is executed.

Execution of the aforementioned if block and therefore call to alarm(0) depends on the time taken by the for loop following p++ to terminate. If execution of for loop finishes within 5 seconds, return 0 statement will return the control to the calling function. The return will cancel all the alarm requests and destroy the function call stack. So, in this case alarm(0) is not called.

Next, if execution of for loop takes > 5 seconds (ignoring all the scheduling delays that can happen and may result in unexpected behaviors at times), the pending alarm will be fired, resulting in invocation of signal handler ti(). When the signal handler ti() is invoked, the call to longjump() is made and execution starts again at the calling instruction of the setjump(). By the time control reaches at alarm(0)(assuming the for loop keeps executing for as long as preceding if block does not get executed for the second time), all the remaining alarm requests get cancelled by this call. So, alarm(0) cancels all the pending alarm requests after p>0 and for loop takes longer than 5 seconds.

Here is the execution recorded through asciinema
https://asciinema.org/a/fyZX7CRoikq5kLJS2t0Og2rot

And here is a screen shot of the asciinema session after execution completes.

Title: set jump and long jump codeflow in c

Body:
I am trying to learn setjump and longjump in C. Can anyone help me with the output of the following code along with the code flow and the explanation for the the cases.i have called a function funcall() in the code. The alarm is being called for the first iteration but in the subsequent iterations the alarm is not being called. Why is it so? Does alarm(0) prevents any future alarm requests?

EDIT : Even after deleting the "print_T()" line in the signal handler the code doesnot seem to run.

#include <stdio.h>
#include <setjmp.h>
#include <signal.h>
#include <time.h>

#define LEN 50

jmp_buf po;

void print_T() {
    time_t rawtime;
    struct tm * timeinfo;

    time(&rawtime);
    timeinfo = localtime ( &rawtime );
    printf ( "Current local time and date: %s", asctime (timeinfo) );
}

static void ti() {
    print_T();
    longjmp(po,1);
}
int funcall(int reply) {

    static int p;
    p = 0;
    signal(SIGALRM, ti);
    int q = setjmp(po);
    if(q == 0)
        printf("the value BEFORE setjmp %d for reply %d\n", p, reply);
    else
        printf("the value AFTER setjmp %d for reply %d\n", p, reply);
    alarm(5);

    if(p > 0) {
        printf("INVOKING THE ALARM");
        alarm(0);
        return -1;
    }

    p++;
    for(int i = 0; i < 100000; i++)
        for(int j = 0; j < 100000; j++);
    return 0;

}

int main() {

    int a;
    int reply;
    time_t start, end;
    for(reply=0; ; reply++) {
        printf("~~~~~~~~~~~~~~~~~~~~~~~~~ITERATION NUMBER  %d\n", reply);

        time(&start);
        a = funcall(reply);
        time(&end);
        double tin = difftime(end, start);
        printf("*********************ITERATION END  and a returned is %d after %f\n", a, tin );
        double tidiff = difftime(end, start);
        if(a < 0)
            if(reply == 10) {
                break;
           }

    }

}


问:
Dynamically add element beside inputs
Let's say I have 10 different input fields, each of them has an ID.

<input id="blue">
<input id="pink">
<input id="red">

```

<p>Next to these input fields, I want to create an <code><a></code> element whose <code>href</code> attribute should dynamically include the ID of the button right next to it:</p>

<pre class="lang-html prettyprint-override"><code><input id="blue">
<a/>

<input id="pink">
href="mylink.com/pink"><a/>

<input id="red">
href="mylink.com/red"><a/>
</code>```

This is the simple code I am working with:

$('input').prepend('href="mylink.com/'+ID of the element next to this a tag+'/'');```

答:
try like this

https://jsfiddle.net/o2gxgz9r/18686/

```<code><div class="myHref">
 <input class="clickMe" id="blue">
 <a class="link" href="hello.com"></a>
   </div>
     <div class="myHref">
<input class="clickMe" id="pink">
<a class="link" href="hello.com"></a>
</div>
    <div class="myHref">
  <input class="clickMe" id="red">
      <a class="link" href="hello.com"></a>
 </div>

$(document).ready(function() {
    $('.clickMe').change(function(e){
       var textInput    =   $(this).val();
   $ele = $(this).closest('.myHref').find('.link');
     var _href =$(this).closest('.myHref').find('.link').attr("href");

     $(this).closest('.myHref').find('.link').attr("href", _href +'#'+textInput);

 var _href2 =$(this).closest('.myHref').find('.link').attr("href");
alert(_href2);
 });
 });
</code>```

Title: Dynamically add element beside inputs

Body:
Let's say I have 10 different input fields, each of them has an ID.

<input id="blue">
<input id="pink">
<input id="red">

Next to these input fields, I want to create an  element whose href attribute should dynamically include the ID of the button right next to it:

<input id="blue">

<input id="pink">

<input id="red">

This is the simple code I am working with:

$('input').prepend('<a href="mylink.com/'+ID of the element next to this a tag+'/'');

Body:
try like this

https://jsfiddle.net/o2gxgz9r/18686/

<div class="myHref">
 <input class="clickMe" id="blue">
 <a class="link" href="hello.com"></a>
   </div>
     <div class="myHref">
<input class="clickMe" id="pink">
<a class="link" href="hello.com"></a>
</div>
    <div class="myHref">
  <input class="clickMe" id="red">
      <a class="link" href="hello.com"></a>
 </div>

$(document).ready(function() {
    $('.clickMe').change(function(e){
       var textInput    =   $(this).val();
   $ele = $(this).closest('.myHref').find('.link');
     var _href =$(this).closest('.myHref').find('.link').attr("href");

     $(this).closest('.myHref').find('.link').attr("href", _href +'#'+textInput);

 var _href2 =$(this).closest('.myHref').find('.link').attr("href");
alert(_href2);
 });
 });


问:
how to use hook_views_api to load the views in a module in drupal
my module.views.inc and .module file are located in the same folder

I want to use hook_views_api() to call the .views.inc file
The following code does not work

  function module_name_views_api(){
    return array(
    'api' => 2,
    'path' => array('module','module_name'),
  );
}

Any ideas?

答:
If yourmodule.views.inc and yourmodule.module are in the same folder, I don't think you need the path part. The following example works in one of my modules:</p>

```<code>function mymodule_views_api() {
  return array('api' => 2.0);
}
</code>```

Body:
If yourmodule.views.inc and yourmodule.module are in the same folder, I don't think you need the path part. The following example works in one of my modules:

function mymodule_views_api() {
  return array('api' => 2.0);
}


问:
Element position from nested DataFrame array (Spark 2.2)
I'm trying to explode a nested DataFrame in Spark Scala. I have a DataFrame df which contains the following information:

```<code>root
|-- id: integer (nullable = false)
|-- features: array (nullable = true)
|   |-- element: float (containsNull = false)
</code>```

I've exploded the array information into to a flat DataFrame with:

```<code>df.selectExpr("id","explode(features) as features")
</code>```

and got the following DataFrame:

```<code>id  features
0   0.0629885
0   0.15931357
0   0.08922347
</code>```

My end goal is to pivot the data and calculate some similarities with that information. To do that, it would be very cool to get the actual position of the feature for every ID into the DataFrame, like this:

```<code>  id  features    feature_pos
  0   0.0629885   0
  0   0.15931357  1
  0   0.08922347  2
</code>```

答:
Use posexplode in place of explode:

Creates a new row for each element with position in the given array or map column.

Unlike posexplode, if the array/map is null or empty then the row (null, null) is produced.

Body:
I'm trying to explode a nested DataFrame in Spark Scala. I have a DataFrame df which contains the following information:

root
|-- id: integer (nullable = false)
|-- features: array (nullable = true)
|   |-- element: float (containsNull = false)

I've exploded the array information into to a flat DataFrame with:

df.selectExpr("id","explode(features) as features")

and got the following DataFrame:

id  features
0   0.0629885
0   0.15931357
0   0.08922347

My end goal is to pivot the data and calculate some similarities with that information. To do that, it would be very cool to get the actual position of the feature for every ID into the DataFrame, like this:

  id  features    feature_pos
  0   0.0629885   0
  0   0.15931357  1
  0   0.08922347  2


问:
Ruby openssl documentation
Is there any online documentation of Ruby's openssl library? All I can find are blog posts and third-party articles, and the rdoc itself doesn't really explain how to use the library step-by-step.

答:
Some brave soul finally documented it in the latest versions of ruby.  See github:

https://github.com/ruby/ruby/blob/trunk/ext/openssl/ossl.c#L409

EDIT: just to give credit where it's due, the commit history says that Eric Hodel is responsible for this good documentation.

Title: Ruby openssl documentation


问:
Android - clickable items from JSON
I know there are many similar questions and answers here, but nothing worked for my case.

I created a simple JSON list using fragment - according to this tutorial http://androidbeginnerstutorial.blogspot.sk/2015/06/json-parsing-using-fragment-with.html

It is working fine, but I want to have all items from the list clickable, so after click another page appears with some more info from the same JSON.

I tried to implement to ActorAdapter.java inside

```<code>public View getView(int position, View convertView, ViewGroup parent) {
</code>```

I created something like

```<code> itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
})
</code>```

but not sure what else to put there to get it work.

I have already created the SingleitemView class.

Can you please help me? Thank you.

Here is my code from ActorAdapter.java:

```<code>import java.io.InputStream;
import java.util.ArrayList;

import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        actorList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
            holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.imageview.setImageResource(R.drawable.ic_launcher);
        new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
        holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
        holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());

   v.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(view.getContext(), SingleitemView.class);
        intent.putExtra("name", "XXXXXX");
        view.getContext().startActivity(intent);
    }
});

        return v;

    }

    static class ViewHolder {
        public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;
        public TextView tvSpouse;
        public TextView tvChildren;

    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {

            bmImage.setImageBitmap(result);
        }

    }
}
</code>```

and the SingleitemView.java - that is supposed to be the new activity after click

```<code>    import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.widget.TextView;

public class SingleitemView extends Activity {
// Declare Variables
String name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    Intent i = getIntent();
    // Get the result of rank
    name = i.getStringExtra("name");

    // Locate the TextViews in singleitemview.xml
    TextView txtname = (TextView) findViewById(R.id.name);

    // Set results to the TextViews
    txtname.setText(name);

}
</code>```

}

答:
Try this</p>

```<code>itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(view.getContext(), SingleitemView.class);
            intent.putExtra("name", actorList.get(position).getName());
            view.getContext().startActivity(intent);
        }
    });
</code>```

Title: Android - clickable items from JSON

Body:
I know there are many similar questions and answers here, but nothing worked for my case.

I created a simple JSON list using fragment - according to this tutorial http://androidbeginnerstutorial.blogspot.sk/2015/06/json-parsing-using-fragment-with.html

It is working fine, but I want to have all items from the list clickable, so after click another page appears with some more info from the same JSON.

I tried to implement to ActorAdapter.java inside

public View getView(int position, View convertView, ViewGroup parent) {

I created something like

 itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
})

but not sure what else to put there to get it work.

I have already created the SingleitemView class.

Can you please help me? Thank you.

Here is my code from ActorAdapter.java:

import java.io.InputStream;
import java.util.ArrayList;

import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        actorList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
            holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.imageview.setImageResource(R.drawable.ic_launcher);
        new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
        holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
        holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());

   v.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(view.getContext(), SingleitemView.class);
        intent.putExtra("name", "XXXXXX");
        view.getContext().startActivity(intent);
    }
});

        return v;

    }

    static class ViewHolder {
        public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;
        public TextView tvSpouse;
        public TextView tvChildren;

    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {

            bmImage.setImageBitmap(result);
        }

    }
}

and the SingleitemView.java - that is supposed to be the new activity after click

    import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.widget.TextView;

public class SingleitemView extends Activity {
// Declare Variables
String name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    Intent i = getIntent();
    // Get the result of rank
    name = i.getStringExtra("name");

    // Locate the TextViews in singleitemview.xml
    TextView txtname = (TextView) findViewById(R.id.name);

    // Set results to the TextViews
    txtname.setText(name);

}

}

Body:
Try this

itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(view.getContext(), SingleitemView.class);
            intent.putExtra("name", actorList.get(position).getName());
            view.getContext().startActivity(intent);
        }
    });


问:
PostgresSql + Nodejs (ClaudiaJS) : How to cast array of string to array of timestamp
I am writing API which insert into a table with multiple rows, I am using UNNEST to make it work.

What I have done:

in js file:

```<code>api.post(PREFIX + '/class/insert', function (request) {

    var db = pgp(dbconnect);

    //Params
    var data = request.body; //should be an array

    var classes = [];
    var starts = [];
    var ends = [];

    for (var i = 0; i < data.length; i++) {
        classes.push(data[i].class_id);
        starts.push(data[i].timestamp_start);
        ends.push(data[i].timestamp_end);
    }

    const PQ = require('pg-promise').ParameterizedQuery;

    var sql =
    "INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
    "VALUES(  "+
        "UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"

    const final_sql = new PQ(sql);

    return db.any(final_sql)
        .then(function (data) {
            pgp.end();

            return 'successful';
        })
        .catch(function (error) {
            console.log("Error: " + error);
            pgp.end();
        });
}
</code>```

Request body

```<code>[{
    "class_id":"1",
    "timestamp_start":"2017-11-14 14:01:23.634437+00",
    "timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
    "class_id":"2",
    "timestamp_start":"2017-11-14 15:01:23.634437+00",
    "timestamp_end": "2017-11-14 16:20:23.634437+00"
}]
</code>```

When I run api in postman, I get the error is:

column "timestamp_start" is of type timestamp with time zone but
  expression is of type text

Issue is obviously from ARRAY of string that I used in sql, my question is how to create ARRAY of timestamp for UNNEST, or any suggestion are appreciated.

Thanks

答:
Never initialize the database inside the handler, see: Where should I initialize pg-promise

Never call pgp-end() inside HTTP handlers, it destroys all connection pools.

Use static ColumnSet type to generate multi-insert queries.

Do not return from db.any, there is no point in that context

You must provide an HTTP response within an HTTP handler

You are providing a confusing semantics for column class_id. Why is it called like that and yet being converted into a timestamp?

Never concatenate objects with strings directly.

Never concatenate SQL strings manually, it will break formatting and open your code to SQL injection.

Use Database methods according to the expected result, i.e. none in your case, and not any. See: https://github.com/vitaly-t/pg-promise#methods

Initialize everything needed only once:

```<code>const db = pgp(/*connection*/);

const cs = new pgp.helpers.ColumnSet([
    'class_id',
    {
        name: 'timestamp_start',
        cast: 'timestamp'
    },
    {
        name: 'timestamp_end',
        cast: 'timestamp'
    }
], {table: {table: 'class', schema: 'sa1'}});
</code>```

Implement the handler:

```<code>api.post(PREFIX + '/class/insert', request => {

    const sql = pgp.helpers.insert(request.body, cs);

    db.none(sql)
        .then(data => {
            // provide an HTTP response here
        })
        .catch(error => {
            console.log('Error:', error);
            // provide an HTTP response here
        });
}
</code>```

Body:
I am writing API which insert into a table with multiple rows, I am using UNNEST to make it work.

What I have done:

in js file:

api.post(PREFIX + '/class/insert', function (request) {

    var db = pgp(dbconnect);

    //Params
    var data = request.body; //should be an array

    var classes = [];
    var starts = [];
    var ends = [];

    for (var i = 0; i < data.length; i++) {
        classes.push(data[i].class_id);
        starts.push(data[i].timestamp_start);
        ends.push(data[i].timestamp_end);
    }

    const PQ = require('pg-promise').ParameterizedQuery;

    var sql =
    "INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
    "VALUES(  "+
        "UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"

    const final_sql = new PQ(sql);

    return db.any(final_sql)
        .then(function (data) {
            pgp.end();

            return 'successful';
        })
        .catch(function (error) {
            console.log("Error: " + error);
            pgp.end();
        });
}

Request body

[{
    "class_id":"1",
    "timestamp_start":"2017-11-14 14:01:23.634437+00",
    "timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
    "class_id":"2",
    "timestamp_start":"2017-11-14 15:01:23.634437+00",
    "timestamp_end": "2017-11-14 16:20:23.634437+00"
}]

When I run api in postman, I get the error is:

column "timestamp_start" is of type timestamp with time zone but
  expression is of type text

Issue is obviously from ARRAY of string that I used in sql, my question is how to create ARRAY of timestamp for UNNEST, or any suggestion are appreciated.

Thanks

Body:
Never initialize the database inside the handler, see: Where should I initialize pg-promise

Never call pgp-end() inside HTTP handlers, it destroys all connection pools.

Use static ColumnSet type to generate multi-insert queries.

Do not return from db.any, there is no point in that context

You must provide an HTTP response within an HTTP handler

You are providing a confusing semantics for column class_id. Why is it called like that and yet being converted into a timestamp?

Never concatenate objects with strings directly.

Never concatenate SQL strings manually, it will break formatting and open your code to SQL injection.

Use Database methods according to the expected result, i.e. none in your case, and not any. See: https://github.com/vitaly-t/pg-promise#methods

Initialize everything needed only once:

const db = pgp(/*connection*/);

const cs = new pgp.helpers.ColumnSet([
    'class_id',
    {
        name: 'timestamp_start',
        cast: 'timestamp'
    },
    {
        name: 'timestamp_end',
        cast: 'timestamp'
    }
], {table: {table: 'class', schema: 'sa1'}});

Implement the handler:

api.post(PREFIX + '/class/insert', request => {

    const sql = pgp.helpers.insert(request.body, cs);

    db.none(sql)
        .then(data => {
            // provide an HTTP response here
        })
        .catch(error => {
            console.log('Error:', error);
            // provide an HTTP response here
        });
}


问:
Readjusting background image in Tkinter?
I tried to place an image in the background of the tkinter window, and added buttons but the image automatically places between two buttons(placed button on bottom left and bottom right) and image doesn't stretch horizontally.

How do we make the image stretch in background?

(I'm using tkinter in python  3.6.1)

答:
Guessing this how your code looks like , change the image file to the file you want to use for your background.

```<code>from tkinter import *

root = Tk()
root.geometry("400x400")

lb = PhotoImage(file="Background image.png") # repalce with your file name
label = Label(root, image=lb)
label.place(x=0, y=0, relwidth=1, relheight=1)

Button1 = Button(root, text="my button one").pack(side="left")
Button = Button(root, text="my button two").pack(side="right")

root.mainloop()
</code>```

if you need additional help post in the comment box

Body:
Guessing this how your code looks like , change the image file to the file you want to use for your background.

from tkinter import *

root = Tk()
root.geometry("400x400")

lb = PhotoImage(file="Background image.png") # repalce with your file name
label = Label(root, image=lb)
label.place(x=0, y=0, relwidth=1, relheight=1)

Button1 = Button(root, text="my button one").pack(side="left")
Button = Button(root, text="my button two").pack(side="right")

root.mainloop()

if you need additional help post in the comment box


问:
Vertical aligning doesn't work on first page load
I'm trying to vertically center a div using

```<code>.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
</code>```

however, I've noticed that on first page load, it doesn't work well. The div moves up to the top of the page. On refresh, everything works properly and the div is vertically centered. What can I do to solve this?

答:
I tend to absolutely position elements by 50% and then use margin-top:-<half .element height>:

example:

```<code>height:100px;
position: absolute;
top:50%;
margin-top:-50px;
</code>```

Check out this fiddle

Body:
I'm trying to vertically center a div using

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

however, I've noticed that on first page load, it doesn't work well. The div moves up to the top of the page. On refresh, everything works properly and the div is vertically centered. What can I do to solve this?

Body:
I tend to absolutely position elements by 50% and then use margin-top:-<half .element height>:

example:

height:100px;
position: absolute;
top:50%;
margin-top:-50px;

Check out this fiddle