问:
How to get row count using ResultSet in Java?
I'm trying to create a simple method that receives a ResultSet as a parameter and returns an int that contains the row count of the ResultSet. Is this a valid way of doing this or not so much?

```<code>int size = 0;
    try {
        while(rs.next()){
            size++;
        }
    }
    catch(Exception ex) {
        System.out.println("------------------Tablerize.getRowCount-----------------");
        System.out.println("Cannot get resultSet row count: " + ex);
        System.out.println("--------------------------------------------------------");
    }
</code>```

I tried this:

```<code>int size = 0;
try {
    resultSet.last();
    size = resultSet.getRow();
    resultSet.beforeFirst();
}
catch(Exception ex) {
    return 0;
}
return size;
</code>```

But I got an error saying

com.microsoft.sqlserver.jdbc.SQLServerException:
The requested operation is not supported on forward only result sets.
```

答:
The ResultSet has it's methods that move the Cursor back and forth depending on the option provided. By default, it's forward moving(TYPE_FORWARD_ONLY ResultSet type).
Unless CONSTANTS indicating Scrollability and Update of ResultSet properly, you might end up getting an error.
E.g. beforeLast()
This method has no effect if the result set contains no rows.
Throws Error if it's not TYPE_FORWARD_ONLY.

The best way to check if empty rows got fetched --- Just to insert new record after checking non-existence

```<code>if( rs.next() ) {

   Do nothing
} else {
  No records fetched!
}
</code>```

See here

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a simple method that receives a ResultSet as a parameter and returns an int that contains the row count of the ResultSet. Is this a valid way of doing this or not so much?

int size = 0;
    try {
        while(rs.next()){
            size++;
        }
    }
    catch(Exception ex) {
        System.out.println("------------------Tablerize.getRowCount-----------------");
        System.out.println("Cannot get resultSet row count: " + ex);
        System.out.println("--------------------------------------------------------");
    }

I tried this:

int size = 0;
try {
    resultSet.last();
    size = resultSet.getRow();
    resultSet.beforeFirst();
}
catch(Exception ex) {
    return 0;
}
return size;

But I got an error saying

com.microsoft.sqlserver.jdbc.SQLServerException:
The requested operation is not supported on forward only result sets.

Body:
The ResultSet has it's methods that move the Cursor back and forth depending on the option provided. By default, it's forward moving(TYPE_FORWARD_ONLY ResultSet type).
Unless CONSTANTS indicating Scrollability and Update of ResultSet properly, you might end up getting an error.
E.g. beforeLast()
This method has no effect if the result set contains no rows.
Throws Error if it's not TYPE_FORWARD_ONLY.

The best way to check if empty rows got fetched --- Just to insert new record after checking non-existence

if( rs.next() ) {

   Do nothing
} else {
  No records fetched!
}

See here


来源: stackexchange

问:
Exact filter when multiple values/html elements in a cell
This might be more DataTables related than specifically YADCF but I'm asking it here as an obvious enhancement if the feature doesn't exist.

I have a column/s which can contain multiple value 'tags', similar to the YADCF examples. The filters to allow filtering by these tags generate correctly.

JSFiddle here https://jsfiddle.net/wallacio/622704ep/6/

See columns titled Area and Rig (excuse the horrific colours...!)

If I wish to see only the events in South, I need to use filter_match_mode: "exact" (to exclude those in South West, South East etc)

There is an event (8th down in unfiltered view) which contains tags "South" and "South East"
Event containing South and South East tags

When the filtering for "South", this event does not appear, presumably because the exact filter is matching against the contents of the cell as a whole and not against each discrete HTML element within it.

I could change filter_match_mode to "contains" but this would result in events which are tagged "South East" etc appearing, which is undesirable.

I've had a trawl through the source and can see that this is taken into account when generating the filter options, but apparently not when filtering, which is why I wonder if it's a limitation caused by how DataTables filters are implemented.

答:
You can use the filter_type: 'custom_func', and write your own filtering logic for that specific column

```<code>column_number: 0,
filter_type: 'custom_func',
custom_func: myCustomFilterFunction,
data: ['one', 'two', 'three']
</code>```

where myCustomFilterFunction looks something like

```<code>function myCustomFilterFunction(filterVal, columnVal) {
        var found = false;
        if (columnVal === '') {
            return true;
        }
        switch (filterVal) {
        case 'one':
            found = //some logic goes here
            break;
        case 'two':
            found = //some logic goes here
            break;
        case 'three':
            found = //some logic goes here
            break;
        default:
            found = false;
            break;
        }

        if (found) {
            return true;
        }
        return false;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use the filter_type: 'custom_func', and write your own filtering logic for that specific column

column_number: 0,
filter_type: 'custom_func',
custom_func: myCustomFilterFunction,
data: ['one', 'two', 'three']

where myCustomFilterFunction looks something like

function myCustomFilterFunction(filterVal, columnVal) {
        var found = false;
        if (columnVal === '') {
            return true;
        }
        switch (filterVal) {
        case 'one':
            found = //some logic goes here
            break;
        case 'two':
            found = //some logic goes here
            break;
        case 'three':
            found = //some logic goes here
            break;
        default:
            found = false;
            break;
        }

        if (found) {
            return true;
        }
        return false;
}


问:
autocomplete in vaadin?
I'm new to vaadin.  How do I do autocomplete (actually, more like google suggest) on a huge set of data that cannot be loaded in memory, but instead performing a JPA query on every key event.  Is it possible to capture key events on a textfield or combobox?</p>

答:
You may find this link helpful. I guess this is getting fixed in 6.5. There is also an addon if you want to check.

you need to consider this though

field value -> json -> vaadin servlet -> service (spring/ejb/pojo or whatever) -> JPA -> query -> result list (which may be huge initially)

and this all the way back to browser for every key press...

think about the end user's typing speed. By the time 1st keystroke's response comes back from the server, user might have completed the whole word.

Title: autocomplete in vaadin?

ContentLicense: CC BY-SA 2.5


问:
MySQL query aggregate MAX and subquery
Is there a way to get value from a subquery in where inside select?

stop_link Table

```<code>id | duid | domain_id
1  | 1    | 1
2  | 2    | 1
3  | 1    | 2
4  | 2    | 2
5  | 3    | 1
</code>```

Result that I want (assume domain_id = 2)

```<code>duid    | domain_id
3       | 2
</code>```

Query (not working):

```<code>INSERT INTO stop_link (
              duid,

              domain_id)
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)
</code>```

Query working but I wish to avoid the Set Variable:

```<code>SET @domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1);
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link sl
WHERE sl.domain_id = @domain_id;
</code>```

答:
Changed answer based on new info from the comments.  It sounds like you've got only_full_group_by enabled in your sql_mode.  Your query would probably work with that disabled, but the following may also work for you:

```<code>INSERT INTO stop_link (
              duid,

              domain_id)

SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)
-- ORDER by sl.domain_id DESC LIMIT 1 # Removed in favor of the following line
GROUP BY sl.domain_id HAVING MAX(sl.id)
;
</code>```

Note that the subquery may not be returning the stop_domain.id that you want it to be -- you might have intended to select MAX(sd.id), or perhaps you just removed a WHERE sd.url='foo' for clarity's sake.

Title: MySQL query aggregate MAX and subquery

Body:
Is there a way to get value from a subquery in where inside select?

stop_link Table

id | duid | domain_id
1  | 1    | 1
2  | 2    | 1
3  | 1    | 2
4  | 2    | 2
5  | 3    | 1

Result that I want (assume domain_id = 2)

duid    | domain_id
3       | 2

Query (not working):

INSERT INTO stop_link (
              duid,

              domain_id)
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)

Query working but I wish to avoid the Set Variable:

SET @domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1);
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link sl
WHERE sl.domain_id = @domain_id;

Body:
Changed answer based on new info from the comments.  It sounds like you've got only_full_group_by enabled in your sql_mode.  Your query would probably work with that disabled, but the following may also work for you:

INSERT INTO stop_link (
              duid,

              domain_id)

SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)
-- ORDER by sl.domain_id DESC LIMIT 1 # Removed in favor of the following line
GROUP BY sl.domain_id HAVING MAX(sl.id)
;

Note that the subquery may not be returning the stop_domain.id that you want it to be -- you might have intended to select MAX(sd.id), or perhaps you just removed a WHERE sd.url='foo' for clarity's sake.


问:
Instantiating an interface implementation based on a dynamic configuration value
New Gopher here, coming from Java land.

Let's say I have a some generic storage interface:

```<code>package repositories

type Repository interface {
  Get(key string) string
  Save(key string) string
}
</code>```

I support multiple different backends (Redis, Boltdb, etc) by implementing this interface in separate packages. However, each implementation has unique configuration values that need to be passed in. So I define a constructor in each package, something like:

```<code>package redis

type Config struct {
 ...
}

func New(config *Config) *RedisRepository {
  ...
}
</code>```

and

```<code>package bolt

type Config struct {
  ...
}

func New(config *Config) *BoltRepository {
  ...
}
</code>```

main.go reads a json configuration file that looks something like:

```<code>type AppConfig struct {
  DatabaseName string,
  BoltConfig *bolt.Config,
  RedisConfig *redis.Config,
}
</code>```

Based on the value of DatabaseName, the app will instantiate the desired repository. What is the best way to do this? Where do I do it? Right now I'm doing some kind of horrible factoryfactory method which seems very much like a Go anti-pattern.

in my main.go, I have a function that reads the above reflected configuration values, selecting the proper configuration (either BoltConfig or RedisConfig) based on the value of DatabaseName:

```<code>func newRepo(c reflect.Value, repoName string) (repositories.Repository, error) {
    t := strings.Title(repoName)

    repoConfig := c.FieldByName(t).Interface()

    repoFactory, err := repositories.RepoFactory(t)
    if err != nil {
        return nil, err
    }

    return repoFactory(repoConfig)
}
</code>```

