问:
Android keyboard appears and disappears when clicking search input
I am using Google Maps Js API and my input search bar works fine when I search for a place. When i use it via iPhone devices it works fine too, but when I use it via Android devices then the keyboard appears and disappears instantly. I have already found some solutions about the android keyboard losing focus when i press the search bar, but I can't understand how or where I should implement the solution. I have the following part of code:

Here is my input and onclick event and my search bar:

```<code><div class="col-sm-12" style="padding-right: 0px; margin-bottom: 10px;">
  <span>Closest points</span>
  <input id="locationTextField" type="text" size="40" float: left;">
  <button class="btn pointsok" onclick='gotocustomlocation()' style="float: left; margin-left: 2px; width: 33px; padding-left: 6px; padding-right: 6px;">OK</button>
</div>
</code>```

Maybe something above autocomplete.getPlace could fix the problem ?

```<code><script>
            function gotocustomlocation() {
                var place = autocomplete.getPlace();
                var lat = place.geometry.location.lat();
                var lng = place.geometry.location.lng();
                console.log(lat);
                console.log(lng);
                jQuery.ajax({
                    type: 'GET',
                    url: "<?php echo JURI::base() . "index.php?option=com_ajax&module=points&format=json&method=getClosestAreas&lat=";?>"  + lat + "&lng=" + lng,
                    success:function(resp){
                        if (typeof map !== 'undefined') {
                            jQuery('#prefectures option[value="noval"]').attr("selected",true);
                            jQuery('#subPrefectures').find('option').remove();
                            jQuery('#subPrefectures').append(jQuery("<option></option>").attr("value","noval").text('Choose Area'));
                            jQuery('#subPrefectures').prop('disabled', 'disabled');
                            kmlLayer.forEach(function(l) {
                                l.setMap(null);
                            });
                            var latLng = new google.maps.LatLng(lat, lng);
                            map.setZoom(11);
                            map.panTo(latLng);
                        }
                        var distances = JSON.parse(resp.data);
                        var htmlcontent = "Closest Spot<br />";
                        for (var i=0; i<10; i++) {
                            var uri =  "<?php echo JURI::base(); ?>" + "weather/" + distances[i].uri;
                            htmlcontent += "<span style='display:block;float:left;white-space:nowrap;'> <a href='"+uri+"'>"+distances[i].alias+"</a>";
                            if (i < 10) {
                                htmlcontent += " | </span>";
                            } else {
                                htmlcontent += "</span>";
                            }
                        }
                        jQuery("#pointsareas").html(htmlcontent);
                    },
                    error:function(){
                    }
                });
            }
            //google.maps.event.addDomListener(window, 'load', init);
        </script>
</code>```

Mind that google.maps.event.addDomListener(window, 'load', init); is not affecting the search bar.

Should it be a problem in JS, or it could be a wrong @media resizing in CSS ?

答:
I had the same problem and @amit's solution helped.
The problem is, that clicking on the searchbar somehow triggers the "orientationchange" or "resize" event, maybe the keyboard which shows triggers it. I don't know.

After the event is triggered, the searchbar gets moved to the mobile container, even though it is already in this container. So it gets unlinked from its container and linked to it again. This causes the searchbar to loose focus, so the browser hides the keyboard.

Problem Code:

```<code>$(window).on("orientationchange resize", function() { breakpointChecks(); });

function breakpointChecks()
{
        ifMaxWidth(767, function() {
            $searchForm.appendTo($mobileSearchContainer);
        });

        ifMinWidth(768, function() {
            $searchForm.appendTo($desktopSearchContainer);
        });
}
</code>```

Solution:

Add a variable which stores the current mode (desktop or mobile) and only trigger the move code if we are not already on this mode.

```<code>var currentMode = "";
$(window).on("orientationchange resize", function() { breakpointChecks(); });

function breakpointChecks()
{
    if (currentMode != "mobile") {
        ifMaxWidth(767, function() {
            currentMode = "mobile";
            $searchForm.appendTo($mobileSearchContainer);
            $loginRegisterBox.appendTo($headerContainerMobile);
        });
    }

    if (currentMode != "desktop") {
        ifMinWidth(768, function() {
            currentMode = "desktop";
            $searchForm.appendTo($desktopSearchContainer);
            $loginRegisterBox.appendTo($desktopLoginRegisterContainer);
        });
    }
}
</code>```

Body:
I am using Google Maps Js API and my input search bar works fine when I search for a place. When i use it via iPhone devices it works fine too, but when I use it via Android devices then the keyboard appears and disappears instantly. I have already found some solutions about the android keyboard losing focus when i press the search bar, but I can't understand how or where I should implement the solution. I have the following part of code:

Here is my input and onclick event and my search bar:

  Closest points
  <input id="locationTextField" type="text" size="40" float: left;">
  <button class="btn pointsok" onclick='gotocustomlocation()' style="float: left; margin-left: 2px; width: 33px; padding-left: 6px; padding-right: 6px;">OK</button>

Maybe something above autocomplete.getPlace could fix the problem ?

Mind that google.maps.event.addDomListener(window, 'load', init); is not affecting the search bar.

Should it be a problem in JS, or it could be a wrong @media resizing in CSS ?

Body:
I had the same problem and @amit's solution helped.
The problem is, that clicking on the searchbar somehow triggers the "orientationchange" or "resize" event, maybe the keyboard which shows triggers it. I don't know.

After the event is triggered, the searchbar gets moved to the mobile container, even though it is already in this container. So it gets unlinked from its container and linked to it again. This causes the searchbar to loose focus, so the browser hides the keyboard.

Problem Code:

$(window).on("orientationchange resize", function() { breakpointChecks(); });

function breakpointChecks()
{
        ifMaxWidth(767, function() {
            $searchForm.appendTo($mobileSearchContainer);
        });

        ifMinWidth(768, function() {
            $searchForm.appendTo($desktopSearchContainer);
        });
}

Solution:

Add a variable which stores the current mode (desktop or mobile) and only trigger the move code if we are not already on this mode.

var currentMode = "";
$(window).on("orientationchange resize", function() { breakpointChecks(); });

function breakpointChecks()
{
    if (currentMode != "mobile") {
        ifMaxWidth(767, function() {
            currentMode = "mobile";
            $searchForm.appendTo($mobileSearchContainer);
            $loginRegisterBox.appendTo($headerContainerMobile);
        });
    }

    if (currentMode != "desktop") {
        ifMinWidth(768, function() {
            currentMode = "desktop";
            $searchForm.appendTo($desktopSearchContainer);
            $loginRegisterBox.appendTo($desktopLoginRegisterContainer);
        });
    }
}


来源: stackexchange

问:
symfony create database index with lower function
How can I declare in Doctrine an index for postgresql like:
CREATE INDEX index_name_city_hotel ON booking_hotels(lower(name) text_pattern_ops, city_hotel, cc1)

I already tried but it seems impossible to use lower() function.
This doesn't work because of the lower function:

```<code>indexes={
@ORM\Index(name="index_name_city_hotel", columns={"lower(name) text_pattern_ops", "city_hotel", "cc1"})
</code>```

thanks in advance for your help.

答:
Try to use https://github.com/intaro/custom-index-bundle</p>

```<code><?php

namespace Acme\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Intaro\CustomIndexBundle\Annotations as CustomIndexAnnotation

/**
 * @ORM\Table(name="my_entity")
 * @ORM\Entity()
 * @CustomIndexAnnotation\CustomIndexes(indexes={
 *     @CustomIndexAnnotation\CustomIndex(columns="my_property1"),
 *     @CustomIndexAnnotation\CustomIndex(columns={"lower(my_property1)", "lower(my_property2)"})
 * })
 */
class MyEntity
{
    /**
     * @ORM\Column(type="string", length=256)
     */
    protected $myProperty1;

    /**
     * @ORM\Column(type="string", length=256)
     */
    protected $myProperty2;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I declare in Doctrine an index for postgresql like:
CREATE INDEX index_name_city_hotel ON booking_hotels(lower(name) text_pattern_ops, city_hotel, cc1)

I already tried but it seems impossible to use lower() function.
This doesn't work because of the lower function:

indexes={
@ORM\Index(name="index_name_city_hotel", columns={"lower(name) text_pattern_ops", "city_hotel", "cc1"})

thanks in advance for your help.

Body:
Try to use https://github.com/intaro/custom-index-bundle

<?php

namespace Acme\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Intaro\CustomIndexBundle\Annotations as CustomIndexAnnotation

/**
 * @ORM\Table(name="my_entity")
 * @ORM\Entity()
 * @CustomIndexAnnotation\CustomIndexes(indexes={
 *     @CustomIndexAnnotation\CustomIndex(columns="my_property1"),
 *     @CustomIndexAnnotation\CustomIndex(columns={"lower(my_property1)", "lower(my_property2)"})
 * })
 */
class MyEntity
{
    /**
     * @ORM\Column(type="string", length=256)
     */
    protected $myProperty1;

    /**
     * @ORM\Column(type="string", length=256)
     */
    protected $myProperty2;
}

ContentLicense: CC BY-SA 4.0


问:
HTTP: Error receiving data – Connection reset by peer
Since I’ve rebooted my server yesterday I’m getting this error:

mongodb’ failed protocol test [HTTP] at [localhost]:27017/ [TCP/IP] – HTTP: Error receiving data – Connection reset by peer

‘mongodb’ start: ‘/usr/bin/sudo mongod --dbpath=/var/lib/mongodb’

Tried a couple of thing but no luck.

Also checked with curl -v localhost:27017 and output below:

Rebuilt URL to: localhost:27017/
Trying ::1…
TCP_NODELAY set
connect to ::1 port 27017 failed: Connection refused
Trying 127.0.0.1…
TCP_NODELAY set
Connected to localhost (127.0.0.1) port 27017 (#0)
GET / HTTP/1.1
Host: localhost:27017
User-Agent: curl/7.58.0
Accept: /

Recv failure: Connection reset by peer
stopped the pause stream!
Closing connection 0
curl: (56) Recv failure: Connection reset by peer

Any input or help will be much appreciated.

Thanks.

答: for temporary solution try to use VPN</p>

Body: for temporary solution try to use VPN


问:
Extract a word from multiline string
I have a multiline string from which I have to extract a word.

Sample String:

```<code>`Locale LANG set to the following: "en"
Scheduled for (Exp) 02/12/20 (#4662) on CSC2CXN00002555.  Batchman LIVES.  Limit: 80, Fence: 0, Audit Level: 1`
</code>```

I have to extract only the word CSC2CXN00002555. I tried using regex_search ansible module

```<code>{{ input_string | regex_search('on(.*).  Batchman', multiline=True) }}
</code>```

But I'm getting the whole pattern as output:

```<code>{
"msg": "on CSC2CXN00002555.  Batchman"
}
</code>```

Is there a way to achieve this?

答:
Try using this regex - CS(.*)5.

```<code>{{ input_string | regex_search('CS(.*)5', multiline=True) }}
</code>```

Title: Extract a word from multiline string

Body:
I have a multiline string from which I have to extract a word.

Sample String:

`Locale LANG set to the following: "en"
Scheduled for (Exp) 02/12/20 (#4662) on CSC2CXN00002555.  Batchman LIVES.  Limit: 80, Fence: 0, Audit Level: 1`

I have to extract only the word CSC2CXN00002555. I tried using regex_search ansible module

{{ input_string | regex_search('on(.*).  Batchman', multiline=True) }}

But I'm getting the whole pattern as output:

{
"msg": "on CSC2CXN00002555.  Batchman"
}

Is there a way to achieve this?

Body:
Try using this regex - CS(.*)5.

{{ input_string | regex_search('CS(.*)5', multiline=True) }}


问:
URL join of two URIs
I am trying to join these two URIs

```<code>from urllib.parse import urljoin
# baskslash is not a mistake
r = urljoin(r"https:/\\corrlinks.blob.core.windows.net", r"videofaq")
print(r)
</code>```

I am getting

```<code>https:///videofaq
</code>```

How can I get

```<code>https:/\\corrlinks.blob.core.windows.net/videofaq
</code>```

This one would be Ok too:

```<code>https://corrlinks.blob.core.windows.net/videofaq
</code>```

Note. Browsers handle the link above just fine.

答:
Function interpret slash as baseurl, so you're need to add another one at the end to teach it:

urljoin(r"https:/\\corrlinks.blob.core.windows.net/", "videofaq")
```

Title: URL join of two URIs

Body:
I am trying to join these two URIs

from urllib.parse import urljoin
# baskslash is not a mistake
r = urljoin(r"https:/\\corrlinks.blob.core.windows.net", r"videofaq")
print(r)

I am getting

https:///videofaq

How can I get

https:/\\corrlinks.blob.core.windows.net/videofaq

This one would be Ok too:

https://corrlinks.blob.core.windows.net/videofaq

Note. Browsers handle the link above just fine.


问:
Service account not Authorized to access this resource/api while trying to access directory api using Python
We use Python to get all users from a particular G Suite managed domain, but after completing the following tutorial and granting all the access needed to the Service Account, the following snippet still produces "Not Authorized to access this resource/api:</p>

```<code>import json
from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']

credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES)

