问:
Converting a masked numpy array into a csv file
I am having trouble converting a netCDF file (which is a masked numpy array) into a csv file. The netcdf file was condensed from 12 separate files to form a 3D array of 12 x 52 x 39, where 12 corresponds to the months, 52 to the latitudes and 29 longitudes.

UPDATE:
My desired csv output is 4 columns with grid number (0-437), latitude, longitude and total precipitation. e.g:

```<code>grid number| latitude| longitude| Total_precipitation
0             60.5000  -1.2345     800.123
1              .         .           .
2              .         .           .
</code>```

I want to sum my 12 months of precipitation and condense the data into a single column. (I haven't found any answers on here to help me do this)

At the moment I have managed to read in the netCDF file and save it as csv but it is in the wrong format (see method 1-3).

This is what I have so far:

```<code>###################
# importing modules
###################
import pandas as pd
import numpy as np
import os
import sys
#import csv
from netCDF4 import Dataset

  #setting up directory
    CURRENT_DIR = os.path.abspath(os.curdir)
    precip_path = os.path.join(CURRENT_DIR + '/CLIM8Splash/input/futureCLIM8/precip_2070_2099CDF')
    sys.path.append(precip_path)

    # reading  precip netcdf
    os.chdir('CLIM8_splash/input/futureCLIM8/precip_2070_2099CDF/')
    files = ['jan_precip_2070_2099CDF.nc', 'feb_precip_2070_2099CDF.nc', 'mar_precip_2070_2099CDF.nc', 'apr_precip_2070_2099CDF.nc','may_precip_2070_2099CDF.nc', 'jun_precip_2070_2099CDF.nc', 'jul_precip_2070_2099CDF.nc', 'aug_precip_2070_2099CDF.nc', 'sep_precip_2070_2099CDF.nc', 'oct_precip_2070_2099CDF.nc', 'nov_precip_2070_2099CDF.nc', 'dec_precip_2070_2099CDF.nc']
    #all_precip = ma.zeros((len(files), 52, 39))
    all_precip = np.zeros((len(files), 52, 39))
    all_precip.fill(np.nan)
    for idx, x in enumerate(files):
        ds = Dataset(x, 'r')
        precip = ds.variables['cdf_precip_dmean_tmean_abs'][:, :]
        all_precip[idx, :, :] = precip
        ds.close()
    os.chdir('../../../..')

#dimensions of netCDF file
def altReadin(path):
    my_file = Dataset(path)
    print(my_file.file_format)
    print("Dimensions: " + str(my_file.dimensions.keys()))
    print(my_file.variables['rlon'])
    content = MFDataset(path, False, 'rlon')
    print(content.variables['cdf_precip_dmean_tmean_abs'][:])
    print("Variables: "+ str(my_file.variables.keys()))

    altReadin(FILE_PATH)

    #####OUTPUT
    NETCDF3_CLASSIC
    Dimensions: [u'rlat', u'bound', u'rlon']
    <type 'netCDF4._netCDF4.Variable'>
    float32 rlon(rlon)
        bounds: bounds_rlon
        topology: circular
        long_name: longitude in rotated pole grid
        standard_name: grid_longitude
        units: degrees
        modulo: 360.0
        axis: X
    unlimited dimensions:
    current shape = (39,)
    filling off

    [[-- -- -- ..., -- -- --]
     [-- -- -- ..., 5.498641490936279 5.392685890197754 --]
     [-- -- -- ..., 5.66285514831543 -- --]
     ...,
     [-- -- -- ..., -- -- --]
     [-- -- -- ..., -- -- --]
     [-- -- -- ..., -- -- --]]

       Variables: [u'rlat', u'bounds_rlat', u'rlon', u'bounds_rlon', u'lat', u'lon', u'cdf_precip_dmean_tmean_abs', u'rotated_pole', u'meaning_period', u'time', u'em_scen', u'percentile']

#Totalling 12 months of precipitation
#????

# and then converting it to a csv
precip_tot = precip

#Method 1 saves csv with grid shape preserved
np.savetxt("precip_fut1.csv", precip, delimiter=",")

#Method 2 csv as a long string
precip_tot.sum(axis=0).filled().tofile('precip_tot_fut.csv', sep=',')

#Method 3 netcdf>dataframe>csv (still preserves shape)
precip_tot = pd.DataFrame(precip_tot)
precip_tot.to_csv("precip.csv")

#sample of output of precip
>>> >>> [[-- -- -- ..., -- -- --]
 [-- -- -- ..., 7.167891502380371 6.648772716522217 --]
 [-- -- -- ..., 7.282683372497559 -- --]
 ...,
 [-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]]
print(precip_tot.head()
   0   1   2   3   4   5   6   7   8   9  ...  29  30  31  32  33  34  35  \
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN

         36        37  38
0       NaN       NaN NaN
1  7.167892  6.648773 NaN
2  7.282683       NaN NaN
3  7.517180       NaN NaN
4       NaN       NaN NaN

[5 rows x 39 columns]
</code>```

Thanks for helping me!

答:
Consider these Dataframe, Dimensions are reduced for brevity.

Example Data:

```<code>lat(5,)[ 60.5  61.5  62.5  63.5  64.5]
lon(4,)[-0.2345 -1.2345 -2.2345 -3.2345]
preceip(5, 4)[[        nan         nan         nan         nan]
 [        nan         nan  5.49864149  5.39268589]
 [        nan         nan  5.66285515         nan]
 [        nan         nan         nan         nan]
 [        nan         nan         nan         nan]]
</code>```

Your Data:

```<code>lon = ds.variables['rlon'][:, :]
lat = ds.variables['rlat'][:, :]
precip = ds.variables['cdf_precip_dmean_tmean_abs'][:, :]
</code>```

Read precip array, append not null data:

```<code>precip_list = []
precip_tot = 0
for r in range(len(lat)):
    for c in range(len(lon)):
        if precip[r,c] > 0:
            precip_list.append((lat[r], lon[c], precip[r,c]))
            precip_tot += precip[r,c]

precip_list.append(('', 'precip_tot:', precip_tot))

fieldnames = ['grid number', 'latitude','longitude', 'Total_precipitation']
print('{fn[0]}\t{fn[1]}\t{fn[2]}\t{fn[3]}'.format(fn=fieldnames))
for i, d in enumerate(precip_list[:-1]):
    print('{:<10}\t{:>8.4f}\t{:>9.4f}\t{:10.3f}'.format(i, d[0], d[1], d[2]))
print('{}precip_tot:\t{:10.3f}'.format('\t'*6, precip_tot))
</code>```

Output:

```<code>   grid number    latitude    longitude   Total_precipitation
    0            61.5000      -2.2345        5.499
    1            61.5000      -3.2345        5.393
    2            62.5000      -2.2345        5.663
                            precip_tot:     16.554
</code>```

Tested with Python: 3.4.2

Body:
I am having trouble converting a netCDF file (which is a masked numpy array) into a csv file. The netcdf file was condensed from 12 separate files to form a 3D array of 12 x 52 x 39, where 12 corresponds to the months, 52 to the latitudes and 29 longitudes.

UPDATE:
My desired csv output is 4 columns with grid number (0-437), latitude, longitude and total precipitation. e.g:

grid number| latitude| longitude| Total_precipitation
0             60.5000  -1.2345     800.123
1              .         .           .
2              .         .           .

I want to sum my 12 months of precipitation and condense the data into a single column. (I haven't found any answers on here to help me do this)

At the moment I have managed to read in the netCDF file and save it as csv but it is in the wrong format (see method 1-3).

This is what I have so far:

###################
# importing modules
###################
import pandas as pd
import numpy as np
import os
import sys
#import csv
from netCDF4 import Dataset

  #setting up directory
    CURRENT_DIR = os.path.abspath(os.curdir)
    precip_path = os.path.join(CURRENT_DIR + '/CLIM8Splash/input/futureCLIM8/precip_2070_2099CDF')
    sys.path.append(precip_path)

    # reading  precip netcdf
    os.chdir('CLIM8_splash/input/futureCLIM8/precip_2070_2099CDF/')
    files = ['jan_precip_2070_2099CDF.nc', 'feb_precip_2070_2099CDF.nc', 'mar_precip_2070_2099CDF.nc', 'apr_precip_2070_2099CDF.nc','may_precip_2070_2099CDF.nc', 'jun_precip_2070_2099CDF.nc', 'jul_precip_2070_2099CDF.nc', 'aug_precip_2070_2099CDF.nc', 'sep_precip_2070_2099CDF.nc', 'oct_precip_2070_2099CDF.nc', 'nov_precip_2070_2099CDF.nc', 'dec_precip_2070_2099CDF.nc']
    #all_precip = ma.zeros((len(files), 52, 39))
    all_precip = np.zeros((len(files), 52, 39))
    all_precip.fill(np.nan)
    for idx, x in enumerate(files):
        ds = Dataset(x, 'r')
        precip = ds.variables['cdf_precip_dmean_tmean_abs'][:, :]
        all_precip[idx, :, :] = precip
        ds.close()
    os.chdir('../../../..')

#dimensions of netCDF file
def altReadin(path):
    my_file = Dataset(path)
    print(my_file.file_format)
    print("Dimensions: " + str(my_file.dimensions.keys()))
    print(my_file.variables['rlon'])
    content = MFDataset(path, False, 'rlon')
    print(content.variables['cdf_precip_dmean_tmean_abs'][:])
    print("Variables: "+ str(my_file.variables.keys()))

    altReadin(FILE_PATH)

    #####OUTPUT
    NETCDF3_CLASSIC
    Dimensions: [u'rlat', u'bound', u'rlon']
    <type 'netCDF4._netCDF4.Variable'>
    float32 rlon(rlon)
        bounds: bounds_rlon
        topology: circular
        long_name: longitude in rotated pole grid
        standard_name: grid_longitude
        units: degrees
        modulo: 360.0
        axis: X
    unlimited dimensions:
    current shape = (39,)
    filling off

    [[-- -- -- ..., -- -- --]
     [-- -- -- ..., 5.498641490936279 5.392685890197754 --]
     [-- -- -- ..., 5.66285514831543 -- --]
     ...,
     [-- -- -- ..., -- -- --]
     [-- -- -- ..., -- -- --]
     [-- -- -- ..., -- -- --]]

       Variables: [u'rlat', u'bounds_rlat', u'rlon', u'bounds_rlon', u'lat', u'lon', u'cdf_precip_dmean_tmean_abs', u'rotated_pole', u'meaning_period', u'time', u'em_scen', u'percentile']

#Totalling 12 months of precipitation
#????

# and then converting it to a csv
precip_tot = precip

#Method 1 saves csv with grid shape preserved
np.savetxt("precip_fut1.csv", precip, delimiter=",")

#Method 2 csv as a long string
precip_tot.sum(axis=0).filled().tofile('precip_tot_fut.csv', sep=',')

#Method 3 netcdf>dataframe>csv (still preserves shape)
precip_tot = pd.DataFrame(precip_tot)
precip_tot.to_csv("precip.csv")

#sample of output of precip
>>> >>> [[-- -- -- ..., -- -- --]
 [-- -- -- ..., 7.167891502380371 6.648772716522217 --]
 [-- -- -- ..., 7.282683372497559 -- --]
 ...,
 [-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]]
print(precip_tot.head()
   0   1   2   3   4   5   6   7   8   9  ...  29  30  31  32  33  34  35  \
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN

         36        37  38
0       NaN       NaN NaN
1  7.167892  6.648773 NaN
2  7.282683       NaN NaN
3  7.517180       NaN NaN
4       NaN       NaN NaN

[5 rows x 39 columns]

Thanks for helping me!

Body:
Consider these Dataframe, Dimensions are reduced for brevity.

Example Data:

lat(5,)[ 60.5  61.5  62.5  63.5  64.5]
lon(4,)[-0.2345 -1.2345 -2.2345 -3.2345]
preceip(5, 4)[[        nan         nan         nan         nan]
 [        nan         nan  5.49864149  5.39268589]
 [        nan         nan  5.66285515         nan]
 [        nan         nan         nan         nan]
 [        nan         nan         nan         nan]]

Your Data:

lon = ds.variables['rlon'][:, :]
lat = ds.variables['rlat'][:, :]
precip = ds.variables['cdf_precip_dmean_tmean_abs'][:, :]

Read precip array, append not null data:

precip_list = []
precip_tot = 0
for r in range(len(lat)):
    for c in range(len(lon)):
        if precip[r,c] > 0:
            precip_list.append((lat[r], lon[c], precip[r,c]))
            precip_tot += precip[r,c]

precip_list.append(('', 'precip_tot:', precip_tot))

fieldnames = ['grid number', 'latitude','longitude', 'Total_precipitation']
print('{fn[0]}\t{fn[1]}\t{fn[2]}\t{fn[3]}'.format(fn=fieldnames))
for i, d in enumerate(precip_list[:-1]):
    print('{:<10}\t{:>8.4f}\t{:>9.4f}\t{:10.3f}'.format(i, d[0], d[1], d[2]))
print('{}precip_tot:\t{:10.3f}'.format('\t'*6, precip_tot))

Output:

   grid number    latitude    longitude   Total_precipitation
    0            61.5000      -2.2345        5.499
    1            61.5000      -3.2345        5.393
    2            62.5000      -2.2345        5.663
                            precip_tot:     16.554

Tested with Python: 3.4.2


来源: stackexchange

问:
how to set text shadow with angular?
I want to let user set text shadow by selecting an offset from one input field, blur from another and color from colorpicker. I am using angular and fabric.js and this is my HTML:

```<code>  <div class="shadow">
    <div class="slider-input">
      <span>Offset</span>
      <input min="-25" max="25" step="1" type="number" ng-change="text.setShadow('offset', offset)" ng-model="offset" />
    </div>

    <div class="slider-input">
      <span>Blur</span>
      <input min="0" max="25" step="1" type="number" ng-change="text.setShadow('blur', blur)" ng-model="blur" />
    </div>

    <div class="colorpicker">
      <span>Color</span>
      <input ed-color-picker-disabled="{{ !enableOutline }}" ed-color-picker="text.setShadow('shadowcolor', color)" type="text" />
    </div>
  </div>
</code>```

In the controller I have set these default values:

```<code>$scope.offset = 0;
$scope.blur = 0;
$scope.shadowcolor = '#000';
</code>```

In the service I set this function:

```<code> setShadow: function(property, value) {
   var text   = this.getTextObject();
   //   if (value == 'offset') {
  //      text.set('shadow', value + 'px' + ' ' + value + 'px')
  //    }
       console.log("property", property);
       console.log("value", value);

  },
</code>```

The problem is that on press I get only the value of one input field or color, but in order to set shadow I need to know the context too (other values).

How to retrieve all of the values - ofsset input field, blur input field and shadow color all at once so that I could set text shadow?

答:
In controller or directive:

```<code>$scope.shadow = $scope.offset + "px " + $scope.offset + "px " + $scope.blur + "px " + $scope.color;
</code>```

(retrieving the offset, blur, and color from your ng-models as needed.)

in template:

```<code>ng-style="{textShadow: shadow}"
</code>```

I don't think you're going to be able to do this cleanly from a service that only receives one of the (color / blur / offset) values at a time.  I guess you could have the service cache each value as it receives each one, and only return the text-shadow css when all three values have been fed to the service -- but that would mean only a single directive could use that service without values leaking across directives. (Honestly, I'm questioning why you're using a service for this in the first place; this seems like functionality that belongs in a directive.)

ContentLicense: CC BY-SA 3.0

Title: how to set text shadow with angular?

Body:
I want to let user set text shadow by selecting an offset from one input field, blur from another and color from colorpicker. I am using angular and fabric.js and this is my HTML:

      Offset
      <input min="-25" max="25" step="1" type="number" ng-change="text.setShadow('offset', offset)" ng-model="offset" />

      Blur
      <input min="0" max="25" step="1" type="number" ng-change="text.setShadow('blur', blur)" ng-model="blur" />

      Color
      <input ed-color-picker-disabled="{{ !enableOutline }}" ed-color-picker="text.setShadow('shadowcolor', color)" type="text" />

In the controller I have set these default values:

$scope.offset = 0;
$scope.blur = 0;
$scope.shadowcolor = '#000';

In the service I set this function:

 setShadow: function(property, value) {
   var text   = this.getTextObject();
   //   if (value == 'offset') {
  //      text.set('shadow', value + 'px' + ' ' + value + 'px')
  //    }
       console.log("property", property);
       console.log("value", value);

  },

The problem is that on press I get only the value of one input field or color, but in order to set shadow I need to know the context too (other values).

How to retrieve all of the values - ofsset input field, blur input field and shadow color all at once so that I could set text shadow?

Body:
In controller or directive:

$scope.shadow = $scope.offset + "px " + $scope.offset + "px " + $scope.blur + "px " + $scope.color;

(retrieving the offset, blur, and color from your ng-models as needed.)

in template:

ng-style="{textShadow: shadow}"

I don't think you're going to be able to do this cleanly from a service that only receives one of the (color / blur / offset) values at a time.  I guess you could have the service cache each value as it receives each one, and only return the text-shadow css when all three values have been fed to the service -- but that would mean only a single directive could use that service without values leaking across directives. (Honestly, I'm questioning why you're using a service for this in the first place; this seems like functionality that belongs in a directive.)


问:
Am I forced to use the Android notifyChange() method?
Am I forced to use the notifyChange() method? I ask this because, when I call this method it enters on the onChange() method, but when I don't call the notifyChange() the onChange() method is not called. Why? </p>

答:
Okay here goes,

I don't know if this is a complete answer to your question but anything that inherits from the abstract class ContentObserver should call its "onChange" on instantiation. With that in mind take a look at the ContentObserver you are passing to your notifyChange. To start with I'd say debug step by step with that much in mind and tell me what you get...

But based on the source code, It looks as though ContentObserver fires the OnChange and that "bubbles up" through the the notifyChange method.

So with that the best sense I can make of it is that since the point of the ContentObserver is to "Observe" or listen for the firing of events (aka intents i think; I'm still trying to get the android lingo) then if you want your Observer to know your onChange is happening then yeah. But I think I would need more information about how your going about using it to give you a clearer explanation.

And by all means someone please set me straight if I'm at all wrong here in what I said lol.

ContentLicense: CC BY-SA 2.5


问:
How to define props interface for Apollo's React HOC?
I am trying to use Apollo's React HOC to fetch and pass data to my component, but I'm getting an error of:

```<code>Argument of type 'typeof BrandList' is not assignable to parameter of type
'CompositeComponent<{ data?: QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; }>'.
Type 'typeof BrandList' is not assignable to type 'StatelessComponent<{ data?:
QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; }>'.
Type 'typeof BrandList' provides no match for the signature '(props: { data?:
QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; } & { children?: ReactNode; }, context?: any): ReactElement<any>'.
</code>```

My file looks like this:

```<code>import * as React from 'react'
import {graphql} from 'react-apollo'
import gql from 'graphql-tag'

const BrandsQuery = gql`
  query {
    allBrands {
      id
      name
    }
  }
`

interface IBrand {
  id: string
  name: string
}

interface IData {
  loading: boolean,
  allBrands: IBrand[]
}

interface IProps {
  data: IData
}

class BrandList extends React.Component<IProps, void> {
  public render () {
    const {loading, allBrands} = this.props.data

    if (loading) {
      return (
        <div>Loading data..</div>
      )
    }

    return (
      <div>
        {allBrands.map((brand) => (
          <li>{brand.id} - {brand.name}</li>
        ))}
      </div>
    )
  }
}

export default graphql(BrandsQuery)(BrandList)
                                    ^^^^^^^^^
</code>```

If I use {} instead of the interface, the code compiles, but then I can't use any props inside the render function.

EDIT:

I have tried to rewrite the last line to

```<code>export default graphql<any, IProps>(BrandsQuery)(BrandList)
</code>```

which gets rid of the error, but now when I try to include the component as

```<code><div>
    <BrandList />
</div>
</code>```

I am getting following error:

```<code>Type '{}' is not assignable to type 'Readonly<IProps>'.
Property 'data' is missing in type '{}'.
</code>```

答:
Okay, I have solved the issue like this.. I had to add another Props interface

```<code>interface IExternalProps {
  id: string
}

interface IProps extends IExternalProps {
  data: IData
}

export default graphql<any, IExternalProps}>(BrandsQuery)(BrandList)
</code>```

Basically, IExternalProps is the interface for props your component expects from the outside, ie. when you actually use the component in JSX, while IProps is the interface for props you receive via GraphQL query (HOC). This interface must extend the IExternalProps, Typescript then have a chance to actually type check it.

Body:
I am trying to use Apollo's React HOC to fetch and pass data to my component, but I'm getting an error of:

Argument of type 'typeof BrandList' is not assignable to parameter of type
'CompositeComponent<{ data?: QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; }>'.
Type 'typeof BrandList' is not assignable to type 'StatelessComponent<{ data?:
QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; }>'.
Type 'typeof BrandList' provides no match for the signature '(props: { data?:
QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; } & { children?: ReactNode; }, context?: any): ReactElement<any>'.

My file looks like this:

import * as React from 'react'
import {graphql} from 'react-apollo'
import gql from 'graphql-tag'

const BrandsQuery = gql`
  query {
    allBrands {
      id
      name
    }
  }
`

interface IBrand {
  id: string
  name: string
}

interface IData {
  loading: boolean,
  allBrands: IBrand[]
}

interface IProps {
  data: IData
}

class BrandList extends React.Component<IProps, void> {
  public render () {
    const {loading, allBrands} = this.props.data

    if (loading) {
      return (

Loading data..

      )
    }

    return (

        {allBrands.map((brand) => (

{brand.id} - {brand.name}

        ))}

    )
  }
}

export default graphql(BrandsQuery)(BrandList)
                                    ^^^^^^^^^

If I use {} instead of the interface, the code compiles, but then I can't use any props inside the render function.

EDIT:

I have tried to rewrite the last line to

export default graphql<any, IProps>(BrandsQuery)(BrandList)

which gets rid of the error, but now when I try to include the component as

    <BrandList />

I am getting following error:

Type '{}' is not assignable to type 'Readonly<IProps>'.
Property 'data' is missing in type '{}'.

Body:
Okay, I have solved the issue like this.. I had to add another Props interface

interface IExternalProps {
  id: string
}

interface IProps extends IExternalProps {
  data: IData
}

export default graphql<any, IExternalProps}>(BrandsQuery)(BrandList)