and in my repositories package, I have a factory that looks for the repository type and returns a factory function that produces an instantiated repository:

```<code>func RepoFactory(provider string) (RepoProviderFunc, error) {
    r, ok := repositoryProviders[provider]
    if !ok {
        return nil, fmt.Errorf("repository does not exist for provider: %s", r)
    }
    return r, nil
}

type RepoProviderFunc func(config interface{}) (Repository, error)

var ErrBadConfigType = errors.New("wrong configuration type")

var repositoryProviders = map[string]RepoProviderFunc{
    redis: func(config interface{}) (Repository, error) {
        c, ok := config.(*redis.Config)
        if !ok {
            return nil, ErrBadConfigType
        }
        return redis.New(c)
    },
    bolt: func(config interface{}) (Repository, error) {
        c, ok := config.(*bolt.Config)
        if !ok {
            return nil, ErrBadConfigType
        }
        return bolt.New(c)
    },
}
</code>```

bringing it all together, my main.go looks like:

```<code>cfg := &AppConfig{}
err = json.Unmarshal(data, cfg)
if err != nil {
    log.Fatalln(err)
}

c := reflect.ValueOf(*cfg)

repo, err := newRepo(c, cfg.DatabaseName)
if err != nil {
    log.Fatalln(err)
}
</code>```

And yes, the second I was done typing this code I recoiled at the horror I had brought into this world. Can someone please help me escape this factory hell? What's a better way to do this type of thing -i.e selecting an interface implementation at runtime.

答:
Do you need dynamic registration? It seems like the list of backends is already baked into your server because of the AppConfig type, so you may be better just writing the simplest possible factory code:

```<code>func getRepo(cfg *AppConfig) (Repository, error) {
    switch cfg.DatabaseName {
    case "bolt":
        return bolt.New(cfg.BoltConfig), nil
    case "redis":
        return redis.New(cfg.RedisConfig), nil
    }
    return nil, fmt.Errorf("unknown database: %q", cfg.DatabaseName)
}

func main() {
    ...
    var cfg AppConfig
    if err := json.Unmarshal(data, &cfg); err != nil {
        log.Fatalf("failed to parse config: %s", err)
    }
    repo, err := getRepo(&cfg)
    if err != nil {
        log.Fatalln("repo construction failed: %s", err)
    }
   ...
</code>```

}

Sure, you can replace this with generic reflection-based code. But while that saves a few lines of duplicated code and removes the need to update getRepo if you add a new backend, it introduces a whole mess of confusing abstraction, and you're going to have to edit code anyway if you introduce a new backend (for example, extending your AppConfig type), so saving a couple of lines in getRepo is hardly a saving.

It might make sense to move getRepo and AppConfig into a repos package if this code is used by more than one program.

Body:
New Gopher here, coming from Java land.

Let's say I have a some generic storage interface:

package repositories

type Repository interface {
  Get(key string) string
  Save(key string) string
}

I support multiple different backends (Redis, Boltdb, etc) by implementing this interface in separate packages. However, each implementation has unique configuration values that need to be passed in. So I define a constructor in each package, something like:

package redis

type Config struct {
 ...
}

func New(config *Config) *RedisRepository {
  ...
}

and

package bolt

type Config struct {
  ...
}

func New(config *Config) *BoltRepository {
  ...
}

main.go reads a json configuration file that looks something like:

type AppConfig struct {
  DatabaseName string,
  BoltConfig *bolt.Config,
  RedisConfig *redis.Config,
}

Based on the value of DatabaseName, the app will instantiate the desired repository. What is the best way to do this? Where do I do it? Right now I'm doing some kind of horrible factoryfactory method which seems very much like a Go anti-pattern.

in my main.go, I have a function that reads the above reflected configuration values, selecting the proper configuration (either BoltConfig or RedisConfig) based on the value of DatabaseName:

func newRepo(c reflect.Value, repoName string) (repositories.Repository, error) {
    t := strings.Title(repoName)

    repoConfig := c.FieldByName(t).Interface()

    repoFactory, err := repositories.RepoFactory(t)
    if err != nil {
        return nil, err
    }

    return repoFactory(repoConfig)
}

and in my repositories package, I have a factory that looks for the repository type and returns a factory function that produces an instantiated repository:

func RepoFactory(provider string) (RepoProviderFunc, error) {
    r, ok := repositoryProviders[provider]
    if !ok {
        return nil, fmt.Errorf("repository does not exist for provider: %s", r)
    }
    return r, nil
}

type RepoProviderFunc func(config interface{}) (Repository, error)

var ErrBadConfigType = errors.New("wrong configuration type")

var repositoryProviders = map[string]RepoProviderFunc{
    redis: func(config interface{}) (Repository, error) {
        c, ok := config.(*redis.Config)
        if !ok {
            return nil, ErrBadConfigType
        }
        return redis.New(c)
    },
    bolt: func(config interface{}) (Repository, error) {
        c, ok := config.(*bolt.Config)
        if !ok {
            return nil, ErrBadConfigType
        }
        return bolt.New(c)
    },
}

bringing it all together, my main.go looks like:

cfg := &AppConfig{}
err = json.Unmarshal(data, cfg)
if err != nil {
    log.Fatalln(err)
}

c := reflect.ValueOf(*cfg)

repo, err := newRepo(c, cfg.DatabaseName)
if err != nil {
    log.Fatalln(err)
}

And yes, the second I was done typing this code I recoiled at the horror I had brought into this world. Can someone please help me escape this factory hell? What's a better way to do this type of thing -i.e selecting an interface implementation at runtime.

Body:
Do you need dynamic registration? It seems like the list of backends is already baked into your server because of the AppConfig type, so you may be better just writing the simplest possible factory code:

func getRepo(cfg *AppConfig) (Repository, error) {
    switch cfg.DatabaseName {
    case "bolt":
        return bolt.New(cfg.BoltConfig), nil
    case "redis":
        return redis.New(cfg.RedisConfig), nil
    }
    return nil, fmt.Errorf("unknown database: %q", cfg.DatabaseName)
}

func main() {
    ...
    var cfg AppConfig
    if err := json.Unmarshal(data, &cfg); err != nil {
        log.Fatalf("failed to parse config: %s", err)
    }
    repo, err := getRepo(&cfg)
    if err != nil {
        log.Fatalln("repo construction failed: %s", err)
    }
   ...

}

Sure, you can replace this with generic reflection-based code. But while that saves a few lines of duplicated code and removes the need to update getRepo if you add a new backend, it introduces a whole mess of confusing abstraction, and you're going to have to edit code anyway if you introduce a new backend (for example, extending your AppConfig type), so saving a couple of lines in getRepo is hardly a saving.

It might make sense to move getRepo and AppConfig into a repos package if this code is used by more than one program.


问:
SAS macro variable issue- 'File Name value exceeds maximum length'
I'm trying to leverage macro variables (assigned via %LET) for PROC IMPORTS but it's causing the file name to exceed 201 characters.
(ERROR: File Name value exceeds maximum length of 201 characters)

Is there a different way to define variables so that they are passed as values instead of functions?

My old datafile string ends
    DATAFILE="...Files_Submitted\201612\Reconcile\Q42016 Principal balances.xls"

I have changed it to
    DATAFILE="...Files_Submitted\&yrmm.\Reconcile\&quarter. Principal balances.xls"

Using the following variables.

```<code>%LET EOLM= INTNX('MONTH',today(),-&MonthsAgo.);
%LET yrmm= COMPRESS(year(&EOLM.)||PUT(month(&EOLM.),z2.));
%LET qtr = COMPRESS(year(&EOLM.)||COMPRESS('Q'||CEIL(month(&EOLM.)/3)));
</code>```

Thanks in advance for any/all assistance.

答:
You're not actually passing things the right way here - you're mixing two different things, which is causing your issue.

You can either resolve the results of these functions in your macro variables, OR you can store the function calls and treat this as if you'd typed the functions into the data step - so use CATS or something to combine them.

As it is, you're ending up with a filename like "\\path\to\COMPRESS(INTNX(MONTH...", not with the results of those functions, hence your problem.

So, one option:

```<code>DATAFILE= cats("...Files_Submitted\",&yrmm.,"\Reconcile\",&quarter.,"Principal balances.xls";
</code>```

That would let the functions provide their values as you expect.

The other option is to use %SYSFUNC to ask the values to be resolved in the macro variables.  This is the more common way,  though certainly neither is really specifically better for all purposes.

```<code>%LET EOLM= %sysfunc(INTNX(MONTH,%sysfunc(today()),-&MonthsAgo.));
</code>```

And similar for the other two.  Note that I remove the quotes around MONTH as quotes are not used in %SYSFUNC calls (unless you want to use  quote characters themselves, but not as string delimiters).

```<code>%LET yrmm= %sysfunc(year(&EOLM.))%sysfunc(month(&EOLM.),z2.);
</code>```

Note here I put the format in the SYSFUNC call directly; also note that we do not use concatenation characters in macro variables (they just produce text) and typically you don't need to use COMPRESS (though not always).

```<code>%LET qtr = %sysfunc(year(&EOLM.))Q%sysfunc(CEIL(%sysevalf(%sysfunc(month(&EOLM.))/3)));
</code>```