service = build('admin', 'directory_v1', credentials=credentials)
</code>```

答:
There is a (very vague) clue in Google documentation to the solution:

Note: Only users with access to the Admin APIs can access the Admin
  SDK Directory API, therefore your service account needs to impersonate
  one of those users to access the Admin SDK Directory API.
  Additionally, the user must have logged in at least once and accepted
  the G Suite Terms of Service.

The way to achieve the impersonation in Python is by sending a "subject" when authenticating with OAuth2 library. The subject should be a user with an access to the Admin API (He doesn't have to be an admin, User Management Role should be sufficient, at least for my needs).

A working snippet:

```<code>import json
from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']

credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES, subject="admin@yourdomain.com")
</code>```

Body:
We use Python to get all users from a particular G Suite managed domain, but after completing the following tutorial and granting all the access needed to the Service Account, the following snippet still produces "Not Authorized to access this resource/api:

import json
from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']

credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES)

service = build('admin', 'directory_v1', credentials=credentials)

Body:
There is a (very vague) clue in Google documentation to the solution:

Note: Only users with access to the Admin APIs can access the Admin
  SDK Directory API, therefore your service account needs to impersonate
  one of those users to access the Admin SDK Directory API.
  Additionally, the user must have logged in at least once and accepted
  the G Suite Terms of Service.

The way to achieve the impersonation in Python is by sending a "subject" when authenticating with OAuth2 library. The subject should be a user with an access to the Admin API (He doesn't have to be an admin, User Management Role should be sufficient, at least for my needs).

A working snippet:

import json
from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']

credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES, subject="admin@yourdomain.com")


问:
Woocommerce: How to display SKU for variable product options dropdown
How I can view the SKU code in the dropdown option for the variable products? I have tried to use this code but it is only to view the price option in woocommerce. Cause recently I use the other code but the SKU not dynamically when I change and variable option.

```<code>add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );

function display_price_in_variation_option_name( $term ) {
  global $wpdb, $product;

  if( isset( $product ) ) {

    $result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );

    $term_slug = ( !empty( $result ) ) ? $result[0] : $term;

    $query = sprintf( "SELECT postmeta.post_id AS product_id
      FROM {$wpdb->prefix}postmeta postmeta
      LEFT JOIN {$wpdb->prefix}posts products ON ( products.id = postmeta.post_id )
      WHERE postmeta.meta_key LIKE 'attribute_%%'
      AND postmeta.meta_value = '%s'
      AND products.post_parent = %d", $term_slug, $product->get_id() );

    $variation_id = $wpdb->get_col( $query );

    $parent = wp_get_post_parent_id( $variation_id[0] );

    if ( $parent > 0 ) {
      $_product = new WC_Product_Variation( $variation_id[0] );

      $itemPrice = strip_tags (wc_price( $_product->get_price() ));
      //this is where you can actually customize how the price is displayed
      return $term . ' ('. $itemPrice .')';
    }
  }
}
</code>```

Base on this code how could I assign the get-sku and view beside the variation option area in front end display.If anyone could help me to solve a problem I really appriciate that.

答:
function display_price_in_variation_option_name( $term ) {
    global $wpdb, $product;

    if( isset( $product ) ) {
        $query = sprintf( "SELECT postmeta.post_id AS product_id
            FROM {$wpdb->prefix}postmeta postmeta
            LEFT JOIN {$wpdb->prefix}posts products ON ( products.id = postmeta.post_id )
            WHERE postmeta.meta_key LIKE 'attribute_%%'
            AND postmeta.meta_value = '%s'
            AND products.post_parent = %d", $term, $product->get_id() );

        $results = $wpdb->get_results( $query );

        foreach ($results as $key => $result) {
            $variation_id = $result->product_id;
        }

        $variation_sku = get_post_meta( $variation_id , '_sku', TRUE );

        $term = $term . ' ('. $variation_sku .')';
    }

    return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name', 10, 1 );
```

Body:
How I can view the SKU code in the dropdown option for the variable products? I have tried to use this code but it is only to view the price option in woocommerce. Cause recently I use the other code but the SKU not dynamically when I change and variable option.

add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );

function display_price_in_variation_option_name( $term ) {
  global $wpdb, $product;

  if( isset( $product ) ) {

    $result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );

    $term_slug = ( !empty( $result ) ) ? $result[0] : $term;

    $query = sprintf( "SELECT postmeta.post_id AS product_id
      FROM {$wpdb->prefix}postmeta postmeta
      LEFT JOIN {$wpdb->prefix}posts products ON ( products.id = postmeta.post_id )
      WHERE postmeta.meta_key LIKE 'attribute_%%'
      AND postmeta.meta_value = '%s'
      AND products.post_parent = %d", $term_slug, $product->get_id() );

    $variation_id = $wpdb->get_col( $query );

    $parent = wp_get_post_parent_id( $variation_id[0] );

    if ( $parent > 0 ) {
      $_product = new WC_Product_Variation( $variation_id[0] );

      $itemPrice = strip_tags (wc_price( $_product->get_price() ));
      //this is where you can actually customize how the price is displayed
      return $term . ' ('. $itemPrice .')';
    }
  }
}

Base on this code how could I assign the get-sku and view beside the variation option area in front end display.If anyone could help me to solve a problem I really appriciate that.


问:
Alternative implementations of Haskell's standard library type classes
I've seen many people complaining about some of the type classes from the standard library saying things like "Monad should require Functor" or even "Monad should require Applicative", "Applicative should require Pointed", "Num shouldn't require Show", etc,
So, I have some questions:

Are there arguments for the way the tree of type class dependencies have those "flaws" perceived by the community or is this just the result of how things were done historically?

How drastically a change in this would break existing code?

Are there alternative implementations of the basic type classes (particularly arrows, monads, applicative, etc...) around that implement the "right" set of class dependencies?

答:
I oppose vicarious existence and also I cannot take the credit for the proposal which is related to Applicative-Functor-Monad hierarchies.  I had made mutterings years ago on the need for a mathematically sound Prelude.

One obstacle to a typeclass hierarchy is present at the very beginning with monoids.  For example, integers form both an additive and a multiplicative monoid.  Coq solves this through multiple inheritance.

One great advantage of having a mathematical hierarchy with a constructive mathematics proof system is that we can extract programs from proofs through the Curry-Howard isomorphism.  For those interested in program correctness and automated verification, having direct translations between Haskell typeclasses and proof-verification tools like Coq is nifty.

I currently use the hmatrix package and friends.  Unfortunately, I don't think it plays well with the current Numeric Prelude on hackage.  Ideally, to use the optimised BLAS and LAPACK libraries in generic code, one should just have to implement a typeclass interface specified in the Numeric Prelude.


问:
OpenMP invalid controlling predicate - persistent
I keep getting this error for >6 hours now when trying to compile C-code with -fopenmp flag using gcc.

error: invalid controlling predicate
   for ( int i = 0; i < N; i++ )

I browsed stackoverflow and I stripped down my code up till the point where it is an exact copy of an example from an OpenMP handbook, but still it doesn't compile.

```<code>#include <stdio.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif

int main(int argc, char *argv[]) {
    double N; sscanf (argv[1]," %lf", &N);
    double integral = 0.0;

    #pragma omp parallel for reduction(+: integral)
        for ( int i = 0; i < N; i++ )
            integral = integral + i;

    printf("%20.18lf\n", integral);
    return 0;
}
</code>```

Any suggestions..?

答:
Found it, sorry for the clutter..

To all other C newbies like myself: The error was in the double N. OpenMP wants your loop to run op to an INTEGER N, and not a double.

Body:
I keep getting this error for >6 hours now when trying to compile C-code with -fopenmp flag using gcc.

error: invalid controlling predicate
   for ( int i = 0; i < N; i++ )

I browsed stackoverflow and I stripped down my code up till the point where it is an exact copy of an example from an OpenMP handbook, but still it doesn't compile.

#include <stdio.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif

int main(int argc, char *argv[]) {
    double N; sscanf (argv[1]," %lf", &N);
    double integral = 0.0;

    #pragma omp parallel for reduction(+: integral)
        for ( int i = 0; i < N; i++ )
            integral = integral + i;

    printf("%20.18lf\n", integral);
    return 0;
}

Any suggestions..?


问:
Split Postal Code in R ( just the 2 first numbers)
I have a dataframe. One column is the postal code in Catalonia for example 17190 it's the village Salt when ‘08’ it's Barcelona, ‘17’ it's Girona, ‘25’ it's Lleida and ‘43’ it's Tarragona, the 4 counties.

I would like to know how to split/reduce 17190 to 17, for the grouped by counties

Thanks in advance

答:
We can use substr for that:

```<code>substr(17190, start=1, stop=2)
</code>```

Returns:

```<code>[1] "17"
</code>```

Edit:

How to apply substr to a whole column:

```<code>substr(c(1234, 4567, 8910), start=1, stop=2)
</code>```

Returns:

```<code>[1] "12" "45" "89"
</code>```

or with a data.frame column:

```<code>iris$short_species <- substr(iris$Species, start=1, stop=2)
</code>```

Body:
We can use substr for that:

substr(17190, start=1, stop=2)

Returns:

[1] "17"

Edit:

How to apply substr to a whole column:

substr(c(1234, 4567, 8910), start=1, stop=2)

Returns:

[1] "12" "45" "89"

or with a data.frame column:

iris$short_species <- substr(iris$Species, start=1, stop=2)


问:
Why is the SSL configuration for Artifactory not working?
I am trying to configure Artifactory to work with SSL, the problem is that with some of the keystores he is starting up, but the web UI does not connect (I mean- if you want to open https://:8443), it will not show the welcome screen),  how can it be debugged to see what is causing it?</p>

答: I am not sure how to debug it, but the problem was resolved, I did not specify the correct value of the keystore alias</p>


问:
Append a numpy array with different first dimensions
My program creates a numpy array within a for loop. For example it creates array with shape (100*30*10), then (160*30*10) and then may be (120*30*10) . I have to append the above to an empty numpy array such that , at the end of the loop, it will be a numpy  array with shape (380*30*10) (i.e sum  of 100+160+120) . The second and third dimension doesnt change in the numpy array.

How can I do the above in python. I tried the following.

```<code>np_model = np.append(np_model,np_temp1)
print("Appended model shape is",np_model.shape)
np_label = np.append(np_label,np_temp2)
print("Appended label shape is",np_label.shape)
</code>```

The np_model is an empty array which I have defined as np_model = np.empty(1,30,10) and np_label as np_label = np.empty(1 ,str)

np_temp1 corresponds to array within each for loop like 100*30*10,120*30*10 etc and np_temp2 is a string with "item1","item2" etc

The np_label is a string numpy array with 1 label corresponding to np_temp1.shape[0]. But the result I get in np_model is flattened array with size 380*30*10 = 1140000

Any help is appreciated.

答:
you can use numpy concatenate function, append the output numpy(s) to a list and then feed it to the concatenate function:

```<code>empty_list = []
x = np.zeros([10, 20, 4])
y = np.zeros([12, 20, 4])
empty_list.append(x)
empty_list.append(y)
z = np.concatenate(empty_list, axis=0)
print(x.shape, y.shape, z.shape)
</code>```

(10, 20, 4) (12, 20, 4) (22, 20, 4)

Body:
My program creates a numpy array within a for loop. For example it creates array with shape (100*30*10), then (160*30*10) and then may be (120*30*10) . I have to append the above to an empty numpy array such that , at the end of the loop, it will be a numpy  array with shape (380*30*10) (i.e sum  of 100+160+120) . The second and third dimension doesnt change in the numpy array.

How can I do the above in python. I tried the following.

np_model = np.append(np_model,np_temp1)
print("Appended model shape is",np_model.shape)
np_label = np.append(np_label,np_temp2)
print("Appended label shape is",np_label.shape)

The np_model is an empty array which I have defined as np_model = np.empty(1,30,10) and np_label as np_label = np.empty(1 ,str)

np_temp1 corresponds to array within each for loop like 100*30*10,120*30*10 etc and np_temp2 is a string with "item1","item2" etc

The np_label is a string numpy array with 1 label corresponding to np_temp1.shape[0]. But the result I get in np_model is flattened array with size 380*30*10 = 1140000

Any help is appreciated.

Body:
you can use numpy concatenate function, append the output numpy(s) to a list and then feed it to the concatenate function:

empty_list = []
x = np.zeros([10, 20, 4])
y = np.zeros([12, 20, 4])
empty_list.append(x)
empty_list.append(y)
z = np.concatenate(empty_list, axis=0)
print(x.shape, y.shape, z.shape)

(10, 20, 4) (12, 20, 4) (22, 20, 4)


问:
numpy.corrcoeff() MemoryError
Can't understand MemoryError I get using numpy.corrcoeff() to find correlation coefficient between 2 vectors smin & smax as following:

```<code>import numpy as np
from numpy import random as rn
r=0.01
sigma=0.2
T=1
K=1
N=252
h=T/N
M  = 50000
Z = rn.randn(M,N)
S=np.ones((M,N+1))
smax=np.ones((M,1))
smin=np.ones((M,1))
for i in range(0,N):
    S[:,i+1]=S[:,i]*(np.exp((r-(sigma**2)/2)*h+sigma*Z[:,i]*np.sqrt(h)))
for j in range(0,M):
    smax[j,:]=np.exp(-r*T)*(np.max(S[j,:])>K)*(np.max(S[j,:])-K)
    smin[j,:]=np.exp(-r*T)*(np.min(S[j,:])<K)*(K-np.min(S[j,:]))
c=np.corrcoef(smax,smin)
print(c)
</code>```

if there is another way to find correlation coeff.,like using pandas it's also good.

答:
The shape of your arrays here is what is the problem. The function documentation states that x is a "1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables." and that y is an additional set of variables and observations. So this is trying to allocate an array of size (10000, 10000), which is huge.

If you just want to calculate the pearson correlation coefficient between two one dimensional vectors, you can use a much simpler formula than what is implemented here. This documentation has the formula I am referring to.

https://hydroerr.readthedocs.io/en/stable/api/HydroErr.HydroErr.pearson_r.html#HydroErr.HydroErr.pearson_r

But to be able to still use the numpy version you need to pass in the observations and predictions in the same parameter x, and x and y need to be 1D arrays.

```<code>import numpy as np

simulated_array = np.random.rand(50000)
observed_array = np.random.rand(50000)

c = np.corrcoef([simulated_array, observed_array])[1, 0]
</code>```

More explanation about this here.

Title: numpy.corrcoeff() MemoryError

Body:
Can't understand MemoryError I get using numpy.corrcoeff() to find correlation coefficient between 2 vectors smin & smax as following:

import numpy as np
from numpy import random as rn
r=0.01
sigma=0.2
T=1
K=1
N=252
h=T/N
M  = 50000
Z = rn.randn(M,N)
S=np.ones((M,N+1))
smax=np.ones((M,1))
smin=np.ones((M,1))
for i in range(0,N):
    S[:,i+1]=S[:,i]*(np.exp((r-(sigma**2)/2)*h+sigma*Z[:,i]*np.sqrt(h)))
for j in range(0,M):
    smax[j,:]=np.exp(-r*T)*(np.max(S[j,:])>K)*(np.max(S[j,:])-K)
    smin[j,:]=np.exp(-r*T)*(np.min(S[j,:])<K)*(K-np.min(S[j,:]))
c=np.corrcoef(smax,smin)
print(c)

if there is another way to find correlation coeff.,like using pandas it's also good.

Body:
The shape of your arrays here is what is the problem. The function documentation states that x is a "1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables." and that y is an additional set of variables and observations. So this is trying to allocate an array of size (10000, 10000), which is huge.

If you just want to calculate the pearson correlation coefficient between two one dimensional vectors, you can use a much simpler formula than what is implemented here. This documentation has the formula I am referring to.

https://hydroerr.readthedocs.io/en/stable/api/HydroErr.HydroErr.pearson_r.html#HydroErr.HydroErr.pearson_r

But to be able to still use the numpy version you need to pass in the observations and predictions in the same parameter x, and x and y need to be 1D arrays.

import numpy as np

simulated_array = np.random.rand(50000)
observed_array = np.random.rand(50000)

c = np.corrcoef([simulated_array, observed_array])[1, 0]

More explanation about this here.


问:
Is it worth learning Smarty for PHP templating?
I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?</p>

答: Smarty is template engine easy to learn and use, but I strongly recommend learning and  using Twig instead.


问:
opa5 sap.ui.test.matchers.AggregationLengthEquals not workung
i am setting up some opa 5 tests on a sap.ui.table.Table and i need to test the result of applying a filter to the table.

i know home many rows should display in the result so i use sap.ui.test.matchers.AggregationLengthEquals to test.

but, sap.ui.test.matchers.AggregationLengthEquals only seems to return the total number of rows in the table, ie it includes the 'hidden' rows.

am i mis-understanding what sap.ui.test.matchers.AggregationLengthEquals does?

note, i am using a JSON data model.

cheers

pas.

答:
To clarify lets consider a table (sap.ui.table.Table) and we want to verify/test if it has n rows. We create the function test something like this:

```<code>test: function(tableId,n){
        var ag = new sap.ui.test.matchers.AggregationLengthEquals({name:"rows",length: n});
        var table = this.byId(tableId);
        result = ag.isMatching(table);
        return result;
}
</code>```

To actually test use method isMatching() against your controller. The method above return a boolean value representing if indeed the table with tableId has the length of aggregation rows equal with n. Note that the method will consider all rows of the table (the model associated) not only the displayed ones.

I hope this answer helps to clarify your problem.

Body:
To clarify lets consider a table (sap.ui.table.Table) and we want to verify/test if it has n rows. We create the function test something like this:

test: function(tableId,n){
        var ag = new sap.ui.test.matchers.AggregationLengthEquals({name:"rows",length: n});
        var table = this.byId(tableId);
        result = ag.isMatching(table);
        return result;
}

To actually test use method isMatching() against your controller. The method above return a boolean value representing if indeed the table with tableId has the length of aggregation rows equal with n. Note that the method will consider all rows of the table (the model associated) not only the displayed ones.

I hope this answer helps to clarify your problem.


问:
Mismatch in number of detected contours in OpenCV
As per the documentation, the function cvFindContours() returns the number of retrieved contours from the binary image input. However when I'm running a loop over all the contours the number of detected contours is drastically less.

A possible reason would be that child contours of a parent, as well as holes are being counted in the return value of the function. Even so this number is not matching a reasonable eye-estimate of the pictures used by me.

The return value in this case is 92, whereas in traversing all the contours there are 15 distinct contours.

Here's the code:

```<code>int n = cvFindContours(img_canny_mop, mem, &contours, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
printf("No of retrieved contours = %d",n);
for (ptr = contours; ptr != NULL; ptr = ptr->h_next)
{
        ext_color = CV_RGB( rand()&255, rand()&255, rand()&255 ); //randomly coloring different contours
        cvDrawContours(cc_color, ptr, ext_color, CV_RGB(0,0,0), -1, CV_FILLED, 8, cvPoint(0,0));
        //display( cc_color, "CCs");
        n_cont++;
}
cvSaveImage("CC_colors.jpg",cc_color);
printf("\nNo of contours = %d",n_cont);
</code>```

The images are:

Input: http://imageshack.us/photo/my-images/811/cannymop.jpg/

Randomly colored contours: http://imageshack.us/photo/my-images/819/cccolors.jpg/

答:
You may want to look at the documentation here. The key part being the following.

The pointer firstContour is filled by
the function. It will contain pointer
to the first most outer contour or
NULL if no contours is detected (if
the image is completely black). Other
contours may be reached from
firstContour using h_next and v_next
links.

May be you need to check the number of v_next for each h_next (or vice versa).

Body:
As per the documentation, the function cvFindContours() returns the number of retrieved contours from the binary image input. However when I'm running a loop over all the contours the number of detected contours is drastically less.

A possible reason would be that child contours of a parent, as well as holes are being counted in the return value of the function. Even so this number is not matching a reasonable eye-estimate of the pictures used by me.

The return value in this case is 92, whereas in traversing all the contours there are 15 distinct contours.

Here's the code:

int n = cvFindContours(img_canny_mop, mem, &contours, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
printf("No of retrieved contours = %d",n);
for (ptr = contours; ptr != NULL; ptr = ptr->h_next)
{
        ext_color = CV_RGB( rand()&255, rand()&255, rand()&255 ); //randomly coloring different contours
        cvDrawContours(cc_color, ptr, ext_color, CV_RGB(0,0,0), -1, CV_FILLED, 8, cvPoint(0,0));
        //display( cc_color, "CCs");
        n_cont++;
}
cvSaveImage("CC_colors.jpg",cc_color);
printf("\nNo of contours = %d",n_cont);

The images are:

Input: http://imageshack.us/photo/my-images/811/cannymop.jpg/

Randomly colored contours: http://imageshack.us/photo/my-images/819/cccolors.jpg/


问:
Use a formula to organize columns with different amounts of data
When each column is recorded, the values are different sizes:

I would like the values to be pulled to the left so that one column is always well adjusted with the others:

Is there any way to do this using a formula?

link to Spreadsheet:

https://docs.google.com/spreadsheets/d/1iXqdjs_D-NvyES4LMjpzFEY4uDvbdcMZZY5VUvpmbRQ/edit?usp=sharing

答:
values to be pulled to the left

```<code>=ARRAYFORMULA(SUBSTITUTE(SPLIT(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
 SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)), " "), "♦", " "))
</code>```

while equal distribution would be:

```<code>={FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-1, 4)=0),
  FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-2, 4)=0),
  FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-3, 4)=0),
  FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-4, 4)=0)}
</code>```

note that =COUNTA(A1:D12)/4 needs to be a whole number otherwise you will get ARRAY error. to avoid ARRAY error you can use 1 formula per column. paste in A column and drag it till you reach D column:

```<code>=FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF($A$1:$D$12<>"",
 SUBSTITUTE($A$1:$D$12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
 MOD(ROW(INDIRECT("A1:A"&COUNTA($A$1:$D$12)))-COLUMN(A1), 4)=0)
</code>```

Body:
values to be pulled to the left

=ARRAYFORMULA(SUBSTITUTE(SPLIT(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
 SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)), " "), "♦", " "))