Basically, IExternalProps is the interface for props your component expects from the outside, ie. when you actually use the component in JSX, while IProps is the interface for props you receive via GraphQL query (HOC). This interface must extend the IExternalProps, Typescript then have a chance to actually type check it.


问:
how to extract a number from a string if I know when its starting and when its finishing
for example:

I have the following string

```<code>"somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"
</code>```

so the number is always between

```<code>theStringBeforeTheNumber{number}theStringAfterTheNumber
</code>```

What I want is to extract the number from the whole string, how can I do that? im using scala how should my regex look like?   val myRgx: Regex = """myRegexGoesHere""".r

答:
Here's another approach using Regex along with verifying the extracted number:</p>

```<code>import scala.util.Try

val s = "somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"

val pattern = """.*?theStringBeforeTheNumber([0-9.-]*)theStringAfterTheNumber.*""".r

val number: Double = s match {
  case pattern(num) => Try(num.toDouble).getOrElse(-999)
  case _ => -999
}
number: Double = 20.47
</code>```

Body:
for example:

I have the following string

"somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"

so the number is always between

theStringBeforeTheNumber{number}theStringAfterTheNumber

What I want is to extract the number from the whole string, how can I do that? im using scala how should my regex look like?   val myRgx: Regex = """myRegexGoesHere""".r