Here we use %SYSEVALF to do the math (normally you can't have noninteger math in macro syntax).  We also remove quotes from Q and just place it in line.

Putting it all together:

```<code>   %let monthsAgo = 3;
   %LET EOLM= %sysfunc(INTNX(MONTH,%sysfunc(today()),-&MonthsAgo.));
   %put &=EOLM;
EOLM=20789
   %LET yrmm= %sysfunc(year(&EOLM.))%sysfunc(month(&EOLM.),z2.);
   %put &=yrmm;
YRMM=201612
   %LET qtr =   %sysfunc(year(&EOLM.))Q%sysfunc(CEIL(%sysevalf(%sysfunc(month(&EOLM.))/3)));
   %put &=qtr;
QTR=2016Q4
</code>```

Of course more easy might have been to use formats for yrmm/qtr...

```<code>%let yrmm = %sysfunc(putn(&eolm.,yymmn6.));
%let qtr  = %sysfunc(putn(&eolm.,yyq6.));
%put &=yrmm &=qtr;
</code>```

Or even (and this might be getting a bit cute) removing the %SYSFUNC from &EOLM and letting the %SYSFUNC format option handle the formatting.  Note here EOLM does not store a number, but stores the text you see on the screen, and the number doesn't get resolved until YRMM or QTR is defined.

```<code>%LET EOLM= INTNX(MONTH,%sysfunc(today()),-&MonthsAgo.);
%let yrmm = %sysfunc(&eolm.,yymmn6.);
%let qtr  = %sysfunc(&eolm.,yyq6.);
%put &=yrmm &=qtr;
</code>```

Body:
I'm trying to leverage macro variables (assigned via %LET) for PROC IMPORTS but it's causing the file name to exceed 201 characters.
(ERROR: File Name value exceeds maximum length of 201 characters)

Is there a different way to define variables so that they are passed as values instead of functions?

My old datafile string ends
    DATAFILE="...Files_Submitted\201612\Reconcile\Q42016 Principal balances.xls"

I have changed it to
    DATAFILE="...Files_Submitted\&yrmm.\Reconcile\&quarter. Principal balances.xls"

Using the following variables.

%LET EOLM= INTNX('MONTH',today(),-&MonthsAgo.);
%LET yrmm= COMPRESS(year(&EOLM.)||PUT(month(&EOLM.),z2.));
%LET qtr = COMPRESS(year(&EOLM.)||COMPRESS('Q'||CEIL(month(&EOLM.)/3)));

Thanks in advance for any/all assistance.

Body:
You're not actually passing things the right way here - you're mixing two different things, which is causing your issue.

You can either resolve the results of these functions in your macro variables, OR you can store the function calls and treat this as if you'd typed the functions into the data step - so use CATS or something to combine them.

As it is, you're ending up with a filename like "\\path\to\COMPRESS(INTNX(MONTH...", not with the results of those functions, hence your problem.

So, one option:

DATAFILE= cats("...Files_Submitted\",&yrmm.,"\Reconcile\",&quarter.,"Principal balances.xls";

That would let the functions provide their values as you expect.

The other option is to use %SYSFUNC to ask the values to be resolved in the macro variables.  This is the more common way,  though certainly neither is really specifically better for all purposes.

%LET EOLM= %sysfunc(INTNX(MONTH,%sysfunc(today()),-&MonthsAgo.));

And similar for the other two.  Note that I remove the quotes around MONTH as quotes are not used in %SYSFUNC calls (unless you want to use  quote characters themselves, but not as string delimiters).

%LET yrmm= %sysfunc(year(&EOLM.))%sysfunc(month(&EOLM.),z2.);

Note here I put the format in the SYSFUNC call directly; also note that we do not use concatenation characters in macro variables (they just produce text) and typically you don't need to use COMPRESS (though not always).

%LET qtr = %sysfunc(year(&EOLM.))Q%sysfunc(CEIL(%sysevalf(%sysfunc(month(&EOLM.))/3)));

Here we use %SYSEVALF to do the math (normally you can't have noninteger math in macro syntax).  We also remove quotes from Q and just place it in line.

Putting it all together:

   %let monthsAgo = 3;
   %LET EOLM= %sysfunc(INTNX(MONTH,%sysfunc(today()),-&MonthsAgo.));
   %put &=EOLM;
EOLM=20789
   %LET yrmm= %sysfunc(year(&EOLM.))%sysfunc(month(&EOLM.),z2.);
   %put &=yrmm;
YRMM=201612
   %LET qtr =   %sysfunc(year(&EOLM.))Q%sysfunc(CEIL(%sysevalf(%sysfunc(month(&EOLM.))/3)));
   %put &=qtr;
QTR=2016Q4

Of course more easy might have been to use formats for yrmm/qtr...

%let yrmm = %sysfunc(putn(&eolm.,yymmn6.));
%let qtr  = %sysfunc(putn(&eolm.,yyq6.));
%put &=yrmm &=qtr;

Or even (and this might be getting a bit cute) removing the %SYSFUNC from &EOLM and letting the %SYSFUNC format option handle the formatting.  Note here EOLM does not store a number, but stores the text you see on the screen, and the number doesn't get resolved until YRMM or QTR is defined.

%LET EOLM= INTNX(MONTH,%sysfunc(today()),-&MonthsAgo.);
%let yrmm = %sysfunc(&eolm.,yymmn6.);
%let qtr  = %sysfunc(&eolm.,yyq6.);
%put &=yrmm &=qtr;


问:
Using cout with basic_string<unsigned char>
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

```<code>#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}
</code>```

This doesn't compile with

```<code>error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')
</code>```

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?

答: Like with, say, a std::vector<char>, there's no obvious "default" behaviour here, so it's not provided out of the box. It can work; you'll just have to define how it works yourself.

Body:
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}

This doesn't compile with

error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?


问:
Encapsulate the properties design pattern
I want to encapsulate the logic how a document is activated(boolean). When a document is activated it should be added to a list of activeDocuments and the flag should be set to true. I want to forbid the direct access to the isActive property.

```<code>class DocumentService {
      private activeDocuments : Map<DocumentModel> = new Map<DocumentModel>();

      // Activates the document and adds it to the list
      activateDocument(document: DocumentModel) {
                document.setActive();
                activeDocuments.set(document.id, document);
      }
}

class DocumentModel {
      private isActive: boolean;

      setActive() {
                this.isActive = true;
      }
}

class DocumentComponent {
      documentSelected() {
           // this.document.setActive()  - SHOULD BE FORBIDDEN because the document is not added to the activedocument list !
           this.documentService.activateDocument(this.document);
      }
}
</code>```

The only solution that i figured out for this problem is to create two interfaces DocumentServiceInterface that has a setActive() method and DocumentInterface that doesn't have it so it prevents the |DocumentComponent to activate the document but the service can still activate the document.

Is there a design pattern/ recipe that can solve this ?

Iterating through the list of documents to check if it's active or not is not an option because the structure is much more complex in the application and the number of documents should scale (for example there could be multiple thousand documents)

答:
you can use Mediator Design Pattern to solve the problem. or if you want to hidden the method to the client code only, you can use es2015 symbol methods,then the code out of your DocumentService & DocumentModel can't access the active method,because the visibility of ACTIVE is only visible in module,the code like as below:

```<code>const ACTIVE = Symbol("active");

class DocumentService {
    private activeDocuments: Map<String,DocumentModel> = new Map<String,DocumentModel>();

    // Activates the document and adds it to the list
    activateDocument(document: DocumentModel) {
        document[ACTIVE]();
        this.activeDocuments.set(document.id, document);
    }

}

class DocumentModel {
    public id: string;
    private isActive: boolean;

    [ACTIVE]() {
        this.isActive = true;
    }
}
</code>```

Body:
I want to encapsulate the logic how a document is activated(boolean). When a document is activated it should be added to a list of activeDocuments and the flag should be set to true. I want to forbid the direct access to the isActive property.

class DocumentService {
      private activeDocuments : Map<DocumentModel> = new Map<DocumentModel>();

      // Activates the document and adds it to the list
      activateDocument(document: DocumentModel) {
                document.setActive();
                activeDocuments.set(document.id, document);
      }
}

class DocumentModel {
      private isActive: boolean;

      setActive() {
                this.isActive = true;
      }
}

class DocumentComponent {
      documentSelected() {
           // this.document.setActive()  - SHOULD BE FORBIDDEN because the document is not added to the activedocument list !
           this.documentService.activateDocument(this.document);
      }
}

The only solution that i figured out for this problem is to create two interfaces DocumentServiceInterface that has a setActive() method and DocumentInterface that doesn't have it so it prevents the |DocumentComponent to activate the document but the service can still activate the document.

Is there a design pattern/ recipe that can solve this ?

Iterating through the list of documents to check if it's active or not is not an option because the structure is much more complex in the application and the number of documents should scale (for example there could be multiple thousand documents)

Body:
you can use Mediator Design Pattern to solve the problem. or if you want to hidden the method to the client code only, you can use es2015 symbol methods,then the code out of your DocumentService & DocumentModel can't access the active method,because the visibility of ACTIVE is only visible in module,the code like as below:

const ACTIVE = Symbol("active");

class DocumentService {
    private activeDocuments: Map<String,DocumentModel> = new Map<String,DocumentModel>();

    // Activates the document and adds it to the list
    activateDocument(document: DocumentModel) {
        document[ACTIVE]();
        this.activeDocuments.set(document.id, document);
    }

}

class DocumentModel {
    public id: string;
    private isActive: boolean;

    [ACTIVE]() {
        this.isActive = true;
    }
}


问:
DLL conflict when building Sitefinity 9.2 with visual studio
When building an instance of Sitefinity 9.2 using visual studio 2013 I get a DLL conflict error.

There was a conflict between "Telerik.Windows.Documents.Core, Version=2015.1.225.40, Culture=neutral, PublicKeyToken=5803cfa389c90ce7" and "Telerik.Windows.Documents.Core, Version=2016.2.421.40, Culture=neutral, PublicKeyToken=5803cfa389c90ce7". (TaskId:7)

The DLL that is causing the issue is their own DLL

References which depend on "Telerik.Windows.Documents.Core, Version=2016.2.421.40, Culture=neutral, PublicKeyToken=5803cfa389c90ce7" []. C:...\bin\Telerik.Web.UI.dll (TaskId:7)
Project file item includes which caused reference "C:...\bin\Telerik.Web.UI.dll". (TaskId:7)

The included DLL for Telerik.Windows.Documents.Core is the older version 2015.1.225.40 and not the newer 2016.2.421.40 version.

Is there a way to resolve this in the web.config (like a binding redirect) or some other method? Being that it is a vendor application should they provide the correct DLL version?

答:
I would check your references on the SitefinityWebApp project.  In some cases I found that you have to delete the reference and then re-add it back.  Also, if you have other projects part of your solution you will need to check those projects for references to that assembly.

Also, something to look into, Sitefinity will allow you to use NuGet packages to manage the assemblies and project references in your solution.  You can see more details about this at the following link...

http://docs.sitefinity.com/upgrade-a-project-that-has-nuget-packages

Hope this helps.


问:
Scheme Language - Background running application - Error Analysis after crash
Do I have any chance to get a stack backtrace or similar
of a running scheme background process. Or to dump an Image
on any exception or error of the running system which I can
examine later ?

EDITED
to be more precise
On Unix I have been running a web application (started in background from shell via &). Now I want to get some debuggable stuff in case of any error. for example stack backtrace, Image Dump (core dump), or such.

this probably is easy to get in Common Lisp, Java or Smalltalk, but I don't have any clue how to achieve this with Scheme.

thanks for any suggestions

答:
What do you mean by scheme background process? There are no scheme reports that has fork or thread support so to run portable scheme in background the shell needs to do this for you.

There are no mention on how to return a value either, but printing to stderr can be done in the standard using the port given by (current-error-port)

For everything else you can try to find SRFIs to make it semi portable and hope your implementation has implemented it or else you are locking yourself in by using non portable code.


问:
YouTube API: How can I get the date/time in which a user marked video as favorite?
I'm accessing the feed of a user's favorite videos through the YouTube API. How can I get the date/time in which he marked each video as favorite?

Update:

Someone pointed out that the YouTube API documentation says that the "Published" date on a user's favorite feed will have the time in which the user marked the video as favorite. But that seems to be false.

For example, check out this video entry:

http://gdata.youtube.com/feeds/api/videos/g2981r_MtHQ

It has a "published" date of 2008-03-19T21:09:09.000Z.

Now let's see the same video in the favorite feed of some user:

http://gdata.youtube.com/feeds/api/users/KeepWatchingTheSkies/favorites

It has a "published" date of 2008-03-19T21:09:09.000Z. Identical.

Here is a different way to get the favorites feed:

http://gdata.youtube.com/feeds/base/users/KeepWatchingTheSkies/favorites

And still we have a "published" date of 2008-03-19T21:09:09.000Z.

Assuming the user was not quick enough to favorite the video on the same millisecond it was published, what's written in the YouTube documentation is probably wrong, and this is not the time in which the user marked the video as favorite.

So my question is: How can I get the time at which a user marked a video as favorite?

答:
I figured it out: The URLs must specify ?v=2 so version 2 of the API will be used.

Here's the fixed URL:

http://gdata.youtube.com/feeds/api/users/KeepWatchingTheSkies/favorites?v=2

Now it shows a correct "published" time of 2010-09-03T08:59:53.000Z.


问:
Parsing a .csv file to xml with Java
Hello all so i'm trying to make a program that converts data from a .csv file, build a DOM representation of the .csv file and then output it to an xml file.

I have the .csv file being parsed at the moment with the code below but i'm not sure how to go about taking this information and building a DOM representation. I've read around and came across 'jaxb' but it seem

The .csv file information

```<code>QUESTIONS,Comment,Yes,Comment,No,Comment,Sit,Comment,Stand,Comment,Blank,Comment,Optional,Comment
Is there free circulation of air through and about the building in which you work?,a,468,,249,,,,,,93,,,
"Are there offensive odors in the rooms occupied by employees; if so, from what causes?",b,342,,233,,,,,,235,,,
Are there facilities for washing?,c,460,,124,,,,,,226,,,
"Are seats provided, as prescribed by law?",,320,,192,,,,,,298,,,
Are employees furnished with pure drinking water?,d,527,,102,,,,,,181,,,
Does the work require the employees to stoop over?,,587,,116,,,,,,107,,,
Are there proper and separate facilities for change of dress by males and females?,e,354,,221,,,,,,235,,,
Are there separate water-closets for males and females?,f,509,,126,g,,,,,175,,,
Are there stairways from the windows outside?,,350,,318,,,,,,148,,,
Are the rooms supplied with water pipes?,,265,,385,,,,,,165,,,
Are there hose attachments?,,224,,375,,,,,,218,,,
Are employees compelled to stand or sit at their work?,h,,,,,469,,175,,99,,67,
Are there water tanks and buckets on each floor?,,236,,387,,,,,,198,,,
</code>```

The parser class.

```<code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class parserClass {

@SuppressWarnings("rawtypes")
   public static void main(String[] args) throws Exception {
               String splitBy = ",";
       BufferedReader br = new BufferedReader(new FileReader("surveydata.csv"));
       String line = br.readLine();
       while((line = br.readLine()) !=null){
            String[] b = line.split(splitBy);
           System.out.println(Arrays.toString(b));
       }
       br.close();

 }
}*
</code>```

The information it outputs to the console

```<code>  [Is there free circulation of air through and about the building in which you work?, a, 468, , 249, , , , , , 93]
["Are there offensive odors in the rooms occupied by employees; if so,  from what causes?", b, 342, , 233, , , , , , 235]
[Are there facilities for washing?, c, 460, , 124, , , , , , 226]
["Are seats provided,  as prescribed by law?", , 320, , 192, , , , , , 298]
[Are employees furnished with pure drinking water?, d, 527, , 102, , , , , , 181]
[Does the work require the employees to stoop over?, , 587, , 116, , , , , , 107]
[Are there proper and separate facilities for change of dress by males and females?, e, 354, , 221, , , , , , 235]
[Are there separate water-closets for males and females?, f, 509, , 126, g, , , , , 175]
[Are there stairways from the windows outside?, , 350, , 318, , , , , , 148]
[Are the rooms supplied with water pipes?, , 265, , 385, , , , , , 165]
[Are there hose attachments?, , 224, , 375, , , , , , 218]
[Are employees compelled to stand or sit at their work?, h, , , , , 469, , 175, , 99, , 67]
[Are there water tanks and buckets on each floor?, , 236, , 387, , , , , , 198]
</code>```

答:
Perhaps a simple, low-code, option is to use Jackson for this. There is a Jackson CSV module that will read CSV files (with a defined schema - in this case you can use the header row), and then emit it back to XML (another free behaviour).

One can read the CSV using:

```<code>CsvSchema bootstrap = CsvSchema.emptySchema().withHeader();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader(Map.class).with(bootstrap).readValues(file);
</code>```

and then emit it as XML using something like:

```<code>XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(mappingIterator.next....
</code>```

There are, of course, many other options for doing this. At the very least use a CSV parser such as Apache Commons CSV and don't attempt to parse the CSV by hand (there are too many potential problems, most of which have been robustly solved already).

Title: Parsing a .csv file to xml with Java

Body:
Hello all so i'm trying to make a program that converts data from a .csv file, build a DOM representation of the .csv file and then output it to an xml file.

I have the .csv file being parsed at the moment with the code below but i'm not sure how to go about taking this information and building a DOM representation. I've read around and came across 'jaxb' but it seem

The .csv file information

QUESTIONS,Comment,Yes,Comment,No,Comment,Sit,Comment,Stand,Comment,Blank,Comment,Optional,Comment
Is there free circulation of air through and about the building in which you work?,a,468,,249,,,,,,93,,,
"Are there offensive odors in the rooms occupied by employees; if so, from what causes?",b,342,,233,,,,,,235,,,
Are there facilities for washing?,c,460,,124,,,,,,226,,,
"Are seats provided, as prescribed by law?",,320,,192,,,,,,298,,,
Are employees furnished with pure drinking water?,d,527,,102,,,,,,181,,,
Does the work require the employees to stoop over?,,587,,116,,,,,,107,,,
Are there proper and separate facilities for change of dress by males and females?,e,354,,221,,,,,,235,,,
Are there separate water-closets for males and females?,f,509,,126,g,,,,,175,,,
Are there stairways from the windows outside?,,350,,318,,,,,,148,,,
Are the rooms supplied with water pipes?,,265,,385,,,,,,165,,,
Are there hose attachments?,,224,,375,,,,,,218,,,
Are employees compelled to stand or sit at their work?,h,,,,,469,,175,,99,,67,
Are there water tanks and buckets on each floor?,,236,,387,,,,,,198,,,

The parser class.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class parserClass {

@SuppressWarnings("rawtypes")
   public static void main(String[] args) throws Exception {
               String splitBy = ",";
       BufferedReader br = new BufferedReader(new FileReader("surveydata.csv"));
       String line = br.readLine();
       while((line = br.readLine()) !=null){
            String[] b = line.split(splitBy);
           System.out.println(Arrays.toString(b));
       }
       br.close();

 }
}*

The information it outputs to the console

  [Is there free circulation of air through and about the building in which you work?, a, 468, , 249, , , , , , 93]
["Are there offensive odors in the rooms occupied by employees; if so,  from what causes?", b, 342, , 233, , , , , , 235]
[Are there facilities for washing?, c, 460, , 124, , , , , , 226]
["Are seats provided,  as prescribed by law?", , 320, , 192, , , , , , 298]
[Are employees furnished with pure drinking water?, d, 527, , 102, , , , , , 181]
[Does the work require the employees to stoop over?, , 587, , 116, , , , , , 107]
[Are there proper and separate facilities for change of dress by males and females?, e, 354, , 221, , , , , , 235]
[Are there separate water-closets for males and females?, f, 509, , 126, g, , , , , 175]
[Are there stairways from the windows outside?, , 350, , 318, , , , , , 148]
[Are the rooms supplied with water pipes?, , 265, , 385, , , , , , 165]
[Are there hose attachments?, , 224, , 375, , , , , , 218]
[Are employees compelled to stand or sit at their work?, h, , , , , 469, , 175, , 99, , 67]
[Are there water tanks and buckets on each floor?, , 236, , 387, , , , , , 198]

Body:
Perhaps a simple, low-code, option is to use Jackson for this. There is a Jackson CSV module that will read CSV files (with a defined schema - in this case you can use the header row), and then emit it back to XML (another free behaviour).

One can read the CSV using:

CsvSchema bootstrap = CsvSchema.emptySchema().withHeader();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader(Map.class).with(bootstrap).readValues(file);

and then emit it as XML using something like:

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(mappingIterator.next....

There are, of course, many other options for doing this. At the very least use a CSV parser such as Apache Commons CSV and don't attempt to parse the CSV by hand (there are too many potential problems, most of which have been robustly solved already).


答:
You need to select the maximum seqNr per liteNr which you can do by SELECT liteNr, MAX(seqNr) ... GROUP BY liteNr. Then you join this back with the table using ON a.liteNr = b.liteNr AND a.seqNr = b.seqNr. Queries like this require two steps. With the first query you query the maximum seqNrs per liteNr but this will only give you two columns (liteNr, seqNrMax) which you now have to look up again in the original table which you can do with a join or a nested select.

However, if you have two rows with a max seqNr then your final result may contain duplicates which you need to be aware of.

```<code>mysql> SELECT `NAME`, `PRICE`,
          `VENDOR`
   FROM `PRODUCTS` `P1`
   WHERE `P1`.`PRICE` = (
    SELECT MIN(`PRICE`)
    FROM `PRODUCTS` `P2`
    WHERE `P2`.`NAME` = `P1`.`NAME`);

mysql> SELECT `P1`.`NAME`, `N` AS `PRICE`,
          `P1`.VENDOR
   FROM `PRODUCTS` `P1`
   JOIN (
    SELECT `NAME`, MIN(`PRICE`) AS `N`
    FROM `PRODUCTS` `P2`
    GROUP BY `NAME`) `P2`
   ON `P1`.`NAME` = `P2`.`NAME`
   WHERE `P1`.`PRICE` = `N`;
</code>```

Are the two most common ways to do these kind of queries but there are like at least three additional other ways to do it.

Title: MySQL select distinct and max with all columns

Body:
I have a db table: pf_pqs:

+----------+------+--------+-------+---------+
|    onr   | prSh | liteNr | seqNr | planQty |
+----------+------+--------+-------+---------+
| 10347006 | HEG  |    1   |    0  |   5     |
| 10347006 | TEH  |    1   |    1  |   5     |
| 10347006 | KAR  |    1   |    2  |   5     |
| 10347006 | LEN  |    1   |    3  |   5     |
| 10347006 | HEG  |    2   |    0  |   5     |
| 10347006 | LEN  |    2   |    1  |   5     |
| 10347006 | HEG  |    3   |    0  |   5     |
| 10347006 | TEH  |    3   |    1  |   5     |
| 10347006 | KAR  |    3   |    2  |   5     |
| 10347006 | LEN  |    3   |    3  |   5     |

Result must include biggest seqNr in every liteNr and all other corresponding fields correctly; like this:

+----------+------+--------+-------+---------+
|    onr   | prSh | liteNr | seqNr | planQty |
+----------+------+--------+-------+---------+
| 10347006 | LEN  |    1   |    3  |   5     |
| 10347006 | LEN  |    2   |    1  |   5     |
| 10347006 | LEN  |    3   |    3  |   5     |

I tried different queries with joins and grouping but no luck so far :(.
Thanks in advance.

Body:
You need to select the maximum seqNr per liteNr which you can do by SELECT liteNr, MAX(seqNr) ... GROUP BY liteNr. Then you join this back with the table using ON a.liteNr = b.liteNr AND a.seqNr = b.seqNr. Queries like this require two steps. With the first query you query the maximum seqNrs per liteNr but this will only give you two columns (liteNr, seqNrMax) which you now have to look up again in the original table which you can do with a join or a nested select.

However, if you have two rows with a max seqNr then your final result may contain duplicates which you need to be aware of.

mysql> SELECT `NAME`, `PRICE`,
          `VENDOR`
   FROM `PRODUCTS` `P1`
   WHERE `P1`.`PRICE` = (
    SELECT MIN(`PRICE`)
    FROM `PRODUCTS` `P2`
    WHERE `P2`.`NAME` = `P1`.`NAME`);

mysql> SELECT `P1`.`NAME`, `N` AS `PRICE`,
          `P1`.VENDOR
   FROM `PRODUCTS` `P1`
   JOIN (
    SELECT `NAME`, MIN(`PRICE`) AS `N`
    FROM `PRODUCTS` `P2`
    GROUP BY `NAME`) `P2`
   ON `P1`.`NAME` = `P2`.`NAME`
   WHERE `P1`.`PRICE` = `N`;

Are the two most common ways to do these kind of queries but there are like at least three additional other ways to do it.


问:
How can we add a UIGestureRecognizer to Outlet Collection?
I'm trying to add a tap gesture to an outlet collection of labels [UILabel], like this:

```<code>@IBOutlet var subLabels: [UILabel]!

    override func viewDidLoad() {
            super.viewDidLoad()

            let tap = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.selectSubLabel(tap:)))
            tap.numberOfTapsRequired = 1
            tap.cancelsTouchesInView = false

            for i in (0..<(subLabels.count)) {
                subLabels[i].addGestureRecognizer(tap)
            }
    }

    func selectSubLabel(tap: UITapGestureRecognizer) {
            print("Gesture Is WORKING!")
        }
</code>```

and i tried to add it on a single label in storyboard; but NONE are working.

答: Please check the User Interaction Enabled Attribute of your UIlabel's in Attribute inspector of Xcode. User Interaction Enabled must be ticked for detecting the tap. Please see the picture below,

Body:
I'm trying to add a tap gesture to an outlet collection of labels [UILabel], like this:

@IBOutlet var subLabels: [UILabel]!

    override func viewDidLoad() {
            super.viewDidLoad()

            let tap = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.selectSubLabel(tap:)))
            tap.numberOfTapsRequired = 1
            tap.cancelsTouchesInView = false

            for i in (0..<(subLabels.count)) {
                subLabels[i].addGestureRecognizer(tap)
            }
    }

    func selectSubLabel(tap: UITapGestureRecognizer) {
            print("Gesture Is WORKING!")
        }

and i tried to add it on a single label in storyboard; but NONE are working.


问:
Java for the web
I posted this question: https://stackoverflow.com/questions/418597/java-and-net-for-php-programmer and the answers I was given didn't really help me out.

I read a few of the tutorials at sun.
The basic syntax I understand. The thing I don't understand and really need to (because I think my company is going to tell me start working with this) is to learn how to work with java for the web. I am a php programmer and I did some asp.net c# a few months ago. I am really not understanding how to work with java on the web.

I installed netbeans.
When I start a web project I also get asked what frameworks I want.
I don't know any java frameworks (I do know about spring but never really worked with it).
Is there no simple tutorial on how to do some java for the web??? I never had these much problems when I was first introduced to php :(

Someone help me out, or at least point me in a good direction.

答:
Since you're using NetBeans, start with the tuturials they have on their site.
http://www.netbeans.org/kb/docs/web/quickstart-webapps.html

Go through the simple tutorials on the site before you start going into the details on any frameworks.

Java webapps are pretty simple. You have your Java classes (.java) that handle your business logic and your .jsp files that handle the presentation. Try and keep them seperate. You also want to familiarize yourself with the JSTL tags and el (expression language) syntax

OwnerDisplayName: AntonioCS

Title: Java for the web


问:
Finding the address range of the data segment
As a programming exercise, I am writing a mark-and-sweep garbage collector in C. I wish to scan the data segment (globals, etc.) for pointers to allocated memory, but I don't know how to get the range of the addresses of this segment. How could I do this?</p>

答:
The bounds for text (program code) and data for linux (and other unixes):

```<code>#include <stdio.h>
#include <stdlib.h>

/* these are in no header file, and on some
systems they have a _ prepended
These symbols have to be typed to keep the compiler happy
Also check out brk() and sbrk() for information
about heap */

extern char  etext, edata, end;

int
main(int argc, char **argv)
{
    printf("First address beyond:\n");
    printf("    program text segment(etext)      %10p\n", &etext);
    printf("    initialized data segment(edata)  %10p\n", &edata);
    printf("    uninitialized data segment (end) %10p\n", &end);

    return EXIT_SUCCESS;
}
</code>```

Where those symbols come from: Where are the symbols etext ,edata and end defined?

Body:
The bounds for text (program code) and data for linux (and other unixes):

#include <stdio.h>
#include <stdlib.h>

/* these are in no header file, and on some
systems they have a _ prepended
These symbols have to be typed to keep the compiler happy
Also check out brk() and sbrk() for information
about heap */

extern char  etext, edata, end;

int
main(int argc, char **argv)
{
    printf("First address beyond:\n");
    printf("    program text segment(etext)      %10p\n", &etext);
    printf("    initialized data segment(edata)  %10p\n", &edata);
    printf("    uninitialized data segment (end) %10p\n", &end);

    return EXIT_SUCCESS;
}

Where those symbols come from: Where are the symbols etext ,edata and end defined?


问:
Soccer-Head to Head
I want to get sum(goals) both team from head to head Teaams
if i send query [team-Id] 1 & 2  will return 3-1
if i send query [team-Id] 2 & 3  should not return anything</p>

```<code> Tour-Id, Match Id, Team-Id, Goals
    1       1          1       1
    1       1          2       1
    1       1          1       1
    1       1          1       1

    1       2          1       1
    1       2          3       1
</code>```

答:
Simple group by and sum will help to get your results

```<code>select tourid, matchid, teamid, sum(goals) from #yourtour
group by tourid, matchid, teamid
</code>```

Good point raised by Jacobr365, What you have tried?

Title: Soccer-Head to Head

Body:
I want to get sum(goals) both team from head to head Teaams
if i send query [team-Id] 1 & 2  will return 3-1
if i send query [team-Id] 2 & 3  should not return anything

 Tour-Id, Match Id, Team-Id, Goals
    1       1          1       1
    1       1          2       1
    1       1          1       1
    1       1          1       1

    1       2          1       1
    1       2          3       1

Body:
Simple group by and sum will help to get your results

select tourid, matchid, teamid, sum(goals) from #yourtour
group by tourid, matchid, teamid

Good point raised by Jacobr365, What you have tried?


问:
Launch of activity shows white blank windows
When I open my app for debugging on my device it shows white blank page for around 1-2 sec then my splash screen is shown. I read about this problem on android developer website that says it may be causes due to heavy app initalization in application subclass.

My application extended class code is here :

```<code>public class MyApplication extends Application{

private static ApplicationComponent mApplicationComponent;

@Override
public void onCreate() {
    super.onCreate();

    FacebookSdk.sdkInitialize(getApplicationContext());

    if (mApplicationComponent == null){
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this)).build();
    }
}

public static ApplicationComponent providesApplicationComponent(){return Preconditions.checkNotNull(mApplicationComponent);}

}
</code>```

My splash Screen Code : -

```<code>public class SplashActivity extends AppCompatActivity {

@BindView(R.id.splash_screen)
ImageView mSplashScreen;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    ButterKnife.bind(this);
    Picasso.with(this).load(R.drawable.bg_splash_screen).fit().centerCrop().into(mSplashScreen);
    SharedPreferences mSharedPreferences = getSharedPreferences(Constants.PREFERENCE,MODE_PRIVATE);
    if (mSharedPreferences.getBoolean(Constants.LOGGEDIN,false)){
        Intent homeIntent = new Intent(this, HomeActivity.class);
        openPage(homeIntent);
    } else {
        Intent signupIntent = new Intent(this, SignUpActivity.class);
        openPage(signupIntent);
    }
}

private void openPage(final Intent intent){

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(intent);
            finish();
        }
    },1200);
}

}
</code>```

I'm doing only this two initialization in my application class. Is this is the problem ? If or If not How to solve this problems.

答:
please build release mode or Disable Instant Run

I'd like to recommend to disable Instant Run

To disable Instant Run:
Opens the Settings or Preferences dialog box.
Go to Build, Execution, Deployment > Instant Run .
Clear the check box next to Enable Instant Run .

Body:
When I open my app for debugging on my device it shows white blank page for around 1-2 sec then my splash screen is shown. I read about this problem on android developer website that says it may be causes due to heavy app initalization in application subclass.

My application extended class code is here :

public class MyApplication extends Application{

private static ApplicationComponent mApplicationComponent;

@Override
public void onCreate() {
    super.onCreate();

    FacebookSdk.sdkInitialize(getApplicationContext());

    if (mApplicationComponent == null){
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this)).build();
    }
}

public static ApplicationComponent providesApplicationComponent(){return Preconditions.checkNotNull(mApplicationComponent);}

}

My splash Screen Code : -

public class SplashActivity extends AppCompatActivity {

@BindView(R.id.splash_screen)
ImageView mSplashScreen;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    ButterKnife.bind(this);
    Picasso.with(this).load(R.drawable.bg_splash_screen).fit().centerCrop().into(mSplashScreen);
    SharedPreferences mSharedPreferences = getSharedPreferences(Constants.PREFERENCE,MODE_PRIVATE);
    if (mSharedPreferences.getBoolean(Constants.LOGGEDIN,false)){
        Intent homeIntent = new Intent(this, HomeActivity.class);
        openPage(homeIntent);
    } else {
        Intent signupIntent = new Intent(this, SignUpActivity.class);
        openPage(signupIntent);
    }
}

private void openPage(final Intent intent){

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(intent);
            finish();
        }
    },1200);
}

}