while equal distribution would be:

={FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-1, 4)=0),
  FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-2, 4)=0),
  FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-3, 4)=0),
  FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(A1:D12<>"",
  SUBSTITUTE(A1:D12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
  MOD(ROW(INDIRECT("A1:A"&COUNTA(A1:D12)))-4, 4)=0)}

note that =COUNTA(A1:D12)/4 needs to be a whole number otherwise you will get ARRAY error. to avoid ARRAY error you can use 1 formula per column. paste in A column and drag it till you reach D column:

=FILTER(SUBSTITUTE(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF($A$1:$D$12<>"",
 SUBSTITUTE($A$1:$D$12, " ", "♦"), )),,999^99)),,999^99), " ")), "♦", " "),
 MOD(ROW(INDIRECT("A1:A"&COUNTA($A$1:$D$12)))-COLUMN(A1), 4)=0)


问:
Compound configuration in intellij
I have several applications. Each of them is deployed in its own application server. It's done this way because it minimizes time to redeploy each application when a change is made only in that application. This is because only one app server with one application will be restarted, which takes less time.

Anyway, I need to start all of those application servers in a certain order and in debug mode. Intellij IDEA has a compound configuration which allows you to start multiple applications. But it has 2 significant flaws: it doesn't allow you to specify the order in which applications should be started and it seems to not allow to start them in debug mode. So is it possible to somehow achieve those goals?

答:
You can add tasks to a Run/Debug configuration and configure their order with before launch options.

https://www.jetbrains.com/help/idea/run-launcher.html#before-launch-options
https://youtrack.jetbrains.com/issue/IDEA-181164

Title: Compound configuration in intellij


问:
How to specify the model version label in a REST API request?
As described in the documentation, using the version_labels field, you can specify a label to a model version in order to handle canary deployments.

https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/serving_config.md#assigning-string-labels-to-model-versions-to-simplify-canary-and-rollback

For example, you can have model 43 labeled as stable and model 44 labeled as canary.

That feature sounds really neat, but I did not find in the doc how to adapt my POST request to specify the label I want to use.

Until now, I was using something of the sort:

```<code>curl -d '{"instances": <<my input data>>}' -X POST http://localhost:8501/v1/models/<<my model name>>:predict
</code>```

Any idea ?

答:
Update:

Based on comments on this GitHub Issue, @misterpeddy states that, as of August 14th 2019:

Re: not being able to access the version using labels via HTTP - this is something that's not possible today (AFAIR) - only through the grpc interface can you declare labels :(

To the best of my knowledge, this feature is yet to be implemented.

Original Answer:

It looks like the current implementation of the HTTP API Handler expects the version to be numeric.

You can see the regular expression that attempts to parse the URL here.

prediction_api_regex_(
          R"((?i)/v1/models/([^/:]+)(?:/versions/(\d+))?:(classify|regress|predict))")
```

The \d defines an expectation for a numeric version indicator rather than a text label.

I've opened a corresponding TensorFlow Serving issue here.

Body:
As described in the documentation, using the version_labels field, you can specify a label to a model version in order to handle canary deployments.

https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/serving_config.md#assigning-string-labels-to-model-versions-to-simplify-canary-and-rollback

For example, you can have model 43 labeled as stable and model 44 labeled as canary.

That feature sounds really neat, but I did not find in the doc how to adapt my POST request to specify the label I want to use.

Until now, I was using something of the sort:

curl -d '{"instances": <<my input data>>}' -X POST http://localhost:8501/v1/models/<<my model name>>:predict

Any idea ?

Body:
Update:

Based on comments on this GitHub Issue, @misterpeddy states that, as of August 14th 2019:

Re: not being able to access the version using labels via HTTP - this is something that's not possible today (AFAIR) - only through the grpc interface can you declare labels :(

To the best of my knowledge, this feature is yet to be implemented.

Original Answer:

It looks like the current implementation of the HTTP API Handler expects the version to be numeric.

You can see the regular expression that attempts to parse the URL here.

prediction_api_regex_(
          R"((?i)/v1/models/([^/:]+)(?:/versions/(\d+))?:(classify|regress|predict))")

The \d defines an expectation for a numeric version indicator rather than a text label.

I've opened a corresponding TensorFlow Serving issue here.


问:
How to display json data in a reactjs component
I'm new to react. I dont know how to import json data in one of my component.

This is my json data:

```<code>[
    {
        "id": 1,
        "firstname": "abc",
        "lastname": "xyz",
        "phone": "+91 789654123",
        "email": "abcyz@gmail.com"
    },
    {
        "id": 2,
        "firstname": "def",
        "lastname": "uvz",
        "phone": "+91 123456987",
        "email": "defvu@gmail.com"
    }
]
</code>```

Here is list Component :

```<code><Container>
  <Grid>
    <Grid.Row>
      <Grid.Column>
        <Header>List</Header>
        <List>
          <List.Item block>
            <List.Content>FirstName and Last Name</List.Content>
            <List.Content>Phone</List.Content>
          </List.Item>
        </List>
      </Grid.Column>
    </Grid.Row>
  </Grid>
</Container>
</code>```

Can anyone help me in displaying the list? Thanks in advance

答:
constructor(props) {
super(props);
this.state = {
  loadedList: [],
  lists: [],
};
  }

componentDidMount() {

  // after 3001/ write your .json file directory

  axios.get('http://localhost:3001/../static/data/terrifdata.json')
      .then(response => {
       this.setState({
         lists: response.data,
         loadedList: response.data,
         isLoading: false
        })
    })
 }

{loadedList.map((postDetail, index) => {
                    return (

                     {postDetail.name}

                  )}
               }

```

Body:
I'm new to react. I dont know how to import json data in one of my component.

This is my json data:

[
    {
        "id": 1,
        "firstname": "abc",
        "lastname": "xyz",
        "phone": "+91 789654123",
        "email": "abcyz@gmail.com"
    },
    {
        "id": 2,
        "firstname": "def",
        "lastname": "uvz",
        "phone": "+91 123456987",
        "email": "defvu@gmail.com"
    }
]

Here is list Component :

<Container>
  <Grid>
    <Grid.Row>
      <Grid.Column>
        List
        <List>
          <List.Item block>
            <List.Content>FirstName and Last Name</List.Content>
            <List.Content>Phone</List.Content>
          </List.Item>
        </List>
      </Grid.Column>
    </Grid.Row>
  </Grid>
</Container>

Can anyone help me in displaying the list? Thanks in advance

Body:
constructor(props) {
super(props);
this.state = {
  loadedList: [],
  lists: [],
};
  }