Body:
Here's another approach using Regex along with verifying the extracted number:

import scala.util.Try

val s = "somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"

val pattern = """.*?theStringBeforeTheNumber([0-9.-]*)theStringAfterTheNumber.*""".r

val number: Double = s match {
  case pattern(num) => Try(num.toDouble).getOrElse(-999)
  case _ => -999
}
number: Double = 20.47


问:
Dependency injection in `ActionFiliter` vs. calling `Activator.CreateInstance()`
Requiring to sometimes use dependency injection in ActioFilter or other attributes running before or after an action API or result is inevitable. However, it is carried out through passing the type to be injected to the attribute using the typeof keyword. In order to simplify the case, when having various implementations for an interface, I have found it much simpler to manually instantiate the type than using the built-in dependency injection framework. For example:

```<code>public TestAttribute: Attribute, IActionFilter {
   private Type injectionType;
   public TestAttribute(Type injectionType){
     ...
   }
   ...
   public void OnActionExecuting(ActionExecutingContext context) {
       InjectedTypeInterface injectedTypInterface = (InjectedTypeInterface) Activator.CreateInstance(injectedType, arg1, arg2, ...);
       ...
   }
}
</code>```

I want to know, from the point of view of other people here, that would this approach cause problems that using the built-in dependency injection framework would not? (Injected implementation will be always Transient in this case and not Scoped or Singleton)

答:
I don't recommend doing the route of Activator.CreateInstance, here are some reasons why to avoid it and stick with the official way:

You'd need to pass in all instances of the parameters (i.e. of the type you want to instantiate has other dependencies) to it

The instance created this way isn't tracked by the scoped container. This also means, it won't automatically get disposed (Updated note this of course will only happen if the service implements IDisposable interface) at the end of the request and instead be disposed at some indeterminable time in future, when the GC kicks in and will keep resources open for longer then intended (i.e. holding connection or file handle open for longer then intended) unless you dispose it explicitly

Like you already recognized, you can't do so with scoped and singleton instances

For your concrete examples, there are easier ways to get a specific instance from DI - aside from the official supported ways (Filters - Dependency Injection) - you can also resolve from HttpContext, assuming you have access to it in the type of filter you are using.

For ActionFilter/IActionFilter

```<code>public void OnActionExecuting(ActionExecutingContext context) {
    InjectedTypeInterface injectedTypInterface = context.HttpContext
        .RequestServices.GetService<InjectedTypeInterface>();
   ...
}
</code>```

Body:
Requiring to sometimes use dependency injection in ActioFilter or other attributes running before or after an action API or result is inevitable. However, it is carried out through passing the type to be injected to the attribute using the typeof keyword. In order to simplify the case, when having various implementations for an interface, I have found it much simpler to manually instantiate the type than using the built-in dependency injection framework. For example:

public TestAttribute: Attribute, IActionFilter {
   private Type injectionType;
   public TestAttribute(Type injectionType){
     ...
   }
   ...
   public void OnActionExecuting(ActionExecutingContext context) {
       InjectedTypeInterface injectedTypInterface = (InjectedTypeInterface) Activator.CreateInstance(injectedType, arg1, arg2, ...);
       ...
   }
}

I want to know, from the point of view of other people here, that would this approach cause problems that using the built-in dependency injection framework would not? (Injected implementation will be always Transient in this case and not Scoped or Singleton)

Body:
I don't recommend doing the route of Activator.CreateInstance, here are some reasons why to avoid it and stick with the official way:

You'd need to pass in all instances of the parameters (i.e. of the type you want to instantiate has other dependencies) to it

The instance created this way isn't tracked by the scoped container. This also means, it won't automatically get disposed (Updated note this of course will only happen if the service implements IDisposable interface) at the end of the request and instead be disposed at some indeterminable time in future, when the GC kicks in and will keep resources open for longer then intended (i.e. holding connection or file handle open for longer then intended) unless you dispose it explicitly

Like you already recognized, you can't do so with scoped and singleton instances

For your concrete examples, there are easier ways to get a specific instance from DI - aside from the official supported ways (Filters - Dependency Injection) - you can also resolve from HttpContext, assuming you have access to it in the type of filter you are using.

For ActionFilter/IActionFilter

public void OnActionExecuting(ActionExecutingContext context) {
    InjectedTypeInterface injectedTypInterface = context.HttpContext
        .RequestServices.GetService<InjectedTypeInterface>();
   ...
}