I'm doing only this two initialization in my application class. Is this is the problem ? If or If not How to solve this problems.


问:
How long it take to train English/Russian/... model from scratch with SyntaxNet/DragNN?
I want to retrain existing models for SyntaxNet/DragNN and looking for some real numbers how long does it take to train models for any language (it will give me good baseline for my languages).
What hardware have you used during this process?

Thank you in advance!

答:
it took about 24 hours on my mac pro with cpu.
(10000 iterations)
https://github.com/dsindex/syntaxnet</p>


问:
Using Environment.UserName on a StreamReader
I need help in changing the \bob\ part to something like \%username%\ when locating the file to read.

I've been reading and everything is saying Environment.UserName but how do I add this to my current code?

```<code>Imports System.IO
Imports System

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim sr As New StreamReader("C:\Users\bob\Dropbox\Apps\Attachments\my.txt")
        Dim word As String = ""
        Dim words(1000) As String
        Dim i As Integer = 0

        Do Until sr.Peek = -1
            word = sr.ReadLine()
            words(i) = word

            mytext.AppendText(vbNewLine + vbNewLine + TimeOfDay + vbNewLine + vbNewLine + words(i) + vbNewLine + "__________________________________________")
            i += 1

        Loop

        sr.Close()

    End Sub

End Class
</code>```