componentDidMount() {

  // after 3001/ write your .json file directory

  axios.get('http://localhost:3001/../static/data/terrifdata.json')
      .then(response => {
       this.setState({
         lists: response.data,
         loadedList: response.data,
         isLoading: false
        })
    })
 }

<div>
{loadedList.map((postDetail, index) => {
                    return (
                  <h5>
                     {postDetail.name}
                  </h5>
                  )}
               }
</div>


问:
What is the behavior of the vector here?
I am unable to comprehend why in the test shown below, iterator p never reaches the end and therefore the loop breaks only when k = 20? What exactly is the push_back doing to cause undefined behavior? Is it because the vector dynamically allocated a bunch of additional storage for the new elements I want to use, and the amount is not necessarily the amount I will use?</p>

```<code>#include <iostream>
#include <vector>
#include <list>
using namespace std;

const int MAGIC = 11223344;

void test()
{
    bool allValid = true;

    int k = 0;
    vector<int> v2(5, MAGIC);
    k = 0;
    for (vector<int>::iterator p = v2.begin(); p != v2.end(); p++, k++)
    {
        if (k >= 20)  // prevent infinite loop
            break;
        if (*p != MAGIC)
        {
            cout << "Item# " << k << " is " << *p << ", not " << MAGIC <<"!" << endl;
            allValid = false;
        }
        if (k == 2)
        {
            for (int i = 0; i < 5; i++)
                v2.push_back(MAGIC);
        }
    }
    if (allValid  &&  k == 10)
        cout << "Passed test 3" << endl;
    else
        cout << "Failed test 3"  << "\n" <<  k << endl;
}

int main()
{
    test();
}
</code>```

答:
Insertion to a vector while iterating over it is really a bad idea. Data insertion may cause memory reallocation that invalidates iterators. In this case, the capacity was not enough to insert additional elements, which caused memory allocation with a different address. You can check it yourself:

```<code>void test()
{
    bool allValid = true;
    int k = 0;
    vector<int> v2(5, MAGIC);
    k = 0;

    for (vector<int>::iterator p = v2.begin(); p != v2.end(); p++, k++)
    {
        cout << v2.capacity() << endl; // Print the vector capacity

        if (k >= 20)  // prevent infinite loop
            break;

        if (*p != MAGIC) {
            //cout << "Item# " << k << " is " << *p << ", not " << MAGIC <<"!" << endl;
            allValid = false;
        }
        if (k == 2) {
            for (int i = 0; i < 5; i++)
                v2.push_back(MAGIC);
        }
    }
    if (allValid && k == 10)
        cout << "Passed test 3" << endl;
    else
        cout << "Failed test 3" << "\n" << k << endl;
}
</code>```

This code will output something like the following:

```<code>5
5
5
10 <-- the capacity has changed
10
... skipped ...
10
10
Failed test 3
20
</code>```

We can see that where k is equal to 2  (third line), the capacity of the vector doubled (fourth line) because we are adding new elements. The memory is redistributed, and the vector elements are most likely now located elsewhere. You can also check it by printing vector base address with data member function instead of capacity:

```<code>Address: 0x136dc20 k: 0
Address: 0x136dc20 k: 1
Address: 0x136dc20 k: 2
Address: 0x136e050 k: 3 <-- the address has changed
Address: 0x136e050 k: 4
... skipped ...
Address: 0x136e050 k: 19
Address: 0x136e050 k: 20
Failed test 3
20
</code>```

The code is poorly written, you can make it more robust by using indices instead of iterators.

Body:
I am unable to comprehend why in the test shown below, iterator p never reaches the end and therefore the loop breaks only when k = 20? What exactly is the push_back doing to cause undefined behavior? Is it because the vector dynamically allocated a bunch of additional storage for the new elements I want to use, and the amount is not necessarily the amount I will use?

#include <iostream>
#include <vector>
#include <list>
using namespace std;

const int MAGIC = 11223344;

void test()
{
    bool allValid = true;

    int k = 0;
    vector<int> v2(5, MAGIC);
    k = 0;
    for (vector<int>::iterator p = v2.begin(); p != v2.end(); p++, k++)
    {
        if (k >= 20)  // prevent infinite loop
            break;
        if (*p != MAGIC)
        {
            cout << "Item# " << k << " is " << *p << ", not " << MAGIC <<"!" << endl;
            allValid = false;
        }
        if (k == 2)
        {
            for (int i = 0; i < 5; i++)
                v2.push_back(MAGIC);
        }
    }
    if (allValid  &&  k == 10)
        cout << "Passed test 3" << endl;
    else
        cout << "Failed test 3"  << "\n" <<  k << endl;
}

int main()
{
    test();
}

Body:
Insertion to a vector while iterating over it is really a bad idea. Data insertion may cause memory reallocation that invalidates iterators. In this case, the capacity was not enough to insert additional elements, which caused memory allocation with a different address. You can check it yourself:

void test()
{
    bool allValid = true;
    int k = 0;
    vector<int> v2(5, MAGIC);
    k = 0;

    for (vector<int>::iterator p = v2.begin(); p != v2.end(); p++, k++)
    {
        cout << v2.capacity() << endl; // Print the vector capacity

        if (k >= 20)  // prevent infinite loop
            break;

        if (*p != MAGIC) {
            //cout << "Item# " << k << " is " << *p << ", not " << MAGIC <<"!" << endl;
            allValid = false;
        }
        if (k == 2) {
            for (int i = 0; i < 5; i++)
                v2.push_back(MAGIC);
        }
    }
    if (allValid && k == 10)
        cout << "Passed test 3" << endl;
    else
        cout << "Failed test 3" << "\n" << k << endl;
}

This code will output something like the following:

5
5
5
10 <-- the capacity has changed
10
... skipped ...
10
10
Failed test 3
20

We can see that where k is equal to 2  (third line), the capacity of the vector doubled (fourth line) because we are adding new elements. The memory is redistributed, and the vector elements are most likely now located elsewhere. You can also check it by printing vector base address with data member function instead of capacity:

Address: 0x136dc20 k: 0
Address: 0x136dc20 k: 1
Address: 0x136dc20 k: 2
Address: 0x136e050 k: 3 <-- the address has changed
Address: 0x136e050 k: 4
... skipped ...
Address: 0x136e050 k: 19
Address: 0x136e050 k: 20
Failed test 3
20

The code is poorly written, you can make it more robust by using indices instead of iterators.


问:
Getting error when calling a method inside observable which returns another observable
I am new to angular and observable. I have tried flatMap, swithMap and concatMap, but nothing helps.  I have got the error " You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable." When the code of switch case 1 runs of inputprocessing method,while the default case works completely fine.

app.component.ts

```<code> export class AppComponent implements OnInit, AfterViewChecked, OnChanges {
  ProcessInput(input: string, session: string): void {
    this.appService
      .ProcessInput(input, session)//this works fine and returns the response.
      .pipe(
        concatMap((res: any) => {
          return this.inputProcessing.inputProcessing(res);
        })
      )
      .subscribe(
        res => {
          this.arr.push("TEST");
        },
        err => {
          console.log(err);
        }
      );
  }
  }
</code>```

inputprocessing.service.ts

```<code>import "reflect-metadata";
import { Injectable } from "@angular/core";
import { Container, inject, injectable, AsyncContainerModule } from "inversify";
import { OutputResponse } from "../response";
import { PrescriptionStatus } from "src/Classes/PrescriptionStatus";
import { service } from "./service.service";
import { HttpClient } from "@angular/common/http";
import { CourierMode } from "../enums/CourierMode";
import { Observable, of } from "rxjs";
import { switchMap, flatMap, concatMap } from "rxjs/operators";
import { PrescriptionStatusMain } from "src/models/PrescriptionStatusResponse";

@Injectable({
  providedIn: "root"
})
export class InputprocessingService {
  constructor(private service: service,private http: HttpClient) {}

  responseText: string;
  returnMessage: string;
  inputProcessing(response: OutputResponse): Observable<any> {

    this.responseText = response.output.generic[0].text;
    //works completely fine with default case, but when case 1: runs it gave an error
    switch (this.responseText) {
      case "1": {

        const obsFail = new Observable(observer => {
          observer.next(this.returnMessage);
          observer.error();
          observer.complete();
        });

        this.service.getStatus().pipe(
          concatMap((res: StatusMain) => {
            return obsFail ;
          })
        );
        break;
      }

      default: {
        const obs = new Observable(observer => {
          observer.next(this.responseText);
          observer.complete();
        });
        return obs;
      }
    }
  }
}
</code>```

service.ts

```<code>import * as request from "request";
import * as request_promise from "request-promise-native";
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { StatusMain } from "src/models/StatusResponse";
import { Observable } from "rxjs";
@Injectable()
export class service {
  constructor(private http: HttpClient) {}

  getStatus(): Observable<StatusMain> {
    const body = { bdate: "1999/05/01" };
    return this.http.post<StatusMain>(
      "http://localhost:49995/api/Status",
      body
    );
  }
}
</code>```

答:
inputProcessing function in your service needs to return an observable. With your implementation the created observable only emits the value, while the concatMap expects an observable. Hence the error: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Try this:

 export class AppComponent implements OnInit, AfterViewChecked, OnChanges {
  ProcessInput(input: string, session: string): void {
    this.appService
      .ProcessInput(input, session)//this works fine and returns the response.
      .pipe(
        flatMap((res: any) => {
          return this.inputProcessing.inputProcessing(res);
        })
      )
      .subscribe(
        res => {
          this.arr.push("TEST");
        },
        err => {
          console.log(err);
        }
      );
   }
  }

```

<p>And in your service:</p>

<pre class="lang-js prettyprint-override"><code>@Injectable({
  providedIn: "root"
})
export class InputprocessingService {
  constructor(private service: service,private http: HttpClient) {}

  responseText: string;
  returnMessage: string;
  inputProcessing(response: OutputResponse): Observable<any> {

    this.responseText = response.output.generic[0].text;
    let returnObservable;

    //works completely fine with default case, but when case 1: runs it gave an error
    switch (this.responseText) {
      case "1": {

        const obsFail = new Observable(observer => {
          observer.next(this.returnMessage);
          observer.error();
          observer.complete();
        });

        returnObservable = this.service.getStatus().pipe(
          concatMap((res: StatusMain) => {
            return obsFail ;
          })
        );
        break;
      }

      default: {
        returnObservable = new Observable(observer => {
          observer.next(this.responseText);
          observer.complete();
        });
      }
    }

    return returnObservable;
  }
}
</code>```

Note how AppComponent implements flatMap. flatmap must return an observable. Hence inputProcessing creates a local variable (returnObservable) which holds a reference to different observables (switch statement: case1, case2... default).

When the inner observables emit value, then returnObservable emits that value to the outer flatMap.

Body:
I am new to angular and observable. I have tried flatMap, swithMap and concatMap, but nothing helps.  I have got the error " You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable." When the code of switch case 1 runs of inputprocessing method,while the default case works completely fine.

app.component.ts

 export class AppComponent implements OnInit, AfterViewChecked, OnChanges {
  ProcessInput(input: string, session: string): void {
    this.appService
      .ProcessInput(input, session)//this works fine and returns the response.
      .pipe(
        concatMap((res: any) => {
          return this.inputProcessing.inputProcessing(res);
        })
      )
      .subscribe(
        res => {
          this.arr.push("TEST");
        },
        err => {
          console.log(err);
        }
      );
  }
  }

inputprocessing.service.ts

import "reflect-metadata";
import { Injectable } from "@angular/core";
import { Container, inject, injectable, AsyncContainerModule } from "inversify";
import { OutputResponse } from "../response";
import { PrescriptionStatus } from "src/Classes/PrescriptionStatus";
import { service } from "./service.service";
import { HttpClient } from "@angular/common/http";
import { CourierMode } from "../enums/CourierMode";
import { Observable, of } from "rxjs";
import { switchMap, flatMap, concatMap } from "rxjs/operators";
import { PrescriptionStatusMain } from "src/models/PrescriptionStatusResponse";

@Injectable({
  providedIn: "root"
})
export class InputprocessingService {
  constructor(private service: service,private http: HttpClient) {}

  responseText: string;
  returnMessage: string;
  inputProcessing(response: OutputResponse): Observable<any> {

    this.responseText = response.output.generic[0].text;
    //works completely fine with default case, but when case 1: runs it gave an error
    switch (this.responseText) {
      case "1": {

        const obsFail = new Observable(observer => {
          observer.next(this.returnMessage);
          observer.error();
          observer.complete();
        });

        this.service.getStatus().pipe(
          concatMap((res: StatusMain) => {
            return obsFail ;
          })
        );
        break;
      }

      default: {
        const obs = new Observable(observer => {
          observer.next(this.responseText);
          observer.complete();
        });
        return obs;
      }
    }
  }
}

service.ts

import * as request from "request";
import * as request_promise from "request-promise-native";
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { StatusMain } from "src/models/StatusResponse";
import { Observable } from "rxjs";
@Injectable()
export class service {
  constructor(private http: HttpClient) {}

  getStatus(): Observable<StatusMain> {
    const body = { bdate: "1999/05/01" };
    return this.http.post<StatusMain>(
      "http://localhost:49995/api/Status",
      body
    );
  }
}

Body:
inputProcessing function in your service needs to return an observable. With your implementation the created observable only emits the value, while the concatMap expects an observable. Hence the error: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Try this:

 export class AppComponent implements OnInit, AfterViewChecked, OnChanges {
  ProcessInput(input: string, session: string): void {
    this.appService
      .ProcessInput(input, session)//this works fine and returns the response.
      .pipe(
        flatMap((res: any) => {
          return this.inputProcessing.inputProcessing(res);
        })
      )
      .subscribe(
        res => {
          this.arr.push("TEST");
        },
        err => {
          console.log(err);
        }
      );
   }
  }

And in your service:

@Injectable({
  providedIn: "root"
})
export class InputprocessingService {
  constructor(private service: service,private http: HttpClient) {}

  responseText: string;
  returnMessage: string;
  inputProcessing(response: OutputResponse): Observable<any> {

    this.responseText = response.output.generic[0].text;
    let returnObservable;

    //works completely fine with default case, but when case 1: runs it gave an error
    switch (this.responseText) {
      case "1": {

        const obsFail = new Observable(observer => {
          observer.next(this.returnMessage);
          observer.error();
          observer.complete();
        });

        returnObservable = this.service.getStatus().pipe(
          concatMap((res: StatusMain) => {
            return obsFail ;
          })
        );
        break;
      }

      default: {
        returnObservable = new Observable(observer => {
          observer.next(this.responseText);
          observer.complete();
        });
      }
    }

    return returnObservable;
  }
}

Note how AppComponent implements flatMap. flatmap must return an observable. Hence inputProcessing creates a local variable (returnObservable) which holds a reference to different observables (switch statement: case1, case2... default).

When the inner observables emit value, then returnObservable emits that value to the outer flatMap.


问:
Crystal Report text functions
i'm using ItemName field in a Crystal Report. The field contains the item name and dimensions: -

Egg Pot & Saucer 47x41cm

I wish to suppress the dimension details, leaving just the text part of the string.
I'm looking for a set of functions that could create a formula in Crystal to do this.
The issue is the there are many different syntax for the dimension part: -

65x47x30cm or 43cm or  47x41cm

The constant is that they all start with a Numeric.

答:
I think using a combination of crystals string functions (Instr,Left,Length,Replace etc) you should be able to accomplish this.

What have you tried so far?

would any of the required info (Egg Pot & Saucer) contain numbers?

if not, find the first occurrence of a number using a loop and isNumeric

then use LEFT to return everything before that number.

```<code>Local StringVar f := {Command.ItemName} ;
local Numbervar L := length(f) ;
Local Numbervar i ;
Local StringVar s ;
for i := 1 to L do
(
( If IsNumeric(f[i]) then exit for )
);
Left ({Command.CardName},i -1)
</code>```

updated with additional condition:

```<code>Local StringVar f := {Command.CardName} ;
local Numbervar L := length(f) ;
Local Numbervar i ;
Local StringVar OutPut ;

If {Command.CardName} like "* Set *"  Then
f
else
(for i := 1 to L do
( If IsNumeric(f[i]) then exit for);
 OutPut:= Left({Command.CardName},i -1);)

</code>```

Title: Crystal Report text functions

Body:
I think using a combination of crystals string functions (Instr,Left,Length,Replace etc) you should be able to accomplish this.

What have you tried so far?

would any of the required info (Egg Pot & Saucer) contain numbers?

if not, find the first occurrence of a number using a loop and isNumeric

then use LEFT to return everything before that number.

Local StringVar f := {Command.ItemName} ;
local Numbervar L := length(f) ;
Local Numbervar i ;
Local StringVar s ;
for i := 1 to L do
(
( If IsNumeric(f[i]) then exit for )
);
Left ({Command.CardName},i -1)

updated with additional condition:

Local StringVar f := {Command.CardName} ;
local Numbervar L := length(f) ;
Local Numbervar i ;
Local StringVar OutPut ;

If {Command.CardName} like "* Set *"  Then
f
else
(for i := 1 to L do
( If IsNumeric(f[i]) then exit for);
 OutPut:= Left({Command.CardName},i -1);)


答:
You can use aggregation and filter with a having clause:

```<code>select weekending
from mytable
group by weekending
having min(isapproved) = 1
</code>```

This works because isapproved only has 0/1 values. So condition min(isapproved) = 1 actually ensures that there is no 0 value.

Title: How to get weekending having all approved records?

Body:
I have a table like below

date      |    weekending   |    isapproved

2/17/2020     2/23/2020            0
2/18/2020     2/23/2020            1
2/19/2020     2/23/2020            0
2/20/2020     2/23/2020            0
2/27/2020     3/1/2020             1
2/26/2020     3/1/2020             1
2/28/2020     3/1/2020             1
3/4/2020      3/8/2020             0
3/5/2020      3/8/2020             1
3/5/2020      3/8/2020             1

now want to get weekending '3/1/2020' since it have all 1's in isApproved like this I want to get list of weekending having all 1's in isApproved

Body:
You can use aggregation and filter with a having clause:

select weekending
from mytable
group by weekending
having min(isapproved) = 1

This works because isapproved only has 0/1 values. So condition min(isapproved) = 1 actually ensures that there is no 0 value.


问:
Given an array of integers, find the first missing positive integer in linear time and constant space
In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
This question was asked by Stripe in it's programming interview. I have devised a solution for the same as below:

```<code>#include<bits/stdc++.h>
using namespace std;

int main(){
    int arr[]={1,-1,-5,-3,3,4,2,8};
    int size= sizeof(arr)/sizeof(arr[0]);
    sort(arr, arr+size);
    int min=1;

    for(int i=0; i<size; i++){
        if(arr[i]>min) break;
        if(arr[i]==min) min=min+1;
    }
    cout<<min;
    return 0;
}
</code>```

Here, I am first sorting the array, and then traversing the array once. Before traversing the array, I have initialized a variable named "min" as 1. Now, while traversing the array, when we get an integer that is equal to min, we simply increment the value of min. This ensures that the min variable hold the latest least positive integer that has not occurred yet.
Can you think of any better approach? Thanks in advance.

答:
This is in Java. Time complexity f O(N) and space complexity O(1)</p>

```<code>private static int minimum_positive_integer(int[] arr) {
        int i = 0;
        int j = arr.length - 1;

        //splitting array
        while (i < j) {
            if (arr[i] > 0) {
                i++;
            }

            if (arr[j] <= 0) {
                j--;
            }

            if (arr[i] <= 0 && arr[j] > 0) {
                int t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;

                i++;
                j--;
            }
        }
        int len_positive = i;

        if (arr[i] > 0) len_positive++;

        for (i = 0; i < len_positive; i++) {
            int abs = Math.abs(arr[i]);
            if (abs <= len_positive) {
                int index = abs - 1;
                arr[index] = -abs;
            }
        }

        for (i = 0; i < len_positive; i++) {
            if(arr[i] > 0) return  i + 1;
        }

        return len_positive + 1;
    }
</code>```

Body:
In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
This question was asked by Stripe in it's programming interview. I have devised a solution for the same as below:

#include<bits/stdc++.h>
using namespace std;

int main(){
    int arr[]={1,-1,-5,-3,3,4,2,8};
    int size= sizeof(arr)/sizeof(arr[0]);
    sort(arr, arr+size);
    int min=1;

    for(int i=0; i<size; i++){
        if(arr[i]>min) break;
        if(arr[i]==min) min=min+1;
    }
    cout<<min;
    return 0;
}

Here, I am first sorting the array, and then traversing the array once. Before traversing the array, I have initialized a variable named "min" as 1. Now, while traversing the array, when we get an integer that is equal to min, we simply increment the value of min. This ensures that the min variable hold the latest least positive integer that has not occurred yet.
Can you think of any better approach? Thanks in advance.

Body:
This is in Java. Time complexity f O(N) and space complexity O(1)

private static int minimum_positive_integer(int[] arr) {
        int i = 0;
        int j = arr.length - 1;

        //splitting array
        while (i < j) {
            if (arr[i] > 0) {
                i++;
            }

            if (arr[j] <= 0) {
                j--;
            }

            if (arr[i] <= 0 && arr[j] > 0) {
                int t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;

                i++;
                j--;
            }
        }
        int len_positive = i;

        if (arr[i] > 0) len_positive++;

        for (i = 0; i < len_positive; i++) {
            int abs = Math.abs(arr[i]);
            if (abs <= len_positive) {
                int index = abs - 1;
                arr[index] = -abs;
            }
        }

        for (i = 0; i < len_positive; i++) {
            if(arr[i] > 0) return  i + 1;
        }

        return len_positive + 1;
    }


问:
Keras fit generator - ValueError: Failed to find data adapter that can handle input
i'm trying to fit my deep learning model with a custom generator.

When i fit the model, it shows me this error:

I tried to find similar questions, but all the answers were about converting lists to numpy array. I think that's not the question in this error. My lists are all in numpy array format. This custom generator is based on a custom generator from  here

This is the part of code where I fit the model:

```<code>        train_generator = RepresentationGenerator(representation_path=representations_path, target_path=target_path,
                                              filenames=training_filenames, batch_size=batch_size)
    val_generator = RepresentationGenerator(representation_path=representations_path, target_path=target_path,
                                            filenames=validation_filenames, batch_size=batch_size)
    self.model_semantic.fit_generator(train_generator,
                            epochs=10,
                            verbose=1,
                            validation_data=val_generator,
                            )
    return 0
</code>```

where the variables are:

representations_path - is a string with the directory to the path where i store the training files, that which file is the input to model

target_path - is a string with the directory to the path where i store the target files, that which file is the target of the model (output)

training_filenames - is a list with the names of training and target files (both have the same name, but they are in different folders)

batch_size - integer with the size of the batch. It has the value 7.

My generator class is below:

```<code>import np
from tensorflow_core.python.keras.utils.data_utils import Sequence
</code>```

```<code>class RepresentationGenerator(Sequence):

    def __init__(self, representation_path, target_path, filenames, batch_size):
        self.filenames = np.array(filenames)
        self.batch_size = batch_size
        self.representation_path = representation_path
        self.target_path = target_path

    def __len__(self):
        return (np.ceil(len(self.filenames) / float(self.batch_size))).astype(np.int)

    def __getitem__(self, idx):
        files_to_batch = self.filenames[idx * self.batch_size: (idx + 1) * self.batch_size]
        batch_x, batch_y = [], []
        for file in files_to_batch:
            batch_x.append(np.load(self.representation_path + file + ".npy", allow_pickle=True))
            batch_y.append(np.load(self.target_path + file + ".npy", allow_pickle=True))

        return np.array(batch_x), np.array(batch_y)
</code>```

These are the values, when the method fit is called:

How can I fix this error?

Thank you mates!

When I call the method fit_generator, it calls the method fit.

The method fit, calls the method func.fit and it passes the variable Y that is set as None

The error occurs in this line:

答:
Final solution:

Import from the correct place:

```<code>from tensorflow.keras.utils import Sequence
</code>```

Old answers:

If __getitem__ is never called, the problem might be in __len__. You're not returning an int, you're returning a np.int.

I suggest you try:

```<code>def __len__(self):
    length = len(self.filenames) // self.batch_size
    if len(self.filenames) % self.batch_size > 0:
        length += 1

    return length
</code>```

But if __getitem__ is being called and your data returned, then you should inspect your arrays.

Get an item from the generator yourself and check the content:

```<code>x, y = train_generator[0]
</code>```

Are they single arrays? Or are they arrays of arrays? (Must be single)

What are their shapes? Do they have the expected shapes?

What are their types? Usually they should be float, sometimes int (for inputs to embedding layers), very rarely string (for inputs to custom layers that know how to treat strings).

The outputs must always be float, at most int (for sparse losses)

Other suppositions, you're using fit with batch_size while using a generator.... this is strange and the "if" clauses inside the method may not be well prepared, you might be falling into another training case.

Go straight to the usual options:

```<code>self.model_semantic.fit_generator(train_generator,
                                 epochs=10,
                                 verbose=1,
                                 validation_data=val_generator)
</code>```

Your generator is a Sequence, it already has a __len__, you don't need to specify steps_per_epoch or validation_steps.

Every generator has automatic batch sizes, every step is a batch and that's it. You don't need to specify batch_size in fit_generator.

If you're going to use fit, go like this:

```<code>...fit(train_generator, steps_per_epoch = len(train_generator),
       epochs = 10, verbose = 1,
       validation_data = val_generator, validation_steps = len(val_generator))
</code>```

Finally, you should be hunting for anything that might be None (as the error message suggests) in your code.

Check if every function has a return line.

Check all inputs of your generator in __init__.

Print the filenames inside the generator.

Get the __len__ of the generator.

Try to get an item from the generator: x, y= train_generator[0]

Body:
i'm trying to fit my deep learning model with a custom generator.

When i fit the model, it shows me this error:

I tried to find similar questions, but all the answers were about converting lists to numpy array. I think that's not the question in this error. My lists are all in numpy array format. This custom generator is based on a custom generator from  here

This is the part of code where I fit the model:

        train_generator = RepresentationGenerator(representation_path=representations_path, target_path=target_path,
                                              filenames=training_filenames, batch_size=batch_size)
    val_generator = RepresentationGenerator(representation_path=representations_path, target_path=target_path,
                                            filenames=validation_filenames, batch_size=batch_size)
    self.model_semantic.fit_generator(train_generator,
                            epochs=10,
                            verbose=1,
                            validation_data=val_generator,
                            )
    return 0

where the variables are:

representations_path - is a string with the directory to the path where i store the training files, that which file is the input to model

target_path - is a string with the directory to the path where i store the target files, that which file is the target of the model (output)

training_filenames - is a list with the names of training and target files (both have the same name, but they are in different folders)

batch_size - integer with the size of the batch. It has the value 7.

My generator class is below:

import np
from tensorflow_core.python.keras.utils.data_utils import Sequence

class RepresentationGenerator(Sequence):

    def __init__(self, representation_path, target_path, filenames, batch_size):
        self.filenames = np.array(filenames)
        self.batch_size = batch_size
        self.representation_path = representation_path
        self.target_path = target_path

    def __len__(self):
        return (np.ceil(len(self.filenames) / float(self.batch_size))).astype(np.int)

    def __getitem__(self, idx):
        files_to_batch = self.filenames[idx * self.batch_size: (idx + 1) * self.batch_size]
        batch_x, batch_y = [], []
        for file in files_to_batch:
            batch_x.append(np.load(self.representation_path + file + ".npy", allow_pickle=True))
            batch_y.append(np.load(self.target_path + file + ".npy", allow_pickle=True))

        return np.array(batch_x), np.array(batch_y)

These are the values, when the method fit is called:

How can I fix this error?

Thank you mates!

When I call the method fit_generator, it calls the method fit.

The method fit, calls the method func.fit and it passes the variable Y that is set as None

The error occurs in this line:

Body:
Final solution:

Import from the correct place:

from tensorflow.keras.utils import Sequence

Old answers:

If __getitem__ is never called, the problem might be in __len__. You're not returning an int, you're returning a np.int.

I suggest you try:

def __len__(self):
    length = len(self.filenames) // self.batch_size
    if len(self.filenames) % self.batch_size > 0:
        length += 1

    return length

But if __getitem__ is being called and your data returned, then you should inspect your arrays.

Get an item from the generator yourself and check the content:

x, y = train_generator[0]

Are they single arrays? Or are they arrays of arrays? (Must be single)

What are their shapes? Do they have the expected shapes?

What are their types? Usually they should be float, sometimes int (for inputs to embedding layers), very rarely string (for inputs to custom layers that know how to treat strings).

The outputs must always be float, at most int (for sparse losses)

Other suppositions, you're using fit with batch_size while using a generator.... this is strange and the "if" clauses inside the method may not be well prepared, you might be falling into another training case.

Go straight to the usual options:

self.model_semantic.fit_generator(train_generator,
                                 epochs=10,
                                 verbose=1,
                                 validation_data=val_generator)

Your generator is a Sequence, it already has a __len__, you don't need to specify steps_per_epoch or validation_steps.

Every generator has automatic batch sizes, every step is a batch and that's it. You don't need to specify batch_size in fit_generator.

If you're going to use fit, go like this:

...fit(train_generator, steps_per_epoch = len(train_generator),
       epochs = 10, verbose = 1,
       validation_data = val_generator, validation_steps = len(val_generator))

Finally, you should be hunting for anything that might be None (as the error message suggests) in your code.

Check if every function has a return line.

Check all inputs of your generator in __init__.

Print the filenames inside the generator.

Get the __len__ of the generator.

Try to get an item from the generator: x, y= train_generator[0]


问:
smooth scrolling recyclerview
```<code>  public class Maindashboard extends AppCompatActivity {

            ArrayList<SectionDataModel> allSampleData;
            private Toolbar toolbar;
            public static TextView title;

            public static RecyclerView my_recycler_view;

            @SuppressLint("WrongConstant")
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                getSupportActionBar().hide();
                setContentView(R.layout.activity_main2);
                allSampleData = new ArrayList<SectionDataModel>();
                title = findViewById(R.id.title);
                ArrayList<String> years = new ArrayList<String>();
                int thisYear = Calendar.getInstance().get(Calendar.YEAR) + 10;
                for (int ik = 2019; ik <= thisYear; ik++) {
                    years.add(Integer.toString(ik));
                    int year = ik;
                }
                my_recycler_view = (RecyclerView) findViewById(R.id.rv_item);
                my_recycler_view.setHasFixedSize(true);
        RecyclerViewDataAdapter adapter = new RecyclerViewDataAdapter(Maindashboard.this, allSampleData);
   my_recycler_view.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                my_recycler_view.setItemViewCacheSize(20);
                my_recycler_view.setDrawingCacheEnabled(true);
                my_recycler_view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
                my_recycler_view.setRecycledViewPool(new RecyclerView.RecycledViewPool());
                my_recycler_view.setAdapter(adapter);
                createDummyData();
            }
            public void createDummyData() {
                for (int j = 0; j < 132; j++) {
                    Calendar cal = Calendar.getInstance();
                    int month = cal.get(Calendar.MONTH);
                    SectionDataModel dm = new SectionDataModel();
                    ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
                    // cal.set(Calendar.DAY_OF_YEAR, 2019);
                    cal.set(Calendar.MONTH, month + j);
                    SimpleDateFormat dfs = new SimpleDateFormat("MMMM-yyyy");
                    String months = dfs.format(cal.getTime());
                    dm.setHeaderTitle(months);
                    int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
                    SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy");
                    //System.out.print(df.format(cal.getTime()));
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
                    for (int i = 1; i < maxDay + dayOfWeek; i++) {
                        SingleItemModel imageModel = new SingleItemModel();
                            if (i < dayOfWeek) {
                            imageModel.setName(" - - ");
                        } else {
                            int index = i - dayOfWeek + 1;
                            cal.set(Calendar.DAY_OF_MONTH, index);
                            imageModel.setName(df.format(cal.getTime()));
                        }
                        singleItem.add(imageModel);
                    }
                    dm.setAllItemsInSection(singleItem);
                    allSampleData.add(dm);
                }
            }
            public int getWeekdayOfMonth(int year, int month) {
                Calendar cal = Calendar.getInstance();
                cal.set(year, month - 1, 1);
                int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
                return dayOfWeek;
            }
        }
</code>```

<p>i created custom vertical scrolling 10 years  calendar view  its working fine but not scrolling smoothly and when open calendar screen it taking to 5 seconds to open activity  i used below code  in that code executing perfectly but not scrolling smoothly and taking to much time top open activity </p>

答:
Try this,this might help

```<code> recyclerView.setNestedScrollingEnabled(false);
</code>```

Title: smooth scrolling recyclerview

Body:
  public class Maindashboard extends AppCompatActivity {

            ArrayList<SectionDataModel> allSampleData;
            private Toolbar toolbar;
            public static TextView title;

            public static RecyclerView my_recycler_view;

            @SuppressLint("WrongConstant")
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                getSupportActionBar().hide();
                setContentView(R.layout.activity_main2);
                allSampleData = new ArrayList<SectionDataModel>();
                title = findViewById(R.id.title);
                ArrayList<String> years = new ArrayList<String>();
                int thisYear = Calendar.getInstance().get(Calendar.YEAR) + 10;
                for (int ik = 2019; ik <= thisYear; ik++) {
                    years.add(Integer.toString(ik));
                    int year = ik;
                }
                my_recycler_view = (RecyclerView) findViewById(R.id.rv_item);
                my_recycler_view.setHasFixedSize(true);
        RecyclerViewDataAdapter adapter = new RecyclerViewDataAdapter(Maindashboard.this, allSampleData);
   my_recycler_view.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                my_recycler_view.setItemViewCacheSize(20);
                my_recycler_view.setDrawingCacheEnabled(true);
                my_recycler_view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
                my_recycler_view.setRecycledViewPool(new RecyclerView.RecycledViewPool());
                my_recycler_view.setAdapter(adapter);
                createDummyData();
            }
            public void createDummyData() {
                for (int j = 0; j < 132; j++) {
                    Calendar cal = Calendar.getInstance();
                    int month = cal.get(Calendar.MONTH);
                    SectionDataModel dm = new SectionDataModel();
                    ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
                    // cal.set(Calendar.DAY_OF_YEAR, 2019);
                    cal.set(Calendar.MONTH, month + j);
                    SimpleDateFormat dfs = new SimpleDateFormat("MMMM-yyyy");
                    String months = dfs.format(cal.getTime());
                    dm.setHeaderTitle(months);
                    int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
                    SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy");
                    //System.out.print(df.format(cal.getTime()));
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
                    for (int i = 1; i < maxDay + dayOfWeek; i++) {
                        SingleItemModel imageModel = new SingleItemModel();
                            if (i < dayOfWeek) {
                            imageModel.setName(" - - ");
                        } else {
                            int index = i - dayOfWeek + 1;
                            cal.set(Calendar.DAY_OF_MONTH, index);
                            imageModel.setName(df.format(cal.getTime()));
                        }
                        singleItem.add(imageModel);
                    }
                    dm.setAllItemsInSection(singleItem);
                    allSampleData.add(dm);
                }
            }
            public int getWeekdayOfMonth(int year, int month) {
                Calendar cal = Calendar.getInstance();
                cal.set(year, month - 1, 1);
                int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
                return dayOfWeek;
            }
        }