问:
Oracle Apex 5 Data upload from csv
I'm having a peculiar problem when I try to upload data from a file into a Oracle Apex 5 (version: 5.0.0.00.31) table.

I created a table view script

CREATE TABLE projects
( projectid NUMBER          NOT NULL,
  proj_name VARCHAR(45)     NOT NULL,
  proj_client   VARCHAR(35),
  CONSTRAINT    pk_projectid PRIMARY KEY (projectid)
);

But when I go to submit the csv comma delimited file data

"Inventory tracking for tire company","ACE Tire Company"
"Sales order processing for retail business","Book World"
"Project management and activity tracking","Digital Images"
"Production management","ACME Manufacturing"
"Art gallery inventory","Aurora Gallery"
"Work order processing for auto shop","Auto Pros"

I get this error : Photo of Error  stating that "1 Error Occurred, There are NOT NULL columns in db.PROJECTS. Select to upload the data without an error.

ProjectID must be Not Null because its the primary key and it uses a sequential number, the others can be changed to allow Nulls but this still won't upload.

Is there a way around this besides manually entering data?

答:
You're trying to insert data into a table that has a NOT NULL column and your CSV doesn't have anything for that column. So of course it's going to raise that error. That's what's supposed to happen.

I suggest you do an ALTER TABLE to drop the relevant constraints, upload your data, then add the constraints back.

Title: Oracle Apex 5 Data upload from csv


问:
how do you separate each part of an array into another array?
so I have a string that is split at any period. It is then stored into the array "sentences". Now I want to split all parts of the array "sentences" by spacing. How do I do that?

my code so far:

```<code>string input = TextEditor.Text;
string[] sentences = input.Split('.');
string[] words = sentences[0].Split(' ');
</code>```

this does not work though, obviously.

the output I want is if the string is: hello world I feel great. How about you.

output:

```<code>wordarray[0] = {"hello", "world", "I", "feel", "great"};
wordarray[1] = {"How", "about", "you"};
</code>```

答:
To get all the words in one array use SelectMany()

```<code>string[] sentences = input.Split('.');
string[] words = sentences.SelectMany((sentence) => sentence.Split(' ')).ToArray();
</code>```

Edit 1

For the fun of it you can get a histogram of words (count of each word) with

```<code>foreach (var item in words.GroupBy((word) => word).OrderByDescending((word) => word.Count()))
{
    Debug.WriteLine($"{item.Key}: {item.Count()}");
}
</code>```

Body:
so I have a string that is split at any period. It is then stored into the array "sentences". Now I want to split all parts of the array "sentences" by spacing. How do I do that?

my code so far:

string input = TextEditor.Text;
string[] sentences = input.Split('.');
string[] words = sentences[0].Split(' ');

this does not work though, obviously.

the output I want is if the string is: hello world I feel great. How about you.

output:

wordarray[0] = {"hello", "world", "I", "feel", "great"};
wordarray[1] = {"How", "about", "you"};

Body:
To get all the words in one array use SelectMany()

string[] sentences = input.Split('.');
string[] words = sentences.SelectMany((sentence) => sentence.Split(' ')).ToArray();

Edit 1

For the fun of it you can get a histogram of words (count of each word) with

foreach (var item in words.GroupBy((word) => word).OrderByDescending((word) => word.Count()))
{
    Debug.WriteLine($"{item.Key}: {item.Count()}");
}


问:
Determining local / international phone numbers for the US
You're probably thinking this has been asked a million times before but I think that my question is a little different. Most requests for phone number validation are used for validating user input. In my scenario I'm trying to validating incoming phone calls to a US mobile phone, and determine whether they're calling from another country or from within the US.

My main problem is that I'm based in the UK and have no experience of US phone numbers.. I've read about the format of how to dial etc (both international and national) but my worry is that the phone numbers appear differently on the recipient's phone, and in a variety of formats.

Here is the specification of what I'm trying to do..

Imagine you are based in the US and are receiving a call on your mobile phone

Determine whether the call is from a US or another country

In the UK calls can come appear in the local or international format, it should be able to determine if it's a US number or not

I believe international calls can be displayed on your phone in the format 0044 or +44 (if you were calling from the UK to the US)

If the call is from within the US is it a valid phone number?

Strip out all non numerical characters and reformat to national format. For example, the UK number 01530 123123 would get reformatted to 01530123123

Strip out all non numerical characters and reformat to international format. For example, the UK number 01530 123123 would get reformatted to 00441530123123

I'm trying to write the code in PHP and avoid regular expressions. I'm thinking it could use substr() to break down parts of the number.

Any thoughts on how to go about this, code snippets or example phone numbers? I'm really hoping someone from the US will be able to enlighten me on phone number formatting etc..

答:
The people saying to just look for +1 have not worked with telephone numbers much. The 1 country code applies to many areas of North America not just the US. So what really needs to happen is some logic around the tables listed for the North American Numbering Plan and at the List of North American Numbering Plan area codes

Here is a short list of some "exceptional" countries that have numbers starting in +1 that are not US based.

Bermuda:

After 1995: +1 441 (xxx) xxxx

Puerto Rico:

After 2001: +1 787 xxx xxxx or +1 939 xxx xxxx (overlay for entire island)

US Virgin Islands:

After 1997: +1 340 xxx xxxx

Northern Marianas:

After 1997: +1 670 xxx xxxx

Guam:

After 1997: +1 671 xxx xxxx

American Samoa:

After October 2, 2004: +1 684 xxx xxxx

Saint Maarten:

After joining NANP: +1 721 xxx xxxx (date to be determined)


问:
How to check if a treeview is empty
This seems simple but I am having a mental block at the moment.
Please can anyone just tell me how to check if a Treeview control is completely empty when the user clicks a button?

I am using Visual Basic 2010 express.

答:
```<code>Public Sub Button1_Click('*all handles....*)
       If Me.trvResources.Nodes.Count = 0 Then
         'Your Stuff here
       End If
End Sub
</code>```

trvResources is my Treeview name

Title: How to check if a treeview is empty

Body:
Public Sub Button1_Click('*all handles....*)
       If Me.trvResources.Nodes.Count = 0 Then
         'Your Stuff here
       End If
End Sub

trvResources is my Treeview name


问:
Last day of last month in SQL Server
I need to get last day of last month in SQL Server in the format "2017-05-31". Does anyone know how to write query for this?</p>

答:
There isn't a SQL Server 2010 (to my knowledge).  In SQL Server 2012+, you can use EOMONTH():

```<code>select eomonth(dateadd(month, -1, getdate())
</code>```

Actually, in any version, it is probably simpler to just do:

```<code>select dateadd(day, -day(getdate()), getdate())
</code>```

Oh, and then cast to a date to get rid of the time component:

```<code>select cast(dateadd(day, -day(getdate()), getdate()) as date)
</code>```

Title: Last day of last month in SQL Server

Body:
There isn't a SQL Server 2010 (to my knowledge).  In SQL Server 2012+, you can use EOMONTH():

select eomonth(dateadd(month, -1, getdate())

Actually, in any version, it is probably simpler to just do:

select dateadd(day, -day(getdate()), getdate())

Oh, and then cast to a date to get rid of the time component:

select cast(dateadd(day, -day(getdate()), getdate()) as date)


问:
Tomcat as Proxy Server
We have made a Spring boot based Web Application. Which has only static resources all html pages as angular 2 application under it.

The angular 2 application makes REST API calls which are served from different server.

I want to configure tomcat in such a way that all calls starting with /backend should be forwarded to different server and rest all request should be served from same server.

It should act like node server where we provide a proxy-config.json.

Can you suggest any implementation?

答: Tomcat does not come bundled with anything that would be considered a proxy server. If you want to proxy requests through Tomcat, you'll have to use a 3rd-party solution. Suggestions for 3rd-party solutions are out of scope for Stack Overflow.</p>

Title: Tomcat as Proxy Server


问:
iOS App Preview without iPhone 6 Plus
I have done an iOS App Preview (Video) using iPhone 6 and Quicktime in Yosemite, but I cannot upload it for iPhone 6+ in iTunes Connect, and I don't have an iPhone 6+ Device.

Is there a way to make an App Preview (Video) for iPhone 6+ without the device ?

答:
You can generate the video from the simulator by running through the following steps.

Get your app running in the simulator.

I believe you will need to run the simulator at 100% scale to ensure 1080:1920

Open up Terminal and run the following command

$ xcrun simctl io booted recordVideo /path/Video.mov

Switch to your simulator window and run through your demo

When you have finished your demo switch back to your terminal window and Press CTL+C to stop the recording

Edit the movie in iMovie

In order to upload as an App Preview then it will need to be < 30 seconds. You can cut the video down a little, or speed some sections up in order to get it under 30 seconds.

Once you have finished editing the movie you can then export it (File->Share->iTunes)

This will save it to your iTunes library:

/Users/marcbeavan/Music/iTunes/iTunes Media/Home Videos/

This file is ready to be uploaded to iTunes Connect

File info for my video is shown below

Title: iOS App Preview without iPhone 6 Plus


问:
Angular 1 vs React
I have been using Angular 1 for a while now and am now starting to learn React but cannot figure out the main difference between the two. Seems like React is all about creating components, but can't we do the same in Angular using directives? I'm still at the very beginner level of react (learning through codeschool).

It would be very helpful if someone could provide one case and show me how to solve it using angular 1 and then react.

Below is what I've done in React so far (creating a CommentBox component that will display comments from the Comment component). How could I do this in angular 1 for example so I can see the difference.

CommentBox Component:

```<code>class CommentBox extends React.Component {

  render() {
    const comments = this._getComments() || [];

    return(
      <div className="comment-box">
        <h3>Comments</h3>

        <div className="comment-list">
          {comments}
        </div>
      </div>
    );
  }

  _getComments() {
    const commentList = [
      { id: 1, author: 'Clu', body: 'Just say no to love!', avatarUrl: 'images/default-avatar.png' },
      { id: 2, author: 'Anne Droid', body: 'I wanna know what love is...', avatarUrl: 'images/default-avatar.png' }
    ];

    return commentList.map((comment) => {
      return (<Comment
               author={comment.author}
               body={comment.body}
               avatarUrl={comment.avatarUrl}
               key={comment.id} />);
    });
  }

}
</code>```

Comment Component:

```<code>class Comment extends React.Component {

  render() {

    return(
      <div className="comment">
        <img src={this.props.avatarUrl} alt={`${this.props.author}'s picture`} />
        <p className="comment-header">{this.props.author}</p>
        <p className="comment-body">
          {this.props.body}
        </p>

      </div>
    );
  }

}
</code>```

答:
Bit of background I'm primarily a Angular developer but have dabbled a bit with React and have friends who use React heavily at their day jobs so have some exposure to the differences.

Differences from a developer perspective seem to mostly be that Angular gives you some helper services for common front end tasks and has a built in mechanism for monitoring the data model and updating the view (data binding) and has a built in mechanism for dependency injection ($injector).

React will typically get better performance since it has a virtual in memory copy of the DOM that it applies changes to first then it diffs that against the previous virtual DOM to see what actual changes need to be applied to the real DOM and then it applies those changes (DOM access like reading the size of elements is costly).  The flux way of managing the data model through actions is slightly different and typically gets better performance than the digest cycle that runs in angular where all the registered watchers get triggered to check if their value has changed any time a digest occurs (digests/apply cycles in angular can be applied to a scope but ones from $http calls and the like trigger it on $rootScope so all watchers from any interpolations or manually set up watchers in directives have to run their check function to see if the value has changed and do a comparison).

Angular 2+ they played with taking the VirtualDOM concept but I'm pretty sure they ultimately decided it wasn't worth the complexity for the time gain after they had already optimized the digest or eliminated the old process for updating watchers and replaced it with a one way data flow (similar to how flux is working from what I gather).  Upgrading a ng1 app to ng2 or a component from ng1 to ng2 should see about a 7x performance gain on the digest cycle based on what they showed in ng-conf a while back.  You can also code things in ng1 to avoid having thousands of watchers in the view but it takes more work than just doing everything the naive way.

```<code>angular.module('myApp', [])
  .directive('comment', function(){
    return {
      restrict: 'A', //Will match directive name as an attribute <div comment>
      scope: {commment:'='},
      template: `<div className="comment">
        <img src="{{comment.avatarUrl}}" alt="{{comment.author}}'s picture" />
        <p className="comment-header">{{comment.author}}</p>
        <p className="comment-body">
          {{comment.body}}
        </p>

      </div>`,
     // either use babel for this or typically have the
     // template in a separate file with a templateURL pointing to it,
     // could also use the old array.join() way of breaking
     // the template string across multiple lines
    }
  })