答:
Like this?</p>

```<code>Dim sr As New StreamReader
    ("C:\Users\" + Environment.UserName + "\Dropbox\Apps\Attachments\my.txt")
</code>```

Body:
I need help in changing the \bob\ part to something like \%username%\ when locating the file to read.

I've been reading and everything is saying Environment.UserName but how do I add this to my current code?

Imports System.IO
Imports System

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim sr As New StreamReader("C:\Users\bob\Dropbox\Apps\Attachments\my.txt")
        Dim word As String = ""
        Dim words(1000) As String
        Dim i As Integer = 0

        Do Until sr.Peek = -1
            word = sr.ReadLine()
            words(i) = word

            mytext.AppendText(vbNewLine + vbNewLine + TimeOfDay + vbNewLine + vbNewLine + words(i) + vbNewLine + "__________________________________________")
            i += 1

        Loop

        sr.Close()

    End Sub

End Class

Body:
Like this?

Dim sr As New StreamReader
    ("C:\Users\" + Environment.UserName + "\Dropbox\Apps\Attachments\my.txt")


问:
Search for any number of unknown substrings in place of * in a list of string
First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.

Here is an example:

```<code>strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']
</code>```

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok.
But I don't know how to do the same thing if there are multiple * in the search string.

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?

For example:

```<code>strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']
</code>```

Hope everything is clear enough. Thanks.

答:
I would use the regular expression package for this if I were you. You'll have to learn a little bit of regex to make correct search queries, but it's not too bad. '.+' is pretty similar to '*' in this case.

```<code>import re

def search_strings(str_list, search_query):
    regex = re.compile(search_query)
    result = []
    for string in str_list:
        match = regex.match(string)
        if match is not None:
            result+=[match.group()]
    return result

strList= ['obj_1_mesh',
          'obj_2_mesh',
          'obj_TMP',
          'mesh_1_TMP',
          'mesh_2_TMP',
          'meshTMP']

print search_strings(strList, '.+_1_.+')
</code>```

This should return ['obj_1_mesh', 'mesh_1_TMP']. I tried to replicate the '*_1_*' case. For 'mesh_*' you could make the search_query 'mesh_.+'. Here is the link to the python regex api: https://docs.python.org/2/library/re.html

Body:
First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.

Here is an example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok.
But I don't know how to do the same thing if there are multiple * in the search string.

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?

For example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']

Hope everything is clear enough. Thanks.

Body:
I would use the regular expression package for this if I were you. You'll have to learn a little bit of regex to make correct search queries, but it's not too bad. '.+' is pretty similar to '*' in this case.

import re

def search_strings(str_list, search_query):
    regex = re.compile(search_query)
    result = []
    for string in str_list:
        match = regex.match(string)
        if match is not None:
            result+=[match.group()]
    return result

strList= ['obj_1_mesh',
          'obj_2_mesh',
          'obj_TMP',
          'mesh_1_TMP',
          'mesh_2_TMP',
          'meshTMP']

print search_strings(strList, '.+_1_.+')

This should return ['obj_1_mesh', 'mesh_1_TMP']. I tried to replicate the '*_1_*' case. For 'mesh_*' you could make the search_query 'mesh_.+'. Here is the link to the python regex api: https://docs.python.org/2/library/re.html


问:
How to setup structure with SpringBoot and Angular2?
I'm trying to use Angular2 with Springboot, but I can't set them together.

I first started a springboot project, and then tried to follow the Angular 2 Tour of Heroes by johnpapa and run npm install.

The structure looks like below:

I have the /app folder, and the .js are compiled to resources/static/app/js.

Problems:

1) The folder resources/static/node_modules/ has lots of files. So when running bootRun, it gets really slow and sometimes can't even refresh the files. I believe I shouldn't put the node_modules there, but not sure..