i created custom vertical scrolling 10 years  calendar view  its working fine but not scrolling smoothly and when open calendar screen it taking to 5 seconds to open activity  i used below code  in that code executing perfectly but not scrolling smoothly and taking to much time top open activity

Body:
Try this,this might help

 recyclerView.setNestedScrollingEnabled(false);


问:
GStreamer Python Error: 'gst.ElementNotFoundError: videoconvert'
I'm trying to create a simple GStreamer pipeline that takes a video, crops and plays it, with python.

Through the terminal, this pipeline works great:

```<code>gst-launch-1.0 filesrc location='/home/inbarcha/Desktop/gstreamer_interface/U2One.mp4' ! decodebin ! videoconvert ! videocrop top=150 left=150 right=4 bottom=0 ! ximagesink
</code>```

But, when I try to use this python code:

```<code>import pygst
pygst.require('0.10')
import gst

import pygtk
pygtk.require('2.0')
import gtk

class CropVideo:
    def __init__(self, video_path, top_crop, left_crop, right_crop, bottom_crop):
        self.pipeline = gst.Pipeline('crop_video')

        self.filesrc = gst.element_factory_make('filesrc', 'file_src')
        self.filesrc.set_property('location', video_path)
        self.pipeline.add(self.filesrc)

        self.decodebin = gst.element_factory_make('decodebin', 'decode')
        self.pipeline.add(self.decodebin)
        self.filesrc.link(self.decodebin)

        self.videoconvert = gst.element_factory_make('videoconvert', 'convert')
        self.pipeline.add(self.videoconvert)
        self.decodebin.link(self.videoconvert)

        self.videocrop = gst.element_factory_make('videocrop', 'crop')
        self.videocrop.set_property('top', top_crop)
        self.videocrop.set_property('left', left_crop)
        self.videocrop.set_property('right', right_crop)
        self.videocrop.set_property('bottom', bottom_crop)
        self.pipeline.add(self.videocrop)
        self.videoconvert.link(self.videocrop)

        self.ximagesink = gst.element_factory_make('ximagesink', 'output_video')
        self.pipeline.add(self.ximagesink)
        self.videocrop.link(self.ximagesink)

if __name__ == "__main__":
    start = CropVideo('/home/inbarcha/Desktop/gstreamer_interface/U2One.mp4', 150, 150, 4, 0)
    gtk.main()
</code>```