.directive('commentBox', function(CommentsService){
    return {
      restrict: 'E', //Will match the directive against an element <comment-box></comment-box>, uses camel case to hyphen case from JS->HTML
      template: `<div comment="commentDatum" ng-repeat="commentDatum in comments"></div>`,
      link:function(scope){
        CommentsService.getComments().then( response => scope.comments = response.data)
      }
    }
  })

  .service('CommentService', function($http){
    return {
      getComments: () => $http.get('mysite.com/commentsEndpoint')
    }
  }) //I did some half baked ES6 version here but could define a class and use that for the service instead is a bit cleaner but maybe clearer this way that $http is being injected by the framework, the CommentService is also automatically injected into the directive since we list it in the params.
</code>```

Usage in the container looks like:

```<code><comment-box></comment-box>
</code>```

Also to add you can use Angular and React together but have never tried it myself so can't speak to how that works in reality.

Title: Angular 1 vs React

Body:
I have been using Angular 1 for a while now and am now starting to learn React but cannot figure out the main difference between the two. Seems like React is all about creating components, but can't we do the same in Angular using directives? I'm still at the very beginner level of react (learning through codeschool).

It would be very helpful if someone could provide one case and show me how to solve it using angular 1 and then react.

Below is what I've done in React so far (creating a CommentBox component that will display comments from the Comment component). How could I do this in angular 1 for example so I can see the difference.

CommentBox Component:

class CommentBox extends React.Component {

  render() {
    const comments = this._getComments() || [];

    return(

Comments

          {comments}

    );
  }

  _getComments() {
    const commentList = [
      { id: 1, author: 'Clu', body: 'Just say no to love!', avatarUrl: 'images/default-avatar.png' },
      { id: 2, author: 'Anne Droid', body: 'I wanna know what love is...', avatarUrl: 'images/default-avatar.png' }
    ];

    return commentList.map((comment) => {
      return (<Comment
               author={comment.author}
               body={comment.body}
               avatarUrl={comment.avatarUrl}
               key={comment.id} />);
    });
  }

}

Comment Component:

class Comment extends React.Component {

  render() {

    return(

        <img src={this.props.avatarUrl} alt={`${this.props.author}'s picture`} />

{this.props.author}

          {this.props.body}

    );
  }

}

Body:
Bit of background I'm primarily a Angular developer but have dabbled a bit with React and have friends who use React heavily at their day jobs so have some exposure to the differences.

Differences from a developer perspective seem to mostly be that Angular gives you some helper services for common front end tasks and has a built in mechanism for monitoring the data model and updating the view (data binding) and has a built in mechanism for dependency injection ($injector).

React will typically get better performance since it has a virtual in memory copy of the DOM that it applies changes to first then it diffs that against the previous virtual DOM to see what actual changes need to be applied to the real DOM and then it applies those changes (DOM access like reading the size of elements is costly).  The flux way of managing the data model through actions is slightly different and typically gets better performance than the digest cycle that runs in angular where all the registered watchers get triggered to check if their value has changed any time a digest occurs (digests/apply cycles in angular can be applied to a scope but ones from $http calls and the like trigger it on $rootScope so all watchers from any interpolations or manually set up watchers in directives have to run their check function to see if the value has changed and do a comparison).

Angular 2+ they played with taking the VirtualDOM concept but I'm pretty sure they ultimately decided it wasn't worth the complexity for the time gain after they had already optimized the digest or eliminated the old process for updating watchers and replaced it with a one way data flow (similar to how flux is working from what I gather).  Upgrading a ng1 app to ng2 or a component from ng1 to ng2 should see about a 7x performance gain on the digest cycle based on what they showed in ng-conf a while back.  You can also code things in ng1 to avoid having thousands of watchers in the view but it takes more work than just doing everything the naive way.

angular.module('myApp', [])
  .directive('comment', function(){
    return {
      restrict: 'A', //Will match directive name as an attribute <div comment>
      scope: {commment:'='},
      template: `<div className="comment">
        <img src="{{comment.avatarUrl}}" alt="{{comment.author}}'s picture" />
        <p className="comment-header">{{comment.author}}</p>
        <p className="comment-body">
          {{comment.body}}
        </p>

      </div>`,
     // either use babel for this or typically have the
     // template in a separate file with a templateURL pointing to it,
     // could also use the old array.join() way of breaking
     // the template string across multiple lines
    }
  })

.directive('commentBox', function(CommentsService){
    return {
      restrict: 'E', //Will match the directive against an element <comment-box></comment-box>, uses camel case to hyphen case from JS->HTML
      template: `<div comment="commentDatum" ng-repeat="commentDatum in comments"></div>`,
      link:function(scope){
        CommentsService.getComments().then( response => scope.comments = response.data)
      }
    }
  })

  .service('CommentService', function($http){
    return {
      getComments: () => $http.get('mysite.com/commentsEndpoint')
    }
  }) //I did some half baked ES6 version here but could define a class and use that for the service instead is a bit cleaner but maybe clearer this way that $http is being injected by the framework, the CommentService is also automatically injected into the directive since we list it in the params.

Usage in the container looks like:

<comment-box></comment-box>

Also to add you can use Angular and React together but have never tried it myself so can't speak to how that works in reality.


问:
Can't find CSS rule that is declaring the width of
I am working on some HTML / CSS stuff and for some reason, I have a stray element that is overflowing my body and causing horizontal scroll bars.  Before you say it, I know this is a pretty n00b sounding mistake.  I typically don't have issues like this but I could really use a second set of eyes.

http://easterndancer.com.s66112.gridserver.com/

Can you find the element that's causing the scrolling overflow (horizontal)?

答:
Try to add</p>

```<code><body style="overflow-x:hidden;" class="home page page-id-27 page-template page-template-home-php">
</code>```

Title: Can't find CSS rule that is declaring the width of <body>

Body:
Try to add

<body style="overflow-x:hidden;" class="home page page-id-27 page-template page-template-home-php">


问:
How to call Stored Procedure with Eloquent (Laravel)?
There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

```<code>$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);
</code>```

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

Thanks. Small examples are highly encouraged .