2) npm install puts the files in ./node_modules so currently I copied them to static folder. Should I just build the node_modules to static?

3) My structure looks hacky.. what is the best way to do it ?

How to set this structure? Also, please let me know if I should start using grunt/gulp or some other tool to make this easier.

Ps.: In case anyone is interested in the johnpapa's guide: johnpapa's angular2 guide

答: Try really cool project builder Jhipster ;)


问:
Test DriverManager.getConnection with mockito
I wrote DAO class

```<code>public List<ClassRoom> getAllClassRooms() {
    List<ClassRoom> classRoomsList = new ArrayList<>();
    String sqlStatement = "SELECT * FROM university.classrooms;";
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/Exam6", "postgres", "Navlanart1");
        try {
            statement = connection.prepareStatement(sqlStatement);
            try {
                resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    ClassRoom classRoom = new ClassRoom(resultSet.getString("name"));
                    classRoomsList.add(classRoom);
                }
            } catch (SQLException e) {
            } finally {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return classRoomsList;
}
</code>```

Now i want to test it by class like that

```<code>import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.easymock.PowerMock.mockStatic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;

import com.kolosok.university.dao.ClassRoomDao;

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(DriverManager.class)
public class TestClassRoomDao {

@Mock
Connection mockConnection;

@Mock
PreparedStatement mockPreparedStatement;

@Mock
ResultSet mockResultSet;

@Test
public void testGetAllClassRooms() throws SQLException {

    mockStatic(DriverManager.class);

    when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(mockConnection);
    when(mockConnection.prepareStatement(anyString())).thenReturn(mockPreparedStatement);
    when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet);
    when(mockResultSet.next()).thenReturn(Boolean.FALSE);

    ClassRoomDao classRoomDao = new ClassRoomDao();
    classRoomDao.getAllClassRooms();

    verify(mockConnection, times(1)).prepareStatement(anyString());
    verify(mockPreparedStatement, times(1)).executeQuery();
    verify(mockResultSet, times(1)).next();
}
</code>```

}