The error I get is:

```<code>Traceback (most recent call last):
  File "/home/inbarcha/Desktop/gstreamer_interface/src/gstreamer_crop_video.py", line 41, in <module>
    start = CropVideo('/home/inbarcha/Desktop/gstreamer_interface/U2One.mp4', 150, 150, 4, 0)
  File "/home/inbarcha/Desktop/gstreamer_interface/src/gstreamer_crop_video.py", line 13, in __init__
    self.videoconvert = gst.element_factory_make('videoconvert', 'convert')
gst.ElementNotFoundError: videoconvert
</code>```

I can't figure out the problem.

I've tried to make python use gst-1.0 and not gst-0.10, but although I did download the python package with "sudo apt-get update / sudo apt-get install python-gst-1.0", in the python2.7 dist-packages directory I only see "gst-0.10", and I can't seem to find the installation directory for gst-1.0.

I feel like I'm missing something and the answer is right in front of me.

Any help would be GREATLY appreciated.

Ubuntu version: 14.04

Python version: 2.7

答:
It looks that videoconvert element is not available in Gstreamer 0.10. According to this documentation https://gstreamer.freedesktop.org/documentation/application-development/appendix/porting-1-0.html?gi-language=c

ffmpegcolorspace was removed and replaced with videoconvert

Body:
I'm trying to create a simple GStreamer pipeline that takes a video, crops and plays it, with python.