答:
No there is no Facade for that a simple solution is to use a raw SQL query

```<code>$result = DB::select('my_custom_procedure(?, ?)', [1,2]);
</code>```

Body:
There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

Thanks. Small examples are highly encouraged .

Body:
No there is no Facade for that a simple solution is to use a raw SQL query

$result = DB::select('my_custom_procedure(?, ?)', [1,2]);


问:
Spring Boot Mapping Resource of a sub folder
I'm trying to map a sub folder of my resources to server index.html and images associated.

My resources are located inside folder resources/a/b/c. (ie resources/a/b/c/index.html)

I want this html page to be accessible from my root path (http://localhost:8080/index.html).

I'm extending WebMvcConfigurerAdapter to configure the mapping. I tried several path but nothing worked so far.

```<code>@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter
{
   public static void main(String[] args)
   {
      SpringApplication.run(Application.class, args);
   }

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry)
   {
      registry.addResourceHandler("/**").addResourceLocations(
            "classpath:/resources/a/b/c",
            "classpath:/a/b/c",
            "/resources/a/b/c",
            "/a/b/c",
            "classpath:resources/a/b/c",
            "classpath:a/b/c",
            "resources/a/b/c",
            "a/b/c");
   }
}
</code>```

Can someone give me some guidance on this?

Thanks

答:
From the documentation:

By default Spring Boot will serve static content from a directory
  called /static (or /public or /resources or /META-INF/resources) in
  the classpath or from the root of the ServletContext.

So if you have:

```<code>src
└── main
    └── resources
        └── static
            ├── images
            │       └── image.png
            └── index.html
</code>```

You can access your resources via :

```<code>http://localhost:8080/ (index.html)
http://localhost:8080/index.html
http://localhost:8080/images/image.png
</code>```

Notice that you must not add static in the url and must restart the server when adding a new resource.

Body:
I'm trying to map a sub folder of my resources to server index.html and images associated.

My resources are located inside folder resources/a/b/c. (ie resources/a/b/c/index.html)

I want this html page to be accessible from my root path (http://localhost:8080/index.html).

I'm extending WebMvcConfigurerAdapter to configure the mapping. I tried several path but nothing worked so far.

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter
{
   public static void main(String[] args)
   {
      SpringApplication.run(Application.class, args);
   }

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry)
   {
      registry.addResourceHandler("/**").addResourceLocations(
            "classpath:/resources/a/b/c",
            "classpath:/a/b/c",
            "/resources/a/b/c",
            "/a/b/c",
            "classpath:resources/a/b/c",
            "classpath:a/b/c",
            "resources/a/b/c",
            "a/b/c");
   }
}

Can someone give me some guidance on this?

Thanks

Body:
From the documentation:

By default Spring Boot will serve static content from a directory
  called /static (or /public or /resources or /META-INF/resources) in
  the classpath or from the root of the ServletContext.

So if you have:

src
└── main
    └── resources
        └── static
            ├── images
            │       └── image.png
            └── index.html

You can access your resources via :

http://localhost:8080/ (index.html)
http://localhost:8080/index.html
http://localhost:8080/images/image.png

Notice that you must not add static in the url and must restart the server when adding a new resource.


问:
Java split function gives me a small length of result String array
I have this code:

```<code>String string = "_a_b___";
String[] parts = string.split("_");
</code>```

The result is that variable parts has only three elements

```<code>parts[0] = ""
parts[1] = "a"
parts[2] = "b"
</code>```

This is weird, because there are five "_" chars, so after splitting there should be six elements, not only three of them.

I want

```<code>parts[0] = ""
parts[1] = "a"
parts[2] = "b"
parts[3] = ""
parts[4] = ""
parts[5] = ""
</code>```

How to do that? Thank you very much!

答:
From Java documentation:-

Trailing empty strings are therefore not included in the resulting
  array.

Trysplit("_",6)

Body:
I have this code:

String string = "_a_b___";
String[] parts = string.split("_");

The result is that variable parts has only three elements

parts[0] = ""
parts[1] = "a"
parts[2] = "b"

This is weird, because there are five "_" chars, so after splitting there should be six elements, not only three of them.

I want

parts[0] = ""
parts[1] = "a"
parts[2] = "b"
parts[3] = ""
parts[4] = ""
parts[5] = ""

How to do that? Thank you very much!


问:
VBA: Problems with Application.CountIf
I have a stupid problem and don't know why..

I want to Import some values from another workbook.

Procedure:

-Open the other Workbook (Source)

-Get the needed Data Range.

-Copy the Data

-Get the number of appearances of node* to make the target Table ready.

-Switch to the target Table and get also the node appearances.

-Expand the target table.

-Paste the data.

My Problem:
It only gets the CountIf Value from Sorce table..

Below some Information:

```<code>Sub import_kundenform()

Dim LR As Long
Dim rng As Range
Dim rng2 As Range
Dim ActRow As Integer

actwb = ActiveWorkbook.Name
actsh = ActiveSheet.Name

fName = Application _
.GetOpenFilename("Excel Files (*.xls), *.xls")

If fName = False Then
    Exit Sub
End If

Set wb = Workbooks.Open(fName)
startCell = 19
wb.Activate
LR = Cells(Rows.Count, "A").End(xlUp).Row

Set rng = Range("B1:B" & LR)
wb.Sheets(1).Range("A7:L" & LR).Copy
ival = Application.CountIf(rng, "node*")
Workbooks(actwb).Worksheets(actsh).Activate

ival2 = Application.CountIf(rng, "node*")
If ival > ival2 Then
    ActRow = ival - ival2 + startCell
    Range("A20:A" & ActRow).EntireRow.Insert
ElseIf ival < ival2 Then
    ActRow = ival2 - ival + startCell
    Range("A20:A" & ActRow).EntireRow.Insert
End If
Workbooks(actwb).Sheets(actsh).Range("A1").PasteSpecial Paste:=xlPasteValues

End Sub
</code>```

If there are any information you need to know please let me know.

I hope you could help me.

答:
```<code>wb.Activate
LR = Cells(Rows.Count, "A").End(xlUp).Row

Set rng = Range("B1:B" & LR)
wb.Sheets(1).Range("A7:L" & LR).Copy
ival = Application.CountIf(rng, "node*")

Workbooks(actwb).Worksheets(actsh).Activate
ival2 = Application.CountIf(rng, "node*")
If ival > ival2 Then
</code>```

Both ival and ival2 were calculated from the same range rng. Activating another workbook or worksheet will not change the rng range variable.

You wanted to get ival2 from the same range on another wb/ws after activating it, try

```<code> ival2 = Application.CountIf(Range(rng.Address), "node*")
 '                           ^^^^^^^^^^^^^^^^^^
</code>```

Which will now refer to the same range but in the Active worksheet.

However, it is highly recommended to drop using the Activate stuff altogether and work always with fully qualified ranges.

```<code>  Set wb = Workbooks.Open(fName)
  startCell = 19
   'wb.Activate    ' <----------drop this
  With wb.Sheets(1)
    LR = .Cells(.Rows.count, "A").End(xlUp).row
    Set rng = .Range("B1:B" & LR)
    .Range("A7:L" & LR).Copy
    ival = Application.CountIf(rng, "node*")
  End With

  'Workbooks(actwb).Worksheets(actsh).Activate      ' <----------drop this
  With Workbooks(actwb).Worksheets(actsh)
    ival2 = Application.CountIf(.Range(rng.Address), "node*")
    If ival > ival2 Then
      ActRow = ival - ival2 + startCell
      .Range("A20:A" & ActRow).EntireRow.Insert
    ElseIf ival < ival2 Then
      ActRow = ival2 - ival + startCell
      .Range("A20:A" & ActRow).EntireRow.Insert
    End If
    .Range("A1").PasteSpecial Paste:=xlPasteValues
  End With
</code>```

Title: VBA: Problems with Application.CountIf

Body:
I have a stupid problem and don't know why..

I want to Import some values from another workbook.

Procedure:

-Open the other Workbook (Source)

-Get the needed Data Range.

-Copy the Data

-Get the number of appearances of node* to make the target Table ready.

-Switch to the target Table and get also the node appearances.

-Expand the target table.

-Paste the data.

My Problem:
It only gets the CountIf Value from Sorce table..

Below some Information:

Sub import_kundenform()

Dim LR As Long
Dim rng As Range
Dim rng2 As Range
Dim ActRow As Integer

actwb = ActiveWorkbook.Name
actsh = ActiveSheet.Name

fName = Application _
.GetOpenFilename("Excel Files (*.xls), *.xls")

If fName = False Then
    Exit Sub
End If

Set wb = Workbooks.Open(fName)
startCell = 19
wb.Activate
LR = Cells(Rows.Count, "A").End(xlUp).Row

Set rng = Range("B1:B" & LR)
wb.Sheets(1).Range("A7:L" & LR).Copy
ival = Application.CountIf(rng, "node*")
Workbooks(actwb).Worksheets(actsh).Activate

ival2 = Application.CountIf(rng, "node*")
If ival > ival2 Then
    ActRow = ival - ival2 + startCell
    Range("A20:A" & ActRow).EntireRow.Insert
ElseIf ival < ival2 Then
    ActRow = ival2 - ival + startCell
    Range("A20:A" & ActRow).EntireRow.Insert
End If
Workbooks(actwb).Sheets(actsh).Range("A1").PasteSpecial Paste:=xlPasteValues

End Sub

If there are any information you need to know please let me know.

I hope you could help me.

Body:
wb.Activate
LR = Cells(Rows.Count, "A").End(xlUp).Row

Set rng = Range("B1:B" & LR)
wb.Sheets(1).Range("A7:L" & LR).Copy
ival = Application.CountIf(rng, "node*")

Workbooks(actwb).Worksheets(actsh).Activate
ival2 = Application.CountIf(rng, "node*")
If ival > ival2 Then

Both ival and ival2 were calculated from the same range rng. Activating another workbook or worksheet will not change the rng range variable.

You wanted to get ival2 from the same range on another wb/ws after activating it, try

 ival2 = Application.CountIf(Range(rng.Address), "node*")
 '                           ^^^^^^^^^^^^^^^^^^

Which will now refer to the same range but in the Active worksheet.

However, it is highly recommended to drop using the Activate stuff altogether and work always with fully qualified ranges.

  Set wb = Workbooks.Open(fName)
  startCell = 19
   'wb.Activate    ' <----------drop this
  With wb.Sheets(1)
    LR = .Cells(.Rows.count, "A").End(xlUp).row
    Set rng = .Range("B1:B" & LR)
    .Range("A7:L" & LR).Copy
    ival = Application.CountIf(rng, "node*")
  End With

  'Workbooks(actwb).Worksheets(actsh).Activate      ' <----------drop this
  With Workbooks(actwb).Worksheets(actsh)
    ival2 = Application.CountIf(.Range(rng.Address), "node*")
    If ival > ival2 Then
      ActRow = ival - ival2 + startCell
      .Range("A20:A" & ActRow).EntireRow.Insert
    ElseIf ival < ival2 Then
      ActRow = ival2 - ival + startCell
      .Range("A20:A" & ActRow).EntireRow.Insert
    End If
    .Range("A1").PasteSpecial Paste:=xlPasteValues
  End With


问:
Cycling through workspaces in multi monitor setup in XMonad
I'm currently using alt + ctrl + left and alt + ctrl + right to cycle between workspaces:

...

    , ((altModMask .|. controlMask, xK_Left),
      prevWS)
    , ((altModMask .|. controlMask, xK_Right),
      nextWS)
```
<p>This works fine for single monitor setup. However it is a bit confusing when using a dual monitor setup. This is because the workspace to be shown will change screen if currently visible on another screen. For instance if I have ws 1 on screen 0 and ws 2 on screen 1 and have the focus on screen 0:</p>
<pre class="lang-none prettyprint-override"><code>1:term (2:web) 3:txt
</code>```

When I now do a nextWS, ws 2, that was currently on screen 1 will be drawn to screen 0, while screen 1 will show ws 1.

(1:term) 2:web 3:txt
```

What I would like is a behaviour where prexWS and nextWS will jump over the workspace that is currently shown on the other monitor and only select a workspace that is currently not shown.

Are there such commands already or is there some xmonad.hs example that implements this?

答:
Use XMonad.Actions.DynamicWorkspaceOrder from the xmonad-contrib:

import qualified XMonad.Actions.DynamicWorkspaceOrder as DO

...

    , ((altModMask .|. controlMask, xK_Left),
      DO.moveTo Prev HiddenNonEmptyWS)
    , ((altModMask .|. controlMask, xK_Right),
      DO.moveTo Next HiddenNonEmptyWS)
```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently using alt + ctrl + left and alt + ctrl + right to cycle between workspaces:

...

    , ((altModMask .|. controlMask, xK_Left),
      prevWS)
    , ((altModMask .|. controlMask, xK_Right),
      nextWS)

This works fine for single monitor setup. However it is a bit confusing when using a dual monitor setup. This is because the workspace to be shown will change screen if currently visible on another screen. For instance if I have ws 1 on screen 0 and ws 2 on screen 1 and have the focus on screen 0:

1:term (2:web) 3:txt

When I now do a nextWS, ws 2, that was currently on screen 1 will be drawn to screen 0, while screen 1 will show ws 1.

(1:term) 2:web 3:txt

What I would like is a behaviour where prexWS and nextWS will jump over the workspace that is currently shown on the other monitor and only select a workspace that is currently not shown.

Are there such commands already or is there some xmonad.hs example that implements this?


问:
How to import Material Module or NgxBootstrap in Angular Universal?
Currently I am trying to build a project using Angular Universal. I'm using Angular 4. If I import Material Module - the project can be built, but when serving through ts-node an error appears -

```<code>dist\ngfactory\node_modules\@angular\material\typings\index.ngfactory.ts:9
import * as import0 from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Module._extensions..js (module.js:580:10)
</code>```

Or If I try to import NgXBootstrap then this error appears -

```<code>node_modules\ngx-bootstrap\dropdown\bs-dropdown.module.js:1
(function (exports, require, module, __filename, __dirname) { import { NgModule } from '@angular/core';
                                                          ^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
</code>```

I'm following this project structure  - https://github.com/designcourse/angular-seo

I am pasting the code here -

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

//Material Module
import {MaterialModule} from '@angular/material';

//Ngx Bootstrap
import {BsDropdownModule} from 'ngx-bootstrap';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { PostsComponent } from './posts/posts.component';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    PostsComponent
  ],
  imports: [
    BrowserModule.withServerTransition({appId: 'universal-app'}),
    FormsModule,
    HttpModule,
    AppRoutingModule,
    MaterialModule,
    BsDropdownModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]

})
export class AppModule { }
</code>```

app.server.module.ts

```<code>import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
imports: [
    ServerModule,
    AppModule
],
bootstrap: [AppComponent]
})
export class AppServerModule { }
</code>```

server.ts

```<code>import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});
</code>```

I guess this is a problem for all third party libraries in Angular Universal. So, How do I properly import these libraries ?

答:
I would suggest you use this seed project ng-seed/universal instead of the one you are currently following.

Now if you structure your app following ng-seed/universal then for using Material Module and BsDropdownModule you would simply add these lines in client/app/app.module.ts

```<code>import {MaterialModule} from '@angular/material';
import {BsDropdownModule} from 'ngx-bootstrap';
</code>```

Make sure you update your package.json accordingly. Then run :

```<code>npm install