But it doesnt work.

```<code>java.sql.SQLException: No suitable driver found for
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at     com.kolosok.university.TestClassRoomDao.testGetAllClassRooms(TestClassRoomDao.java:58)
</code>```

I read alot of stackOverFlow answers on similar quastions. But still cant solve my issue

I'm using

postgresql-42.0.0.jre7.jar

mockito-all-1.10.19.jar

powermock-api-easymock-1.6.6.jar

powermock-core-1.6.6.jar

cglib-nodep-3.1.jar

javassist-3.12.1.GA.jar

objenesis-2.5.jar

powermock-api-mockito-1.6.6.jar

powermock-api-support-1.6.6.jar

easymock-3.4.jar

答:
I think the problem may be that you are not running this with the PowerMockRunner, so the PowerMock extensions to are using ( like mockStatic ) aren't obeyed

Try changing @RunWith(MockitoJUnitRunner.class) to @RunWith(PowerMockRunner.class)

EDIT

You may also need to initialize the mocks. Easiest way is to use an @Before method, something like

@Before
public void setup(){
   initMocks(this);
}

Body:
I wrote DAO class

public List<ClassRoom> getAllClassRooms() {
    List<ClassRoom> classRoomsList = new ArrayList<>();
    String sqlStatement = "SELECT * FROM university.classrooms;";
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/Exam6", "postgres", "Navlanart1");
        try {
            statement = connection.prepareStatement(sqlStatement);
            try {
                resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    ClassRoom classRoom = new ClassRoom(resultSet.getString("name"));
                    classRoomsList.add(classRoom);
                }
            } catch (SQLException e) {
            } finally {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return classRoomsList;
}

Now i want to test it by class like that

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.easymock.PowerMock.mockStatic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;

import com.kolosok.university.dao.ClassRoomDao;

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(DriverManager.class)
public class TestClassRoomDao {

@Mock
Connection mockConnection;

@Mock
PreparedStatement mockPreparedStatement;

@Mock
ResultSet mockResultSet;

@Test
public void testGetAllClassRooms() throws SQLException {

    mockStatic(DriverManager.class);

    when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(mockConnection);
    when(mockConnection.prepareStatement(anyString())).thenReturn(mockPreparedStatement);
    when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet);
    when(mockResultSet.next()).thenReturn(Boolean.FALSE);

    ClassRoomDao classRoomDao = new ClassRoomDao();
    classRoomDao.getAllClassRooms();

    verify(mockConnection, times(1)).prepareStatement(anyString());
    verify(mockPreparedStatement, times(1)).executeQuery();
    verify(mockResultSet, times(1)).next();
}

}

But it doesnt work.

java.sql.SQLException: No suitable driver found for
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at     com.kolosok.university.TestClassRoomDao.testGetAllClassRooms(TestClassRoomDao.java:58)

I read alot of stackOverFlow answers on similar quastions. But still cant solve my issue

I'm using

postgresql-42.0.0.jre7.jar

mockito-all-1.10.19.jar

powermock-api-easymock-1.6.6.jar

powermock-core-1.6.6.jar

cglib-nodep-3.1.jar

javassist-3.12.1.GA.jar

objenesis-2.5.jar

powermock-api-mockito-1.6.6.jar

powermock-api-support-1.6.6.jar

easymock-3.4.jar


问:
Serial communication between stm32f103 and computer using USB to ttl pl2303
I would like to know is if is possible to send data from my stm32f103 board to my laptop using usb-ttl pl2303. I have tried but even after downloading the drivers the com port is not recognized by com terminal applications.</p>

答: i think i found the solution, for others who might be in need, u have to backdate or roll back the driver .you do that by downloading old driver packages .</p>


问:
Which version of coreclr?
In the .NET CLI I can use the switch --version to get the version of CLI. Is there a similar way to get the version of the coreclr ?

答:
The existing answers probably have all the information, but that's in part obscured by legacy information, so let me attempt a pragmatic summary as of .NET Core v2.0 beta.

While there is a globally active SDK version, as reported by dotnet --version[1]
,

there's no globally active runtime (CoreCLR) version - runtimes are installed side-by-side, and each project determines which runtime it targets, by way of its *.csproj file.

To list all installed CoreCLR versions:

In bash:

ls -1 "$(dirname "$(which dotnet)")/shared/Microsoft.NETCore.App"

In PowerShell Core (both Windows and Unix):

(Get-ChildItem "$((Get-Command -Type Application dotnet).source)/../shared/Microsoft.NETCore.app").Name

To inspect a given project's target CoreCLR: (run the commands in the project root folder):

In bash:

awk -F '</?RuntimeFrameworkVersion>' 'NF>1 {print $2}' *.csproj

In PowerShell Core (both Windows and Unix):

([xml] (Get-Content -Raw *.csproj)).Project.PropertyGroup.RuntimeFrameworkVersion

For a PowerShell Core script that wraps this functionality and more, see this Gist of mine.

[1] Optionally, on a per-project basis, you can override the globally active SDK version by placing a global.json file in the project folder - see the docs.

Also note that just running dotnet without parameters or running dotnet --version without the SDK installed will show text that reflects the shared host ("driver") version - this obscure and confusing behavior is being discussed on GitHub here.

Title: Which version of coreclr?


问:
callback function doesn't work when using getJSON function in jQuery
I am trying to use the getJSON function in jQuery to import some data and trigger a callback function. The callback function doesn't run. However, if I try the same thing with the get function, it works fine. Strangely, it works with the get function even when I pass "json" as the type. Why is this happening? I tested the following file in Firefox 3 and IE 7:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title>ajax test</title>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
</head>
<body>
<input type="button" id="test1" value="get">
<input type="button" id="test2" value="getJSON">
<input type="button" id="test3" value="get with json type">
<script type="text/javascript">
$("#test1").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        }
    )
});

$("#test2").click(function() {
    $.getJSON("index.html",
        function(response) {
            alert('hi');
            //doesn't work
        }
    )
});

$("#test3").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        },
        "json"
    )
});
</script>
</body></html>
</code>```

This seems to happen no matter what URL I access, as long as it's on the same domain. I tried passing some data and that doesn't make a difference.

Of course I can work around the problem by using the get function like I did in my 3rd test function, but I am still curious as to why this is happening.

I know there is a similar question asked here but it didn't answer my question.

答:
$.getJSON() is JSONP, so change it this way:

```<code>$("#test2").click(function() {
    $.getJSON("index.html?callback=?",
        function(response) {
                alert('hi');
        }
    )
});
</code>```

Server receives param callback filled with something like: jsonp1291077863309.
In a response write back callback function jsonp1291077863309( PUT_JSON_HERE).

Body:
I am trying to use the getJSON function in jQuery to import some data and trigger a callback function. The callback function doesn't run. However, if I try the same thing with the get function, it works fine. Strangely, it works with the get function even when I pass "json" as the type. Why is this happening? I tested the following file in Firefox 3 and IE 7:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title>ajax test</title>

<input type="button" id="test1" value="get">
<input type="button" id="test2" value="getJSON">
<input type="button" id="test3" value="get with json type">

This seems to happen no matter what URL I access, as long as it's on the same domain. I tried passing some data and that doesn't make a difference.

Of course I can work around the problem by using the get function like I did in my 3rd test function, but I am still curious as to why this is happening.

I know there is a similar question asked here but it didn't answer my question.

Body:
$.getJSON() is JSONP, so change it this way:

$("#test2").click(function() {
    $.getJSON("index.html?callback=?",
        function(response) {
                alert('hi');
        }
    )
});

Server receives param callback filled with something like: jsonp1291077863309.
In a response write back callback function jsonp1291077863309( PUT_JSON_HERE).


问:
Rails: Adding scope in a model using column values of same model in where clause
I am new to rails. I am trying to create a scope using where clause. In that where clause i want to use column values of same model. But i don't know the correct way of doing that. Please help me out. Here's the code snippet:

```<code>attr_accessible :booked_qty,
                :cancelled_qty,
                :quantity_shipped