Through the terminal, this pipeline works great:

gst-launch-1.0 filesrc location='/home/inbarcha/Desktop/gstreamer_interface/U2One.mp4' ! decodebin ! videoconvert ! videocrop top=150 left=150 right=4 bottom=0 ! ximagesink

But, when I try to use this python code:

import pygst
pygst.require('0.10')
import gst

import pygtk
pygtk.require('2.0')
import gtk

class CropVideo:
    def __init__(self, video_path, top_crop, left_crop, right_crop, bottom_crop):
        self.pipeline = gst.Pipeline('crop_video')

        self.filesrc = gst.element_factory_make('filesrc', 'file_src')
        self.filesrc.set_property('location', video_path)
        self.pipeline.add(self.filesrc)

        self.decodebin = gst.element_factory_make('decodebin', 'decode')
        self.pipeline.add(self.decodebin)
        self.filesrc.link(self.decodebin)

        self.videoconvert = gst.element_factory_make('videoconvert', 'convert')
        self.pipeline.add(self.videoconvert)
        self.decodebin.link(self.videoconvert)

        self.videocrop = gst.element_factory_make('videocrop', 'crop')
        self.videocrop.set_property('top', top_crop)
        self.videocrop.set_property('left', left_crop)
        self.videocrop.set_property('right', right_crop)
        self.videocrop.set_property('bottom', bottom_crop)
        self.pipeline.add(self.videocrop)
        self.videoconvert.link(self.videocrop)

        self.ximagesink = gst.element_factory_make('ximagesink', 'output_video')
        self.pipeline.add(self.ximagesink)
        self.videocrop.link(self.ximagesink)

if __name__ == "__main__":
    start = CropVideo('/home/inbarcha/Desktop/gstreamer_interface/U2One.mp4', 150, 150, 4, 0)
    gtk.main()

The error I get is:

Traceback (most recent call last):
  File "/home/inbarcha/Desktop/gstreamer_interface/src/gstreamer_crop_video.py", line 41, in <module>
    start = CropVideo('/home/inbarcha/Desktop/gstreamer_interface/U2One.mp4', 150, 150, 4, 0)
  File "/home/inbarcha/Desktop/gstreamer_interface/src/gstreamer_crop_video.py", line 13, in __init__
    self.videoconvert = gst.element_factory_make('videoconvert', 'convert')
gst.ElementNotFoundError: videoconvert

I can't figure out the problem.

I've tried to make python use gst-1.0 and not gst-0.10, but although I did download the python package with "sudo apt-get update / sudo apt-get install python-gst-1.0", in the python2.7 dist-packages directory I only see "gst-0.10", and I can't seem to find the installation directory for gst-1.0.

I feel like I'm missing something and the answer is right in front of me.

Any help would be GREATLY appreciated.

Ubuntu version: 14.04

Python version: 2.7