# dev build (Universal)
npm run build:universal-dev
# prod build (Universal)
npm run build:universal-prod

# start the server (Angular Universal)
npm run serve
</code>```

All should be working alright now.

Body:
Currently I am trying to build a project using Angular Universal. I'm using Angular 4. If I import Material Module - the project can be built, but when serving through ts-node an error appears -

dist\ngfactory\node_modules\@angular\material\typings\index.ngfactory.ts:9
import * as import0 from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Module._extensions..js (module.js:580:10)

Or If I try to import NgXBootstrap then this error appears -

node_modules\ngx-bootstrap\dropdown\bs-dropdown.module.js:1
(function (exports, require, module, __filename, __dirname) { import { NgModule } from '@angular/core';
                                                          ^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)

I'm following this project structure  - https://github.com/designcourse/angular-seo

I am pasting the code here -

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

//Material Module
import {MaterialModule} from '@angular/material';

//Ngx Bootstrap
import {BsDropdownModule} from 'ngx-bootstrap';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { PostsComponent } from './posts/posts.component';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    PostsComponent
  ],
  imports: [
    BrowserModule.withServerTransition({appId: 'universal-app'}),
    FormsModule,
    HttpModule,
    AppRoutingModule,
    MaterialModule,
    BsDropdownModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]

})
export class AppModule { }

app.server.module.ts

import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
imports: [
    ServerModule,
    AppModule
],
bootstrap: [AppComponent]
})
export class AppServerModule { }

server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

I guess this is a problem for all third party libraries in Angular Universal. So, How do I properly import these libraries ?

Body:
I would suggest you use this seed project ng-seed/universal instead of the one you are currently following.

Now if you structure your app following ng-seed/universal then for using Material Module and BsDropdownModule you would simply add these lines in client/app/app.module.ts

import {MaterialModule} from '@angular/material';
import {BsDropdownModule} from 'ngx-bootstrap';

Make sure you update your package.json accordingly. Then run :

npm install

# dev build (Universal)
npm run build:universal-dev
# prod build (Universal)
npm run build:universal-prod

# start the server (Angular Universal)
npm run serve

All should be working alright now.


问:
If all my sql server database access is done thru stored procedures
If all my sql server database access is done thru stored procedures, and I plan on continuing that practice, is using linq2sql and/or the entity framework for future projects an unnecessary layer of complexity that doesn't add much value?

Related question: is Microsoft trying to steer developers away from relying on stored procs for data access?

答: No.  LINQ2SQL adds a lot of value in terms of being able to easily map your database entities to classes in your code and work with those classes easily with native langugage constructs.  You can easily map the CRUD operations of the generated entity class onto your stored procedures if you want.  I do find that some things no longer require stored procedures to work easily and so I have moved away from using them, but you are not forced to.  Essentially what LINQ2SQL can do is replace much, if not all, of your DAL, saving you from having to write this code.</p>

OwnerDisplayName: E.J. Brennan

OwnerDisplayName: tvanfosson


问:
Using patch files with TFS (patch file is from subversion, git, etc)
Can patch files be read by TFS or visual studio?  I'd like to either create a shelveset or apply the patch to a workspace in TFS.</p>

答:
I created a feature request here:
https://connect.microsoft.com/VisualStudio/feedback/details/631052/ability-to-import-or-use-a-unified-diff-patch-file-in-tfs</p>


问:
Check if user is close to scrolling to bottom of element
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

```<code><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});
</code>```

答:
I´m no expert in JavaScript and personally I have to go back to the docs every time I need to remember the difference between document, window and viewport when I have to deal with scroll events but I think this will get you on track.

Note: this will work with the entire document´s scroll event, try and apply it to your modal's body tag and let me know:

```<code>//in this test case your limit is going to be 20
$(document).scroll(function (){
    if($(this).height() - $(this).scrollTop() - $(window).height() < 20){
        console.log('time to show new content');
    }
});
</code>```

hope it helps

EDIT

```<code>$('.modal-content').scroll(function (){
    if($(this).height() - $(this).scrollTop() - $('.modal-dialog').height() < 20){
        console.log('time to show new content');
    }
});
</code>```

If what u r going for is just for .modal-content to scroll inside .modal-dialog and everytime .modal-content's content is about to run out, append more, then I think this is what you need.

Now if you want the entire (and I really have to emphasize) modal to scroll while the background stands still, please let me know how u were able to achieve it without encapsulating it in anything else.

good luck and let me know

ps: if this works, you should really take a look at Erik Philips' answer.

Body:
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

JS:

$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});

Body:
I´m no expert in JavaScript and personally I have to go back to the docs every time I need to remember the difference between document, window and viewport when I have to deal with scroll events but I think this will get you on track.

Note: this will work with the entire document´s scroll event, try and apply it to your modal's body tag and let me know:

//in this test case your limit is going to be 20
$(document).scroll(function (){
    if($(this).height() - $(this).scrollTop() - $(window).height() < 20){
        console.log('time to show new content');
    }
});

hope it helps

EDIT

$('.modal-content').scroll(function (){
    if($(this).height() - $(this).scrollTop() - $('.modal-dialog').height() < 20){
        console.log('time to show new content');
    }
});

If what u r going for is just for .modal-content to scroll inside .modal-dialog and everytime .modal-content's content is about to run out, append more, then I think this is what you need.

Now if you want the entire (and I really have to emphasize) modal to scroll while the background stands still, please let me know how u were able to achieve it without encapsulating it in anything else.

good luck and let me know

ps: if this works, you should really take a look at Erik Philips' answer.


问:
Extracting p within h1 with Python/Scrapy
I am using Scrapy to extract some data about musical concerts from websites. At least one website I'm working with uses (incorrectly, according to W3C - Is it valid to have paragraph elements inside of a heading tag in HTML5 (P inside H1)?) a p element within an h1 element. I need to extract the text within the p element nevertheless, and cannot figure out how.

I have read the documentation and looked around for example uses, but am relatively new to Scrapy. I understand the solution has something to do with setting the Selector type to "xml" rather than "html" in order to recognize any XML tree, but for the life of me I cannot figure out how or where to do that in this instance.

For example, a website has the following HTML:

```<code><h1 class="performance-title">
<p>Bernard Haitink conducts Brahms and Dvořák featuring pianist     Emanuel Ax
</p>
</h1>
</code>```

I have made an item called Concert() that has a value called 'title'.  In my item loader, I use:

```<code>def parse_item(self, response):
    thisconcert = ItemLoader(item=Concert(), response=response)
    thisconcert.add_xpath('title','//h1[@class="performance-title"]/p/text()')

    return thisconcert.load_item()