</code>```

This is the scope that i am trying to create:

```<code>scope :shipped_qty_less_than_max_tolerance_qty, where("quantity_shipped < ?",self.booked_qty-self.cancelled_qty)
</code>```

So what's the best way to write this scope? Thanks in advance!

答: The scope is correct, if you need to find out more about scopes in be sure to check Rails Guides v3.2</p>

Body:
I am new to rails. I am trying to create a scope using where clause. In that where clause i want to use column values of same model. But i don't know the correct way of doing that. Please help me out. Here's the code snippet:

attr_accessible :booked_qty,
                :cancelled_qty,
                :quantity_shipped

This is the scope that i am trying to create:

scope :shipped_qty_less_than_max_tolerance_qty, where("quantity_shipped < ?",self.booked_qty-self.cancelled_qty)

So what's the best way to write this scope? Thanks in advance!


问:
how to make geofencing in google maps with c#
i have created basic geo fencing i have added 2 markers and one circle in that map . i was trying to show if marker is out of the circle marker should visible in different color , so that we can understand object is out of geofence. how to change the color of marker or show different marker when marker is out of circle.LatLng1 is out of circle so i need to show Latlng1 in out of circle.

js fiddle link

https://jsfiddle.net/aoe4vf17/43/

code

```<code>    <body>
        <div id="map" style="width:1400px;height:800px"></div>
        <script>
            function toggleBounce() {
                alert("Asset 1");
                if (marker.getAnimation() !== null) {
                    marker.setAnimation(null);
                } else {
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                }
            }
            function initMap() {
                var myLatLng = {  lat:17.446399, lng:78.383349};
                var myLatLng1 = { lat: 17.428888, lng: 78.384444 };

                var citymap = {
                    hyderabad: {
                        center: { lat: 17.446507, lng: 78.383033 },
                        population: 2714856
                    }
                };
                var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 18,
                center: myLatLng,
                });
                var map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 14,
                    center: myLatLng1
                });
  var image = "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: 'Asset 1',
                animation: google.maps.Animation.DROP,

            });
            marker.addListener('click', toggleBounce);

        var marker = new google.maps.Marker({
            position: myLatLng1,
            map: map,
            title: 'Hello World!',
             icon:image
        });

            for (var city in citymap) {
                // Add the circle for this city to the map.
                var cityCircle = new google.maps.Circle({
                    strokeColor: '#ffb3b3',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#ffb3b3',
                    fillOpacity: 0.35,
                    map: map,
                    center: citymap[city].center,
                    radius: Math.sqrt(citymap[city].population) * 1
                });
            }
          }
        </script>
        <script async defer
                src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDci4vYApOxVdKqwlpXSv9h77AcWbNuzmQ&callback=initMap">
        </script>
    </body>
</code>```

答:
Here are the concepts you have to know:

Adding event listeners to a marker.

Using getBounds().contains

Here's the full working code. When you drop the marker outside the circle, it will change it's icon. When you place it back inside the circle, it will go back to it's default icon image.

The important bits I added were the logic and the listener:

```<code>          marker.addListener('dragend', function() {
            if( cityCircle.getBounds().contains( marker.getPosition()) == false ){

               marker.setIcon(iconBase + 'library_maps.png');
            }else{
               marker.setIcon("");
            }
</code>```

Body:
Here are the concepts you have to know:

Adding event listeners to a marker.

Using getBounds().contains

Here's the full working code. When you drop the marker outside the circle, it will change it's icon. When you place it back inside the circle, it will go back to it's default icon image.

The important bits I added were the logic and the listener:

          marker.addListener('dragend', function() {
            if( cityCircle.getBounds().contains( marker.getPosition()) == false ){

               marker.setIcon(iconBase + 'library_maps.png');
            }else{
               marker.setIcon("");
            }


问:
Java array sorting in reverse! Need to reverse the reverse
Right now I have my array sorting (which is better than getting an error) except it is sorting in the reverse than what I want it to sort in.

```<code>   public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("\nSort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       String a, b = null;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i+1;
           for(int j=iPosMin; j<numRecords; j++)
           {
               a = sDeptArr[i];
               b = sDeptArr[iPosMin];
               if(a.compareTo(b) > 0)
               {
                   sTemp= sDeptArr[j];
                   sDeptArr[j] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[j];
                   iCourseNumArr[j] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[j];
                   iEnrollmentArr[j] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else if(sDeptArr[j].equals(sDeptArr[iPosMin]) && !(iCourseNumArr[j] < iCourseNumArr[iPosMin]))
               {
                   sTemp= sDeptArr[i];
                   sDeptArr[i] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[i];
                   iCourseNumArr[i] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[i];
                   iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else continue;
           }

       }
   }
</code>```

Again, no array lists or array.sorts. I need just to reverse how this is sorting but I have no idea how.

答:
First I'd say you need to build a data structure to encapsulate the information in your program.  So let's call it Course.

```<code>public class Course {
   public String department;
   public Integer courseNumber;
   public Integer enrollment;
}
</code>```

Why not use the built in sort capabilities of Java?

```<code>List<Course> someArray = new ArrayList<Course>();
...
Collections.sort( someArray, new Comparator<Course>() {
    public int compare( Course c1, Course c2 ) {
       int r = c1.compareTo( c2 );
       if( r == 0 ) { /* the strings are the same sort by something else */
          /* using Integer instead of int allows us
           * to compare the two numbers as objects since Integer implement Comparable
           */
          r = c1.courseNumber.compareTo( c2.courseNumber );
       }
       return r;
    }
});
</code>```

Hope that gets you an A on your homework.  Oh and ditch the static Jr.  Maybe one day your prof can go over why statics are poor form.

Body:
Right now I have my array sorting (which is better than getting an error) except it is sorting in the reverse than what I want it to sort in.

   public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("\nSort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       String a, b = null;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i+1;
           for(int j=iPosMin; j<numRecords; j++)
           {
               a = sDeptArr[i];
               b = sDeptArr[iPosMin];
               if(a.compareTo(b) > 0)
               {
                   sTemp= sDeptArr[j];
                   sDeptArr[j] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[j];
                   iCourseNumArr[j] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[j];
                   iEnrollmentArr[j] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else if(sDeptArr[j].equals(sDeptArr[iPosMin]) && !(iCourseNumArr[j] < iCourseNumArr[iPosMin]))
               {
                   sTemp= sDeptArr[i];
                   sDeptArr[i] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[i];
                   iCourseNumArr[i] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[i];
                   iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else continue;
           }

       }
   }

Again, no array lists or array.sorts. I need just to reverse how this is sorting but I have no idea how.

Body:
First I'd say you need to build a data structure to encapsulate the information in your program.  So let's call it Course.

public class Course {
   public String department;
   public Integer courseNumber;
   public Integer enrollment;
}

Why not use the built in sort capabilities of Java?

List<Course> someArray = new ArrayList<Course>();
...
Collections.sort( someArray, new Comparator<Course>() {
    public int compare( Course c1, Course c2 ) {
       int r = c1.compareTo( c2 );
       if( r == 0 ) { /* the strings are the same sort by something else */
          /* using Integer instead of int allows us
           * to compare the two numbers as objects since Integer implement Comparable
           */
          r = c1.courseNumber.compareTo( c2.courseNumber );
       }
       return r;
    }
});

Hope that gets you an A on your homework.  Oh and ditch the static Jr.  Maybe one day your prof can go over why statics are poor form.


问:
VueJS HTTP request error 500 Handling
I am having this problem where I make HTTP Request to the API and in case of error ( specially error 500) the JS just breaks or goes into infinite loop and I should close the window and re-open the page. What I need is a message to pop up and in very generic way explain what happened. How should I handle this kind of error any ideas?

Example Request:

```<code>this.$http.get('people', { params }).then(({ data }) => {

            this.setFetching({
                fetching: false
            })
        })
</code>```

答:
then accepts a second callback to handle errors. You can also supply a .catch in addition to a .then to handle more severe failures.

new Vue({
  el: '#app',
  data: {
    fetching: true
  },
  mounted() {
    this.$http.get('people')
      .then(() => {
          this.setFetching({
            fetching: false
          })
        },
        (err) => {
          console.log("Err", err);
        })
      .catch((e) => {
        console.log("Caught", e);
      })
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.2.1/vue-resource.min.js"></script>
<div id="app">
</div></code>```

Title: VueJS HTTP request error 500 Handling

Body:
I am having this problem where I make HTTP Request to the API and in case of error ( specially error 500) the JS just breaks or goes into infinite loop and I should close the window and re-open the page. What I need is a message to pop up and in very generic way explain what happened. How should I handle this kind of error any ideas?

Example Request:

this.$http.get('people', { params }).then(({ data }) => {

            this.setFetching({
                fetching: false
            })
        })

Body:
then accepts a second callback to handle errors. You can also supply a .catch in addition to a .then to handle more severe failures.

new Vue({
  el: '#app',
  data: {
    fetching: true
  },
  mounted() {
    this.$http.get('people')
      .then(() => {
          this.setFetching({
            fetching: false
          })
        },
        (err) => {
          console.log("Err", err);
        })
      .catch((e) => {
        console.log("Caught", e);
      })
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.2.1/vue-resource.min.js"></script>
<div id="app">
</div>


问:
Context Menu in Word Add Ins
I am developing an Add In for Microsoft Word. I am looking to Add Customised Context Menus . Is it feasible to have context Menu in Word documents?</p>

答: Yes you can. You need to use add-in commands, who enable you to not only add right-click context menus, but also buttons up in the ribbon. You need to add some annotations in the add-in manifest. There is quite a lot of detailed documentation  on how to do it here: https://dev.office.com/docs/add-ins/design/add-in-commands</p>

Title: Context Menu in Word Add Ins


问:
NSFetchedResultsController result filtering
Is there an easy way to filter the results provided by the NSFetchedResultsController?

I am using the standard Core Data Template which works very well for simple tables.

What I have is a UITableVIew with a UISegmentedControl with two categories, one that displays all and one that when selected should display only events what were created today.

I have been able to accomplish this in two different tableViews (so i know how to use NSPredicate, that is not my problem; the problem is combining it into a single tableView).

I know you cannot change the fetchRequest once the NSFetchedResultsController has been created.

So I can guess that I will have to create a new NSFetchedResultsController.

Has anyone implemented something like this or have any ideas on how to accomplish this?

答: Yes, you must create a new NSFetchedResultsController – after all, changing the fetch request would basically amount to reinitializing it from scratch anyways (due to the operations that NSFetchedResultsController performs behind-the-scenes on the fetched data).