</code>```

This returns, in item['title'], a unicode list that does not include the text inside the p element, such as:

```<code>['\n                 ', '\n                 ', '\n                ']
</code>```

I understand why, but I don't know how to get around it. I have also tried things like:

```<code>from scrapy import Selector

def parse_item(self, response):

    s = Selector(text=' '.join(response.xpath('.//section[@id="performers"]/text()').extract()), type='xml')
</code>```

What am I doing wrong here, and how can I parse HTML that contains this problem (p within h1)?

I have referenced the information concerning this specific issue at Behavior of the scrapy xpath selector on h1-h6 tags but it does not provide a complete solution that can be applied to a spider, only an example within a session using a given text string.

Body:
I am using Scrapy to extract some data about musical concerts from websites. At least one website I'm working with uses (incorrectly, according to W3C - Is it valid to have paragraph elements inside of a heading tag in HTML5 (P inside H1)?) a p element within an h1 element. I need to extract the text within the p element nevertheless, and cannot figure out how.

I have read the documentation and looked around for example uses, but am relatively new to Scrapy. I understand the solution has something to do with setting the Selector type to "xml" rather than "html" in order to recognize any XML tree, but for the life of me I cannot figure out how or where to do that in this instance.

For example, a website has the following HTML:

Bernard Haitink conducts Brahms and Dvořák featuring pianist     Emanuel Ax

I have made an item called Concert() that has a value called 'title'.  In my item loader, I use:

def parse_item(self, response):
    thisconcert = ItemLoader(item=Concert(), response=response)
    thisconcert.add_xpath('title','//h1[@class="performance-title"]/p/text()')

    return thisconcert.load_item()

This returns, in item['title'], a unicode list that does not include the text inside the p element, such as:

['\n                 ', '\n                 ', '\n                ']

I understand why, but I don't know how to get around it. I have also tried things like:

from scrapy import Selector

def parse_item(self, response):

    s = Selector(text=' '.join(response.xpath('.//section[@id="performers"]/text()').extract()), type='xml')

What am I doing wrong here, and how can I parse HTML that contains this problem (p within h1)?

I have referenced the information concerning this specific issue at Behavior of the scrapy xpath selector on h1-h6 tags but it does not provide a complete solution that can be applied to a spider, only an example within a session using a given text string.

Body: //*[@id="content"]/section/article/section[2]/h1/p/text()


问:
Google Cloud Dataflow, BigQueryIO and NullPointerException on TableRow.get
I'm new to GC Dataflow and didn't find a relevant answer here. Apologies if I should have found this already answered.

I'm trying to create a simple pipeline using the v2.0 SDK and am having trouble reading data into my PCollection using BigQueryIO. I am using the .withQuery method and I have tested the query in the BigQuery interface and it seems to be working fine. The initial PCollection seems to get created without any issues, but when I think setup a simple ParDo function to convert the values from the TableRow into a PCollection I am getting a NullPointerException on the line of code that does the .get on the TableRow object.

Here is my code. (I'm probably missing something simple. I'm a total newbie at Pipeline programming. Any input would be most appreciated.)

```<code>public class ClientAutocompletePipeline {
    private static final Logger LOG = LoggerFactory.getLogger(ClientAutocompletePipeline.class);

    public static void main(String[] args) {
        //  create the pipeline
        Pipeline p = Pipeline.create(
                PipelineOptionsFactory.fromArgs(args).withValidation().create());

        // A step to read in the product names from a BigQuery table
        p.apply(BigQueryIO.read().fromQuery("SELECT name FROM [beaming-team-169321:Products.raw_product_data]"))

        .apply("ExtractProductNames", ParDo.of(new DoFn<TableRow, String>() {
            @ProcessElement
            public void processElement(ProcessContext c) {
                // Grab a row from the BigQuery Results
                TableRow row = c.element();

                // Get the value of the "name" column from the table row.
                //NOTE: This is the line that is giving me the NullPointerException
                String productName = row.get("name").toString();

                // Make sure it isn't empty
                if (!productName.isEmpty()) {
                    c.output(productName);
                }
            }
        }))
</code>```

The query definitely works in the BigQuery UI and the column called "name" is returned when I test the query. Why am I getting a NullPointerException on this line:

```<code>String productName = row.get("name").toString();
</code>```

Any ideas?

答: This is a common problem when working with BigQuery and Dataflow (most likely the field is indeed null). If you are ok with using Scala, you could take a look at Scio (which is a Scala DSL for Dataflow) and its BigQuery IO.

Body:
I'm new to GC Dataflow and didn't find a relevant answer here. Apologies if I should have found this already answered.

I'm trying to create a simple pipeline using the v2.0 SDK and am having trouble reading data into my PCollection using BigQueryIO. I am using the .withQuery method and I have tested the query in the BigQuery interface and it seems to be working fine. The initial PCollection seems to get created without any issues, but when I think setup a simple ParDo function to convert the values from the TableRow into a PCollection I am getting a NullPointerException on the line of code that does the .get on the TableRow object.

Here is my code. (I'm probably missing something simple. I'm a total newbie at Pipeline programming. Any input would be most appreciated.)

public class ClientAutocompletePipeline {
    private static final Logger LOG = LoggerFactory.getLogger(ClientAutocompletePipeline.class);

    public static void main(String[] args) {
        //  create the pipeline
        Pipeline p = Pipeline.create(
                PipelineOptionsFactory.fromArgs(args).withValidation().create());

        // A step to read in the product names from a BigQuery table
        p.apply(BigQueryIO.read().fromQuery("SELECT name FROM [beaming-team-169321:Products.raw_product_data]"))

        .apply("ExtractProductNames", ParDo.of(new DoFn<TableRow, String>() {
            @ProcessElement
            public void processElement(ProcessContext c) {
                // Grab a row from the BigQuery Results
                TableRow row = c.element();

                // Get the value of the "name" column from the table row.
                //NOTE: This is the line that is giving me the NullPointerException
                String productName = row.get("name").toString();

                // Make sure it isn't empty
                if (!productName.isEmpty()) {
                    c.output(productName);
                }
            }
        }))

The query definitely works in the BigQuery UI and the column called "name" is returned when I test the query. Why am I getting a NullPointerException on this line:

String productName = row.get("name").toString();

Any ideas?