问:
No provider for function (){}! in angular 4
I am running the following command for prod build

```<code>ng serve --prod --env=qa
</code>```

after running this command i don't get any errors but once i run localhost:4200/ in the browser I get the following error

```<code>Uncaught Error: No provider for function (){}!
at b (core.es5.js:1169)
at core.es5.js:1207
at e._throwOrNull (core.es5.js:2649)
at e._getByKeyDefault (core.es5.js:2688)
at e._getByKey (core.es5.js:2620)
at e.get (core.es5.js:2489)
at dt (core.es5.js:9492)
at core.es5.js:9529
at pt (core.es5.js:9503)
at core.es5.js:9456
</code>```

Any help would be appreciated

答:
I have a similar exception with this code block inside my app.module.ts

```<code>providers: [
  ...
  CacheService,
  {
    provide: HttpCaching,
    useFactory: httpFactory,
    deps: [XHRBackend, RequestOptions, CacheService]
  }
]
...
export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, cacheService: CacheService): Http {
  return new HttpCaching(xhrBackend, requestOptions, cacheService);
}
</code>```

It works great in development mode, but the injection of my CacheService fails when running it in production mode giving the Error: Uncaught (in promise): Error: No provider for function (){}!

Please let me know why we are getting this error.

Body:
I am running the following command for prod build

ng serve --prod --env=qa

after running this command i don't get any errors but once i run localhost:4200/ in the browser I get the following error

Uncaught Error: No provider for function (){}!
at b (core.es5.js:1169)
at core.es5.js:1207
at e._throwOrNull (core.es5.js:2649)
at e._getByKeyDefault (core.es5.js:2688)
at e._getByKey (core.es5.js:2620)
at e.get (core.es5.js:2489)
at dt (core.es5.js:9492)
at core.es5.js:9529
at pt (core.es5.js:9503)
at core.es5.js:9456

Any help would be appreciated

Body:
I have a similar exception with this code block inside my app.module.ts

providers: [
  ...
  CacheService,
  {
    provide: HttpCaching,
    useFactory: httpFactory,
    deps: [XHRBackend, RequestOptions, CacheService]
  }
]
...
export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, cacheService: CacheService): Http {
  return new HttpCaching(xhrBackend, requestOptions, cacheService);
}

It works great in development mode, but the injection of my CacheService fails when running it in production mode giving the Error: Uncaught (in promise): Error: No provider for function (){}!

Please let me know why we are getting this error.


来源: stackexchange

问:
Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged
Under what circumstances should I use afterTextChanged instead of onTextChanged and vice versa?

答:
public void afterTextChanged(Editable s)

This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively. (You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span ended up.

public void beforeTextChanged(CharSequence s, int start, int count, int after)

This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after. It is an error to attempt to make changes to s from this callback.

public void onTextChanged(CharSequence s, int start, int before, int count)

This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before. It is an error to attempt to make changes to s from this callback.

Right from Android's Reference for TextWatcher.

OwnerDisplayName: Will

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 3.0


问:
CSS media query to display certain stuff in portrait and landscape mode
I have a div on a page that I dont want to display for a iphone 5 (portrait width of 374px or less). But if I rotate to landscape, the div is displayed.
How can I write a media query that says, if the screen has a max-width of 374px in portrait mode, then apply the css when in lanscape mode too?</p>

答:
The iphone 5 has a landscape width of 568px so you can use this info with orientation and max-device-width like so:

```<code>@media screen and (max-width: 374px),
       screen
       and (max-device-width: 568px)
       and (orientation: landscape) {

    /* styles here for iphone 5 landscape + any screen below 374px */
    .hide-content-iphone5 {
      display: none;
    }
}
</code>```

The comma in the media query signifies "or" -- so it captures screens that are either less than 374px or have a max device width of 568px and are on landscape orientation.

Body:
The iphone 5 has a landscape width of 568px so you can use this info with orientation and max-device-width like so:

@media screen and (max-width: 374px),
       screen
       and (max-device-width: 568px)
       and (orientation: landscape) {

    /* styles here for iphone 5 landscape + any screen below 374px */
    .hide-content-iphone5 {
      display: none;
    }
}

The comma in the media query signifies "or" -- so it captures screens that are either less than 374px or have a max device width of 568px and are on landscape orientation.


问:
Created multiple bundles with one command using npm and Browserify
I am trying to make two bundle.js files, one for iOS and one for Android using a single build command.  I'd like to include a second app in the bundle but import as an alias and have Browserify determine the source.  I don't want to modify App.js but thought I could alias the appOne import and it would either import the blank string or an app.

This is what I have so far which bundles everything:

Package.json

...

```<code> "scripts": {
    "build-dev": "NODE_ENV=production browserify appone-ios.js app.js > public/js/bundle-ios.js && cp public/js/bundle-ios.js public/js/bundle-ios.min.js | NODE_ENV=production browserify appone-andoird.js app.js > public/js/bundle-android.js && cp public/js/bundle-android.js public/js/bundle-android.min.js",
  },
</code>```

...

Appone-ios.js

```<code>// default placeholder for import.
var appOne = '';
export default appOne;
</code>```

Appone-android.js

```<code>// app for import.
var appOne = require('path/to/app/one');
export default appOne;
</code>```

App.js

```<code>// Always import AppOne either a blank string or app so that app.js doesnt change.
var appOne = import('appOne');
</code>```

答:
I ended up having to use Gulp.  This is complete aside from the 'watch' isn't working.</p>

```<code>var gulp = require('gulp');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var transform = require('vinyl-source-stream');
var browserify = require('browserify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');

var ios = browserify({
   entries:['app.js']
 });

var android = browserify({
  entries:['app.js']
});

const bundle = () => {

  process.env.NODE_ENV = 'production';

  const bundleIOS = () => {
    ios.require('./app-ios.js', {expose:'app_alias'})
      .bundle()
      .pipe(transform('bundle-ios.js'))
      .pipe(gulp.dest('./public/js'))
      .pipe(streamify(uglify()))
      .pipe(rename('bundle-ios.min.js'))
      .pipe(gulp.dest('./public/js'));
      return ios;
  }

  const bundleAndroid = () => {
    android.require('./app-android.js', {expose:'app_alias'})
      .bundle()
      .pipe(transform('bundle-android.js'))
      .pipe(gulp.dest('./public/js'))
      .pipe(streamify(uglify()))
      .pipe(rename('bundle-android.min.js'))
      .pipe(gulp.dest('./public/js'));
      return android;
  }

  return bundleIOS() && bundleAndroid();

}

const start = () => {
  return nodemon({
    script: 'server.js',
    watch: ['server.js', 'public/js/*', 'public/index.html', 'public/css/*'],
    ext: 'js html css',
    env: { 'NODE_ENV': 'development' },
  });
}

// Start local server and watch bundles.
gulp.task('start', start);

// Build minified versions for prod.
gulp.task('deploy', bundle);
</code>```

Body:
I am trying to make two bundle.js files, one for iOS and one for Android using a single build command.  I'd like to include a second app in the bundle but import as an alias and have Browserify determine the source.  I don't want to modify App.js but thought I could alias the appOne import and it would either import the blank string or an app.

This is what I have so far which bundles everything:

Package.json

...

 "scripts": {
    "build-dev": "NODE_ENV=production browserify appone-ios.js app.js > public/js/bundle-ios.js && cp public/js/bundle-ios.js public/js/bundle-ios.min.js | NODE_ENV=production browserify appone-andoird.js app.js > public/js/bundle-android.js && cp public/js/bundle-android.js public/js/bundle-android.min.js",
  },

...

Appone-ios.js

// default placeholder for import.
var appOne = '';
export default appOne;

Appone-android.js

// app for import.
var appOne = require('path/to/app/one');
export default appOne;

App.js

// Always import AppOne either a blank string or app so that app.js doesnt change.
var appOne = import('appOne');

Body:
I ended up having to use Gulp.  This is complete aside from the 'watch' isn't working.

var gulp = require('gulp');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var transform = require('vinyl-source-stream');
var browserify = require('browserify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');

var ios = browserify({
   entries:['app.js']
 });

var android = browserify({
  entries:['app.js']
});

const bundle = () => {

  process.env.NODE_ENV = 'production';

  const bundleIOS = () => {
    ios.require('./app-ios.js', {expose:'app_alias'})
      .bundle()
      .pipe(transform('bundle-ios.js'))
      .pipe(gulp.dest('./public/js'))
      .pipe(streamify(uglify()))
      .pipe(rename('bundle-ios.min.js'))
      .pipe(gulp.dest('./public/js'));
      return ios;
  }

  const bundleAndroid = () => {
    android.require('./app-android.js', {expose:'app_alias'})
      .bundle()
      .pipe(transform('bundle-android.js'))
      .pipe(gulp.dest('./public/js'))
      .pipe(streamify(uglify()))
      .pipe(rename('bundle-android.min.js'))
      .pipe(gulp.dest('./public/js'));
      return android;
  }

  return bundleIOS() && bundleAndroid();

}

const start = () => {
  return nodemon({
    script: 'server.js',
    watch: ['server.js', 'public/js/*', 'public/index.html', 'public/css/*'],
    ext: 'js html css',
    env: { 'NODE_ENV': 'development' },
  });
}

// Start local server and watch bundles.
gulp.task('start', start);

// Build minified versions for prod.
gulp.task('deploy', bundle);


问:
myrecv function gSoap
I am trying to write a gSoap server, which needs to save the incoming message.  I want to save it in a buffer.  Here is how gSoap Documentation does it on a client side to save the outgoing message...

```<code>//from gSoap Documentation
//SOURCE: https://www.genivia.com/doc/soapdoc2.html#tth_sEc19.7
int mysend(struct soap *soap, const char *s, size_t n)
{
   struct buffer *h = (struct buffer*)soap->user; // get buffer through handle
   int m = h->max, k = h->len + n;
   // need to increase space?
   if (m == 0)
      m = 1024;
   else
      while (k >= m)
         m *= 2;
   if (m != h->max)
   {
      char *buf = malloc(m);
      memcpy(buf, h->buf, h->len);
      h->max = m;
      if(h->buf)
         free(h->buf);
      h->buf = buf;
   }
   memcpy(h->buf + h->len, s, n);
   h->len += n;
   return SOAP_OK;
}
</code>```

this works with some modification, but if I take this same idea to the server side, store to a buffer and end it with this return statement...

```<code>size_t myrecv(struct soap *soap, char *s, size_t n){
//do similar to above example...
...
return default_frecv(soap,s,n);
}
</code>```

it only stores the message going from the server back to the client.  I need to save the message coming to the server from the client.  I thought recv would give me the incoming message, but this is not the case. Any Ideas?   Any help, suggestions, or ideas are appreciated! Thanks in Advance!

source to the mysend example: https://www.genivia.com/doc/soapdoc2.html#tth_sEc19.7

答:
I need to save the message coming to the server from the client. I
  thought recv would give me the incoming message, but this is not the
  case.

Hmmm. The documentation clearly says that frecv() is the callback that receives all messages, regardless whether it is the client side implementation or the server side implementation. So defining your own frecv() callback should so it. If you get stuck, take a look at the gsoap/plugin/logging.c message logger that implements this callback to capture the message received and sends it to a file/pipe.

Title: myrecv function gSoap

Body:
I am trying to write a gSoap server, which needs to save the incoming message.  I want to save it in a buffer.  Here is how gSoap Documentation does it on a client side to save the outgoing message...

//from gSoap Documentation
//SOURCE: https://www.genivia.com/doc/soapdoc2.html#tth_sEc19.7
int mysend(struct soap *soap, const char *s, size_t n)
{
   struct buffer *h = (struct buffer*)soap->user; // get buffer through handle
   int m = h->max, k = h->len + n;
   // need to increase space?
   if (m == 0)
      m = 1024;
   else
      while (k >= m)
         m *= 2;
   if (m != h->max)
   {
      char *buf = malloc(m);
      memcpy(buf, h->buf, h->len);
      h->max = m;
      if(h->buf)
         free(h->buf);
      h->buf = buf;
   }
   memcpy(h->buf + h->len, s, n);
   h->len += n;
   return SOAP_OK;
}

this works with some modification, but if I take this same idea to the server side, store to a buffer and end it with this return statement...

size_t myrecv(struct soap *soap, char *s, size_t n){
//do similar to above example...
...
return default_frecv(soap,s,n);
}

it only stores the message going from the server back to the client.  I need to save the message coming to the server from the client.  I thought recv would give me the incoming message, but this is not the case. Any Ideas?   Any help, suggestions, or ideas are appreciated! Thanks in Advance!

source to the mysend example: https://www.genivia.com/doc/soapdoc2.html#tth_sEc19.7


问:
How can I add my seed data to my test database using rake db:seed?
I'm using Factory Girl to populate my seed data and adding it to the db in seed.rb.

I'm then running my tests using Cucumber.

I have a price table that contains seed data that I want in all my environments.

I want rake db:seed to add it to my dev and test db's and for cucumber to be able to use that test seed. Then I'll add that seed data in prod also.

How can I ensure that my seed data is added to both dev and test db's?

```<code>rake db:seed #only adds it only to my dev database
</code>```

答:
Check out this answer from a similiar post.

I really think it's better to use factories to fill test database.
And if you need seed data during your tests add it as a before :all block in spec_helper/test_helper.

ContentLicense: CC BY-SA 2.5

Body:
I'm using Factory Girl to populate my seed data and adding it to the db in seed.rb.

I'm then running my tests using Cucumber.

I have a price table that contains seed data that I want in all my environments.

I want rake db:seed to add it to my dev and test db's and for cucumber to be able to use that test seed. Then I'll add that seed data in prod also.

How can I ensure that my seed data is added to both dev and test db's?

rake db:seed #only adds it only to my dev database


问:
Iterate through a table for selenium testing
I want to go through a table and iterate all the rows of the table and want to check validation for a particular columns data, like which date is past date need to identify.

```<code>WebElement tableElement = webDriver.findElement(By.xpath("//[@id='tableID']/tbody/tr"));
    String rowElement = null;

    for(int i = 0; i < 9 ; i ++){
        rowElement = tableElement.findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
        System.out.println(rowElement.toString());
    }
</code>```

Error i got ->

```<code>org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='tableID']/tbody/tr"}
</code>```

Though I double check the table id and it is correct. I am new to selenium testing. Please help to get the data.

答:
Try to find the table by using ID not xpath.</p>

```<code>WebElement tableElement = webDriver.findElement(By.id("tableId"));
</code>```

Body:
I want to go through a table and iterate all the rows of the table and want to check validation for a particular columns data, like which date is past date need to identify.

WebElement tableElement = webDriver.findElement(By.xpath("//[@id='tableID']/tbody/tr"));
    String rowElement = null;

    for(int i = 0; i < 9 ; i ++){
        rowElement = tableElement.findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
        System.out.println(rowElement.toString());
    }

Error i got ->

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='tableID']/tbody/tr"}

Though I double check the table id and it is correct. I am new to selenium testing. Please help to get the data.

Body:
Try to find the table by using ID not xpath.

WebElement tableElement = webDriver.findElement(By.id("tableId"));


问:
How to elegantly check if a number is within a range?
How can I do this elegantly with C#?

For example, a number can be between 1 and 100.

I know a simple if (x >= 1 && x <= 100) would suffice; but with a lot of syntax sugar and new features constantly added to C#/.Net this question is about more idiomatic (one can all it elegance) ways to write that.

Performance is not a concern, but please add performance note to solutions that are not O(1) as people may copy-paste the suggestions.

答:
Elegant because it doesn't require you to determine which of the two boundary values is greater first. It also contains no branches.</p>

```<code>public static bool InRange(float val, float a, float b)
{
    // Determine if val lies between a and b without first asking which is larger (a or b)
    return ( a <= val & val < b ) | ( b <= val & val < a );
}
</code>```

Body:
Elegant because it doesn't require you to determine which of the two boundary values is greater first. It also contains no branches.

public static bool InRange(float val, float a, float b)
{
    // Determine if val lies between a and b without first asking which is larger (a or b)
    return ( a <= val & val < b ) | ( b <= val & val < a );
}


问:
Unexpeced token error when setting contentType to application/json
I am sending data using AJAX POST. The data is JSON format. See below. However, I keep getting 'Unexpected token u in JSON at position 0'. Why is this happening? The reason I am setting contentType here is so that the Boolean field checked does not get converted to string.

```<code>var data = {
  "user": "tom",
  "number": 9,
  "checked": false
}

$.ajax({
    url: url,
    method: "POST",
    data: data,
    contentType: 'application/json',
    dataType: 'json',
    beforeSend: function (xhr) {
        xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
    },
    success: function (success) {
        console.log("success");
    }
});
</code>```

答:
When you use contentType: 'application/json', you need to stringify the data yourself:

```<code>data: JSON.stringify(data),
</code>```

As for the error that seems like a response problem. Inspect the actual request in browser dev tools network and see what is actually contained in the reponse body

Body:
I am sending data using AJAX POST. The data is JSON format. See below. However, I keep getting 'Unexpected token u in JSON at position 0'. Why is this happening? The reason I am setting contentType here is so that the Boolean field checked does not get converted to string.

var data = {
  "user": "tom",
  "number": 9,
  "checked": false
}

$.ajax({
    url: url,
    method: "POST",
    data: data,
    contentType: 'application/json',
    dataType: 'json',
    beforeSend: function (xhr) {
        xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
    },
    success: function (success) {
        console.log("success");
    }
});

Body:
When you use contentType: 'application/json', you need to stringify the data yourself:

data: JSON.stringify(data),

As for the error that seems like a response problem. Inspect the actual request in browser dev tools network and see what is actually contained in the reponse body


问:
r aggregate function -- how to display additional columns
I have two data frames: City and Country.  I am trying to find out the most popular city per country.  City and Country have a common field, City.CountryCode and Country.Code.  These two data frames were merged to one called CityCountry.  I have tried the aggregate command like so:

```<code>aggregate(Population.x~CountryCode, CityCountry, max)
</code>```

This aggregate command only shows the CountryCode and Population.X columns.  How would I show the name of the Country and the name of the City?  Is aggregate the wrong command to use here?

答:
Could also use dplyr to group by Country, then filter by max(Population.x).

```<code>library(dplyr)

set.seed(123)
CityCountry <- data.frame(Population.x = sample(1000:2000, 10, replace = TRUE),
                          CountryCode = rep(LETTERS[1:5], 2),
                          Country = rep(letters[1:5], 2),
                          City = letters[11:20],
                          stringsAsFactors = FALSE)

CityCountry %>%
  group_by(Country) %>%
  filter(Population.x == max(Population.x)) %>%
  ungroup()

# A tibble: 5 x 4
  Population.x CountryCode Country  City
         <int>       <chr>   <chr> <chr>
1         1287           A       a     k
2         1789           B       b     l
3         1883           D       d     n
4         1941           E       e     o
5         1893           C       c     r
</code>```

Body:
I have two data frames: City and Country.  I am trying to find out the most popular city per country.  City and Country have a common field, City.CountryCode and Country.Code.  These two data frames were merged to one called CityCountry.  I have tried the aggregate command like so:

aggregate(Population.x~CountryCode, CityCountry, max)

This aggregate command only shows the CountryCode and Population.X columns.  How would I show the name of the Country and the name of the City?  Is aggregate the wrong command to use here?

Body:
Could also use dplyr to group by Country, then filter by max(Population.x).

library(dplyr)

set.seed(123)
CityCountry <- data.frame(Population.x = sample(1000:2000, 10, replace = TRUE),
                          CountryCode = rep(LETTERS[1:5], 2),
                          Country = rep(letters[1:5], 2),
                          City = letters[11:20],
                          stringsAsFactors = FALSE)

CityCountry %>%
  group_by(Country) %>%
  filter(Population.x == max(Population.x)) %>%
  ungroup()

# A tibble: 5 x 4
  Population.x CountryCode Country  City
         <int>       <chr>   <chr> <chr>
1         1287           A       a     k
2         1789           B       b     l
3         1883           D       d     n
4         1941           E       e     o
5         1893           C       c     r


问:
Handlebars If-Else If-Else With String Equality Function
HandlebarsJS doesn't support string equality ('==') so I have to write my own helper, but this answer isn't clear:

https://stackoverflow.com/a/15095019/1005607

```<code>Handlebars.registerHelper('if_eq', function(a, b, opts) {
    if(a == b) // Or === depending on your needs
        return opts.fn(this);
    else
        return opts.inverse(this);
});
</code>```

and then adjust your template:

```<code>{{#if_eq this "some message"}}
    ...
{{else}}
    ...
{{/if_eq}}
</code>```

1) Why is he doing {{#if_eq ..}} rather than {{#if if_eq .. }} ?

2) I also need to do ELSE-IF, which is supported since Handlebars 3.0.0 (I have 4.0). But using his notation, I wouldn't be able to do {{#elseif_eq}} there is no such expression. How would I implement an ELSE-IF with this custom helper?

答:
The helper in your example is a block helper. The helper is aptly named if_eq because it takes two expressions and, if those expressions are equal, it renders what is in the block. The return opts.inverse(this); line does the job of rendering the else block if the expressions are not equal (see: http://handlebarsjs.com/block_helpers.html#conditionals).

If you want to be able to chain else if conditionals in your template, then you cannot use a custom block helper. Instead you must use a regular (non-block) Handlebars helper. Whereas a block helper will render a block of template, a regular helper will return a value. In your case, we would return a Boolean indicating whether or not all arguments are equal. Such a helper could look like the following:

```<code>Handlebars.registerHelper('eq', function () {
    const args = Array.prototype.slice.call(arguments, 0, -1);
    return args.every(function (expression) {
        return args[0] === expression;
    });
});
</code>```

You would use this helper in your template in the following manner:

```<code>{{#if (eq val1 val2)}}
    <p>IF Branch</p>
{{else if (eq val2 val3)}}
    <p>ELSE IF Branch</p>
{{else}}
    <p>ELSE Branch</p>
{{/if}}
</code>```

Please note the parentheses as in the code (eq val1 val2). These parentheses are required because our eq evaluation is a subexpression within the #if expression. The parentheses tell Handlebars to pass the result of the equality check to the #if block helper.

I have created a JS Fiddle for your reference.

Update

The answer above states that you cannot chain block helpers using else if. This is misleading. In fact, if is itself a block helper; and arbitrarily many if blocks can be chained together by using the else keyword. Even different block helpers can be chained in this way.

The important point to address the poster's first question is that two block helpers cannot be used within the same mustache. That is, {{#if if_eq ... }} is invalid if if_eq is a block helper. However, it would be perfectly valid to use if_eq as in the following:

```<code>{{#if_eq this 'some message'}}
    <p>If branch.</p>
{{else if_eq this 'some other message'}}
    <p>Else if branch.</p>
{{else}}
    <p>Else branch.</p>
{{/if_eq}}
</code>```

Please see this fiddle for an example.

Body:
HandlebarsJS doesn't support string equality ('==') so I have to write my own helper, but this answer isn't clear:

https://stackoverflow.com/a/15095019/1005607

Handlebars.registerHelper('if_eq', function(a, b, opts) {
    if(a == b) // Or === depending on your needs
        return opts.fn(this);
    else
        return opts.inverse(this);
});

and then adjust your template:

{{#if_eq this "some message"}}
    ...
{{else}}
    ...
{{/if_eq}}

1) Why is he doing {{#if_eq ..}} rather than {{#if if_eq .. }} ?

2) I also need to do ELSE-IF, which is supported since Handlebars 3.0.0 (I have 4.0). But using his notation, I wouldn't be able to do {{#elseif_eq}} there is no such expression. How would I implement an ELSE-IF with this custom helper?

Body:
The helper in your example is a block helper. The helper is aptly named if_eq because it takes two expressions and, if those expressions are equal, it renders what is in the block. The return opts.inverse(this); line does the job of rendering the else block if the expressions are not equal (see: http://handlebarsjs.com/block_helpers.html#conditionals).

If you want to be able to chain else if conditionals in your template, then you cannot use a custom block helper. Instead you must use a regular (non-block) Handlebars helper. Whereas a block helper will render a block of template, a regular helper will return a value. In your case, we would return a Boolean indicating whether or not all arguments are equal. Such a helper could look like the following:

Handlebars.registerHelper('eq', function () {
    const args = Array.prototype.slice.call(arguments, 0, -1);
    return args.every(function (expression) {
        return args[0] === expression;
    });
});

You would use this helper in your template in the following manner:

{{#if (eq val1 val2)}}
    <p>IF Branch</p>
{{else if (eq val2 val3)}}
    <p>ELSE IF Branch</p>
{{else}}
    <p>ELSE Branch</p>
{{/if}}

Please note the parentheses as in the code (eq val1 val2). These parentheses are required because our eq evaluation is a subexpression within the #if expression. The parentheses tell Handlebars to pass the result of the equality check to the #if block helper.

I have created a JS Fiddle for your reference.

Update

The answer above states that you cannot chain block helpers using else if. This is misleading. In fact, if is itself a block helper; and arbitrarily many if blocks can be chained together by using the else keyword. Even different block helpers can be chained in this way.

The important point to address the poster's first question is that two block helpers cannot be used within the same mustache. That is, {{#if if_eq ... }} is invalid if if_eq is a block helper. However, it would be perfectly valid to use if_eq as in the following:

{{#if_eq this 'some message'}}
    <p>If branch.</p>
{{else if_eq this 'some other message'}}
    <p>Else if branch.</p>
{{else}}
    <p>Else branch.</p>
{{/if_eq}}

Please see this fiddle for an example.


问:
c# - abort the execution of a method if its taking too long to run
How can I abort the execution of a method if its taking too long to run?

e.g.

```<code>string foo = DoSomethingComplex();
</code>```

but if DoSomethingComplex() is taking too long (20 seconds lets say).
then just set foo to "";

答:
Create a separate thread for DoSomethingComplex and wait for completion of the operation in the main thread:

create an instance of AutoResetEvent and pass it to the thread that will execute DoSomethingComplex;

use AutoResetEvent.Set() method in DoSomethingComplex to tell the main thread about completion

use AutoResetEvent.WaitOne(timeout) in main thread

If WaitOne returned false, use Thread.Abort() method to stop the thread if it works for too long.

Body:
How can I abort the execution of a method if its taking too long to run?

e.g.

string foo = DoSomethingComplex();

but if DoSomethingComplex() is taking too long (20 seconds lets say).
then just set foo to "";


问:
Make sure the same ID is not affected to multiple tables
I want to restrict the number of the ID between multiple tables. Let's say I have 4 tables with products. Each table will have an ID, but I want to restrict the number of ID so I can't duplicate it that number already exists on one of these tables. Let's say I have the ID 43 in one table, I want to "deny" it on another table so I can't use it anymore because it's already created on that one.
Thanks!</p>

答:
Have a 5th table for doling out ids.  There, the id can be AUTO_INCREMENT (if that is suitable).

get new number from 5th table

INSERT into the appropriate of the 4 tables.

The two steps do not need to be in the same 'transaction'.

A sample sequence generator:

```<code>-- Setup:
CREATE TABLE `seq` (
  `id` INT UNSIGNED NOT NULL,
  `code` char(1) CHARACTER SET ascii NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB;
INSERT INTO seq VALUES (0, 'a');   -- The only row for the table

-- Increment and get next value:
UPDATE seq
    SET id = LAST_INSERT_ID(id + 1)
    WHERE code = 'a';
SELECT LAST_INSERT_ID();
</code>```

Note: the UPDATE and SELECT can (should) be done outside any transaction; be in autocommit=ON mode.  The SELECT is specific to the connection, so there is no chance of mixing up numbers with another connection.

Body:
Have a 5th table for doling out ids.  There, the id can be AUTO_INCREMENT (if that is suitable).

get new number from 5th table

INSERT into the appropriate of the 4 tables.

The two steps do not need to be in the same 'transaction'.

A sample sequence generator:

-- Setup:
CREATE TABLE `seq` (
  `id` INT UNSIGNED NOT NULL,
  `code` char(1) CHARACTER SET ascii NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB;
INSERT INTO seq VALUES (0, 'a');   -- The only row for the table

-- Increment and get next value:
UPDATE seq
    SET id = LAST_INSERT_ID(id + 1)
    WHERE code = 'a';
SELECT LAST_INSERT_ID();

Note: the UPDATE and SELECT can (should) be done outside any transaction; be in autocommit=ON mode.  The SELECT is specific to the connection, so there is no chance of mixing up numbers with another connection.


问:
In cake pattern, how to replace some internal implementation from client side without direct relation?
Module code in common-project shared via jar and I wish to change internal dependency in compile time

```<code>trait MyTableNames
trait MyDAO extends MyTableNames
trait ActorService {
  def send(actorMessage: Any) = println("sending message... will reach some Actor and then from actor to DAO")
}
trait MyActor extends MyDAO
object SaveUserActorMessage

trait MyService extends ActorService {
  def addUser() = send(SaveUserActorMessage) // Not aware of dao just sends a message so service is disconnected from DAO.
}
</code>```

A different server code using common-project via it's shared jar
The client code who uses this service only creates the service.
The problem is that I need to "inject" some other implementation of MyTableNames

from a different project which reuses the common-project above:

```<code>trait MyOwnTableNames extends MyTableNames
class MyCustomService extends MyService {
  def someOtherAddUser() = addUser() // How do I tell the DAO which the service does not have a direct reference to, to use MyOwnTableNames, in compile time right now as a client code, I only have reference to MyService.  In addition MyService has no direct relation to MyDAO it's only has a relation to ActorService which has no direct relation to DAO only the end actor which processes the message has a reference to DAO.
}
</code>```

Please note: This example my not look "beautiful" and is not strickly cake pattern, I had to make it so so that I could compact it to a few lines of code, the bottom line is that my client code references a service and does an operation on service, the service then sends a message to actor, and the end actor uses a DAO, my problem is that the DAO at the end is trying to refer to MyTableNames which I want to replace.  I use clean scala code, No DI framework, I prefer to avoid implicits and only use cake pattern if possible.

答:
You could rely on Scala's linearization to order traits correctly and simply do

```<code>class MyCustomService extends MyService with MyOwnTableNames
</code>```

There's a small caveat here. If anything that extends MyTableNames uses some value of MyTableNames in a val, you can get an NPE due to class initialization ordering issues. To fix that you would have to either use lazy val or def.

Body:
Module code in common-project shared via jar and I wish to change internal dependency in compile time

trait MyTableNames
trait MyDAO extends MyTableNames
trait ActorService {
  def send(actorMessage: Any) = println("sending message... will reach some Actor and then from actor to DAO")
}
trait MyActor extends MyDAO
object SaveUserActorMessage

trait MyService extends ActorService {
  def addUser() = send(SaveUserActorMessage) // Not aware of dao just sends a message so service is disconnected from DAO.
}

A different server code using common-project via it's shared jar
The client code who uses this service only creates the service.
The problem is that I need to "inject" some other implementation of MyTableNames

from a different project which reuses the common-project above:

trait MyOwnTableNames extends MyTableNames
class MyCustomService extends MyService {
  def someOtherAddUser() = addUser() // How do I tell the DAO which the service does not have a direct reference to, to use MyOwnTableNames, in compile time right now as a client code, I only have reference to MyService.  In addition MyService has no direct relation to MyDAO it's only has a relation to ActorService which has no direct relation to DAO only the end actor which processes the message has a reference to DAO.
}

Please note: This example my not look "beautiful" and is not strickly cake pattern, I had to make it so so that I could compact it to a few lines of code, the bottom line is that my client code references a service and does an operation on service, the service then sends a message to actor, and the end actor uses a DAO, my problem is that the DAO at the end is trying to refer to MyTableNames which I want to replace.  I use clean scala code, No DI framework, I prefer to avoid implicits and only use cake pattern if possible.

Body:
You could rely on Scala's linearization to order traits correctly and simply do

class MyCustomService extends MyService with MyOwnTableNames

There's a small caveat here. If anything that extends MyTableNames uses some value of MyTableNames in a val, you can get an NPE due to class initialization ordering issues. To fix that you would have to either use lazy val or def.


问:
Azure Cosmos DB: Incorrect syntax near 'Dec' error while executing query through stored procedure
In a stored procedure that runs against the Azure Cosmos DB non-partitioned collection, I am running below select query:

```<code>var twentyMinutesBefore = new Date();
twentyMinutesBefore.setMinutes(twentyMinutesBefore.getMinutes() - 20);
var filterQuery = "SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (" + twentyMinutesBefore + " > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC";
</code>```

I execute the query as below:

```<code>var isAccepted = collection.queryDocuments(collectionLink, filterQuery, options, callback);

function callback(err, queryFeed, responseOptions) {
    if (err) {
        throw err; // <-- Error thrown from this line as per stack trace
    }
    // Iterate through query feed
}
</code>```

I get the below error:

```<code>    "Message": "Microsoft.Azure.Documents.DocumentClientException: Message:
{\"Errors\":[\"Encountered exception while executing function. Exception = Error:
{\\"errors\\":[{\\"severity\\":\\"Error\\",\\"location\\":{\\"start\\":63,\\"end\\":66},\\"code\\":\\"SC1001\\",
\\"message\\":\\"Syntax error, incorrect syntax near 'Dec'.\\"}]}
    Stack trace: Error: {\\"errors\\":[{\\"severity\\":\\"Error\\",\\"location\\":{\\"start\\":63,\\"end\\":66},\\"code\\":\\"SC1001\\",\\"message\\":\\"Syntax error, incorrect syntax near 'Dec'.\\"}]}
</code>```

In a Console application, I tried resolving the filter query to verify if it is properly formatted. It results as below:

```<code>SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (1512593297244 > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC
</code>```

When I copy this query as is and run in Cosmos DB query window, it runs fine and returns results as expected.

Not sure why it doesn't run through the stored procedure. Any idea what that 'Dec' means in the error? I don't find any such string in my stored procedure.

答:
Use twentyMinutesBefore.getTime(), without getTime() to get the UNIX epoch time, you will get the full date like "Thu Dec 07 2017 13:26:39 GMT+1100 (AUS Eastern Daylight Time)":

```<code>var filterQuery = "SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (" + twentyMinutesBefore.getTime() + " > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC";
</code>```

Body:
In a stored procedure that runs against the Azure Cosmos DB non-partitioned collection, I am running below select query:

var twentyMinutesBefore = new Date();
twentyMinutesBefore.setMinutes(twentyMinutesBefore.getMinutes() - 20);
var filterQuery = "SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (" + twentyMinutesBefore + " > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC";

I execute the query as below:

var isAccepted = collection.queryDocuments(collectionLink, filterQuery, options, callback);

function callback(err, queryFeed, responseOptions) {
    if (err) {
        throw err; // <-- Error thrown from this line as per stack trace
    }
    // Iterate through query feed
}

I get the below error:

    "Message": "Microsoft.Azure.Documents.DocumentClientException: Message:
{\"Errors\":[\"Encountered exception while executing function. Exception = Error:
{\\"errors\\":[{\\"severity\\":\\"Error\\",\\"location\\":{\\"start\\":63,\\"end\\":66},\\"code\\":\\"SC1001\\",
\\"message\\":\\"Syntax error, incorrect syntax near 'Dec'.\\"}]}
    Stack trace: Error: {\\"errors\\":[{\\"severity\\":\\"Error\\",\\"location\\":{\\"start\\":63,\\"end\\":66},\\"code\\":\\"SC1001\\",\\"message\\":\\"Syntax error, incorrect syntax near 'Dec'.\\"}]}

In a Console application, I tried resolving the filter query to verify if it is properly formatted. It results as below:

SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (1512593297244 > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC

When I copy this query as is and run in Cosmos DB query window, it runs fine and returns results as expected.

Not sure why it doesn't run through the stored procedure. Any idea what that 'Dec' means in the error? I don't find any such string in my stored procedure.

Body:
Use twentyMinutesBefore.getTime(), without getTime() to get the UNIX epoch time, you will get the full date like "Thu Dec 07 2017 13:26:39 GMT+1100 (AUS Eastern Daylight Time)":

var filterQuery = "SELECT TOP 40 * FROM c WHERE (c.transmissionState = 2 AND (" + twentyMinutesBefore.getTime() + " > c.dateCreated.epoch)) OR c.transmissionState = 0 ORDER BY c.dateCreated.epoch DESC";


问:
MySQL: the inconsistency of auto increment in id numbers
I wonder if you have come across this that the id numbers of auto increment don't arrange in correct order when you click on Browse button on phpMyAdmin - is it just me? Something I have set incorrectly in the db table?

For instance, when you insert a series of data into a table and you have deleted some of them as well, so when you check this table on phpMyAdmin, these data should appear in an order like this,

```<code>id

2
24
28
296
300
</code>```

but in most of my tables they don't appear in orders, instead they appear in something like this,

```<code>id

24
300
2
296
28
</code>```

as in this picture below,

Can we do something about it so that the IDs appear in the correct order?

EDIT 1:

I think most of you have misunderstood the issue I raided here. I mean when you click on Browser button on the phpMyAdmin to list all the data in your tables - not when you use SQL query to list the output by using order by.

Does it make sense?

EDIT 2:

This is one of my table structure - does it help you to see what is wrong in it?

```<code>CREATE TABLE IF NOT EXISTS `root_pages` (
  `pg_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pg_url` varchar(255) DEFAULT NULL,
  `pg_title` varchar(255) DEFAULT NULL,
  `pg_subtitle` varchar(255) DEFAULT NULL,
  `pg_description` text,
  `pg_introduction` text,
  `pg_content_1` text,
  `pg_content_2` text,
  `pg_content_3` text,
  `pg_content_4` text,
  `pg_order` varchar(255) DEFAULT NULL,
  `pg_hide` varchar(255) DEFAULT '0',
  `pg_highlight` varchar(255) DEFAULT '0',
  `pg_important` varchar(255) DEFAULT '0',
  `pg_parent` varchar(255) DEFAULT '0',
  `parent_id` varchar(255) DEFAULT NULL,
  `pg_cat_id` varchar(255) DEFAULT NULL COMMENT 'page category id',
  `ps_cat_id` varchar(255) DEFAULT NULL COMMENT 'post category id',
  `tmp_id` varchar(255) DEFAULT NULL COMMENT 'template id',
  `pg_backdate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`pg_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</code>```

答:
If you want them ordered by the ID then you have to use an order by clause when selecting.

With SQL, the sets returned by select are unordered unless you specify what order you want them in.

You should assume that the actual order will be random unless you specify it. In reality, it's arbitrary rather than random but changes to the table content can easily change the order.

Body:
I wonder if you have come across this that the id numbers of auto increment don't arrange in correct order when you click on Browse button on phpMyAdmin - is it just me? Something I have set incorrectly in the db table?

For instance, when you insert a series of data into a table and you have deleted some of them as well, so when you check this table on phpMyAdmin, these data should appear in an order like this,

id

2
24
28
296
300

but in most of my tables they don't appear in orders, instead they appear in something like this,

id

24
300
2
296
28

as in this picture below,

Can we do something about it so that the IDs appear in the correct order?

EDIT 1:

I think most of you have misunderstood the issue I raided here. I mean when you click on Browser button on the phpMyAdmin to list all the data in your tables - not when you use SQL query to list the output by using order by.

Does it make sense?

EDIT 2:

This is one of my table structure - does it help you to see what is wrong in it?

CREATE TABLE IF NOT EXISTS `root_pages` (
  `pg_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pg_url` varchar(255) DEFAULT NULL,
  `pg_title` varchar(255) DEFAULT NULL,
  `pg_subtitle` varchar(255) DEFAULT NULL,
  `pg_description` text,
  `pg_introduction` text,
  `pg_content_1` text,
  `pg_content_2` text,
  `pg_content_3` text,
  `pg_content_4` text,
  `pg_order` varchar(255) DEFAULT NULL,
  `pg_hide` varchar(255) DEFAULT '0',
  `pg_highlight` varchar(255) DEFAULT '0',
  `pg_important` varchar(255) DEFAULT '0',
  `pg_parent` varchar(255) DEFAULT '0',
  `parent_id` varchar(255) DEFAULT NULL,
  `pg_cat_id` varchar(255) DEFAULT NULL COMMENT 'page category id',
  `ps_cat_id` varchar(255) DEFAULT NULL COMMENT 'post category id',
  `tmp_id` varchar(255) DEFAULT NULL COMMENT 'template id',
  `pg_backdate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`pg_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


问:
Android - All users have to install Google Play Services?
For devleopment I have to do this:

If not installed yet, you have to install the following packages :

```<code>Extras / Google Play services
Extras / Google Repository
Android 6.0 (API 23) / Google APIs Intel x86 Atom System Image Rev. 19
Android SDK Build-tools 23.0.3
</code>```

Is this for development only? Or do all my users of the app have to also download Google Play Services etc?

Yes I know this isn't really a question for stackoverflow, but where else can I ask this question? They are not letting me ask this in the github issues either.

I also can't test this, because react-native-maps isn't working for me, it keeps crashing. I wash hoping to learn if its worth the effort to fix the crash. If users have to install a bunch of stuff to use this, then its not worth.

答:
If you are using services provided by Google Play Services like Maps, or push messages, location services or in-app payments then yes, your users must have it installed too. If you are not using Google Play Services, then it's not required.

But if required, they have to install Google Play Services app from Play Store, not development stuff like you listed:

https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en

EDIT

How come Google doesnt defalt install this?

Google Play Services or apps like Calendar, GMail etc are NOT part of Android. These are Google applications and may or may not come preinstalled, depending on licenses phone/tablet manufacturer purchased from Google. As Android can perfectly live w/o these apps, some devices does not include it or come with alternatives (i.e. using other providers than Google).

I don't know even know where the proper place to tell them would be

Your app should check if Google Play Services exists usually on start before it start using it. See this documentation which discuss this.

Body:
For devleopment I have to do this:

If not installed yet, you have to install the following packages :

Extras / Google Play services
Extras / Google Repository
Android 6.0 (API 23) / Google APIs Intel x86 Atom System Image Rev. 19
Android SDK Build-tools 23.0.3

Is this for development only? Or do all my users of the app have to also download Google Play Services etc?

Yes I know this isn't really a question for stackoverflow, but where else can I ask this question? They are not letting me ask this in the github issues either.

I also can't test this, because react-native-maps isn't working for me, it keeps crashing. I wash hoping to learn if its worth the effort to fix the crash. If users have to install a bunch of stuff to use this, then its not worth.


问:
How do you compare duplicate values?
```<code>private int pic = 0;
private List<int> num = null;
.
.
.

.
.
public void ss(){
this.imageList = new List<Image>();
this.imageList.Add(Properties.Resources.1);
this.imageList.Add(Properties.Resources.2);
this.imageList.Add(Properties.Resources.3);
.
.
.
.
.
this.imageList.Add(Properties.Resources.58);
this.imageList.Add(Properties.Resources.59);
 this.pic = GetMyRandomNumber(0, 60);

 if (this.num == null)
    this.num= new List<int>();

 while (this.num.Count < 61)
 {
       pic = GetMyRandomNumber(0, 60);

       if (this.num.Contains(pic) == false)
       {
             this.num.Add(pic);
             break;
       }
 }
 this.pictureBox1.Image = imageList[pic];
</code>```

}

This code checks for duplicates when calling the ss method

Store the value in num, and check if the stored value is duplicated.

But the same value is stored in pic

duplicate values continue to appear.

How do I fix it?

答:
Hope this help</p>

```<code>    public static void Main(string[] args)
    {
        var nums = new List<int>() { 1, 2, 3, 3, 4, 5 };
        Print(nums);
        //REMOVE DUPLIDATED VALUES AT THE LINE BELOW
        nums = nums.Distinct().ToList();
        Print(nums);
        Console.Read();
    }

    public static void Print(List<int> nums)
    {
        foreach (var num in nums)
        {
            Console.Write(num.ToString() + ", ");
        }
        Console.WriteLine();
    }
</code>```

Title: How do you compare duplicate values?

Body:
private int pic = 0;
private List<int> num = null;
.
.
.

.
.
public void ss(){
this.imageList = new List<Image>();
this.imageList.Add(Properties.Resources.1);
this.imageList.Add(Properties.Resources.2);
this.imageList.Add(Properties.Resources.3);
.
.
.
.
.
this.imageList.Add(Properties.Resources.58);
this.imageList.Add(Properties.Resources.59);
 this.pic = GetMyRandomNumber(0, 60);

 if (this.num == null)
    this.num= new List<int>();

 while (this.num.Count < 61)
 {
       pic = GetMyRandomNumber(0, 60);

       if (this.num.Contains(pic) == false)
       {
             this.num.Add(pic);
             break;
       }
 }
 this.pictureBox1.Image = imageList[pic];

}

This code checks for duplicates when calling the ss method

Store the value in num, and check if the stored value is duplicated.

But the same value is stored in pic

duplicate values continue to appear.

How do I fix it?

Body:
Hope this help

    public static void Main(string[] args)
    {
        var nums = new List<int>() { 1, 2, 3, 3, 4, 5 };
        Print(nums);
        //REMOVE DUPLIDATED VALUES AT THE LINE BELOW
        nums = nums.Distinct().ToList();
        Print(nums);
        Console.Read();
    }

    public static void Print(List<int> nums)
    {
        foreach (var num in nums)
        {
            Console.Write(num.ToString() + ", ");
        }
        Console.WriteLine();
    }


答: research on LiMex or Limited Execution.</p>

Title: c# - abort the execution of a method if its taking too long to run

Body: research on LiMex or Limited Execution.


问:
Install multiple NuGet packages error
I have this problem. I want to download "Install-Package Microsoft.ProjectOxford.Face -Version 1.3.0" but I take this error. I searched but i could not found.

```<code>Install-Package : Could not install package 'Microsoft.ProjectOxford.Common 1.0.324'. You are trying to install this package into a p
roject that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly references or content files that are
compatible with that framework. For more information, contact the package author.
At line:1 char:1
+ Install-Package Microsoft.ProjectOxford.Face -Version 1.3.0
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
</code>```

答:
Install multiple NuGet packages error

The first thing to point out is that magicandre comments pointed the right direction, "upgrade your project to 4.5".

Detailed info:

Search the nuget package Microsoft.ProjectOxford.Face on the nuget.org, we notice that this package have two dependencies: Microsoft.ProjectOxford.Common (>= 1.0.324) and Newtonsoft.Json (>= 9.0.1):

Then manually download the dependency package Microsoft.ProjectOxford.Common (>= 1.0.324) from nuget.org, rename it for the end of .zip, then unzip it. You will notice that package targets .NET Standdard 1.1.

Then according to the compatibility list of .NET Standard:

So to install the package Microsoft.ProjectOxford.Face you should upgrade your project to .NET framwork 4.5.

Title: Install multiple NuGet packages error

Body:
I have this problem. I want to download "Install-Package Microsoft.ProjectOxford.Face -Version 1.3.0" but I take this error. I searched but i could not found.

Install-Package : Could not install package 'Microsoft.ProjectOxford.Common 1.0.324'. You are trying to install this package into a p
roject that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly references or content files that are
compatible with that framework. For more information, contact the package author.
At line:1 char:1
+ Install-Package Microsoft.ProjectOxford.Face -Version 1.3.0
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand


问:
AngularJS ng-repeat grouped 2 dimensional
what I'm trying to do is using the ng-repeat directive to iterate some kind of 2 dimensional in angularjs

I have a long list, that I want to display in an html table with lets say 4 per row.

I'm currently using a somekind workaround to do this by doing so:

```<code><table>
    <tr>
        <td data-ng-repeat="x in my.list.slice(0, 4)">
           {{x}}
        </td>
    </tr>
    <tr>
        <td data-ng-repeat="x in my.list.slice(4, 8)">
           {{x}}
        </td>
    </tr>
    <tr>
        <td data-ng-repeat="x in my.list.slice(8, 12)">
           {{x}}
        </td>
    </tr>
    <tr>
        <!-- -->
    </tr>
</table>
</code>```

I'm wondering if there is somekind of itterating on
 but having everytime 4 *  ?

答:
So for the 'tr', you want it to to be generating one 4th the amount of the array length since there will be 4 'td' in each. Then just using the index you calculate the point in the array you need for the td.

```<code><table>
    <tr data-ng-repeat="x in my.list.slice(0, my.list.length/4) track by $index">
        <td data-ng-repeat="x in my.list.slice($index*4, $index*4+4)">
           {{x}}
        </td>
    </tr>
</table>
</code>```

Edit: The above only works for arrays exactly divisible by 4, If you need something which will accommodate possibly half filled rows, the following should work.

```<code><table>
    <tr data-ng-repeat="x in my.list.slice(0, (my.list.length/4)+1) track by $index" ng-if="myArr%4 !== 0">
        <td data-ng-repeat="x in my.list.slice($index*4, $index*4+4)">
            {{x}}
        </td>
    </tr>
    <tr data-ng-repeat="x in my.list.slice(0, my.list.length/4) track by $index" ng-if="myArr%4 === 0">
        <td data-ng-repeat="x in my.list.slice($index*4, $index*4+4)">
           {{x}}
        </td>
    </tr>
</table>
</code>```

Body:
what I'm trying to do is using the ng-repeat directive to iterate some kind of 2 dimensional in angularjs

I have a long list, that I want to display in an html table with lets say 4 per row.

I'm currently using a somekind workaround to do this by doing so:

           {{x}}

           {{x}}

           {{x}}

I'm wondering if there is somekind of itterating on
 but having everytime 4 *  ?

Body:
So for the 'tr', you want it to to be generating one 4th the amount of the array length since there will be 4 'td' in each. Then just using the index you calculate the point in the array you need for the td.

<table>
    <tr data-ng-repeat="x in my.list.slice(0, my.list.length/4) track by $index">
        <td data-ng-repeat="x in my.list.slice($index*4, $index*4+4)">
           {{x}}
        </td>
    </tr>
</table>

Edit: The above only works for arrays exactly divisible by 4, If you need something which will accommodate possibly half filled rows, the following should work.

<table>
    <tr data-ng-repeat="x in my.list.slice(0, (my.list.length/4)+1) track by $index" ng-if="myArr%4 !== 0">
        <td data-ng-repeat="x in my.list.slice($index*4, $index*4+4)">
            {{x}}
        </td>
    </tr>
    <tr data-ng-repeat="x in my.list.slice(0, my.list.length/4) track by $index" ng-if="myArr%4 === 0">
        <td data-ng-repeat="x in my.list.slice($index*4, $index*4+4)">
           {{x}}
        </td>
    </tr>
</table>


问:
Applying multiple classes to ReactJS component
I need to apply multiple classes to a React component without installing anything extra. Is that possible?

```<code><Component id="test1" className="blue-text kps hide-on-small-and-down" />
</code>```

I also tried

```<code><Component id="test1" className={`blue-text kps hide-on-small-and-down`} />
</code>```

But nothing works.

I have been searching for hours but did not find anything that does not require extra installations.
Please do not downvote without explaining why.
Thank you

答:
When you add a className directly to a component, it is passed to that instance of the component as a prop accessible inside the component as this.props.className, and it's up to you to apply that class to actual DOM elements inside your component.

Remember that a React component is not an actual DOM element, but a higher-order logical construct that will be translated into one or several DOM elements (while also adding behavior, etc.). CSS classes only apply to DOM elements.

Body:
I need to apply multiple classes to a React component without installing anything extra. Is that possible?

<Component id="test1" className="blue-text kps hide-on-small-and-down" />

I also tried

<Component id="test1" className={`blue-text kps hide-on-small-and-down`} />

But nothing works.

I have been searching for hours but did not find anything that does not require extra installations.
Please do not downvote without explaining why.
Thank you


问:
How to make pull down Page refresh on Web app using jQuery Mobile or Javascript
I'm developing a simple web application, I want to give the ability to the user to refresh the page with pull down refresh thing like android or iOs.

the refresh it will only lead to reload the page nothing else :

```<code>location.reload();
</code>```

I'd like to use jQuery Mobile or Javascript.

答:
First, your application is in position to detect the scrolling event.
Do like this.

```<code>$(window).scroll(function()
{
   if($(this).scrcollTop()>='somevalue may be your window height')
          location.reload();
});
</code>```

I think this is gonna work for you.

Body:
I'm developing a simple web application, I want to give the ability to the user to refresh the page with pull down refresh thing like android or iOs.

the refresh it will only lead to reload the page nothing else :

location.reload();

I'd like to use jQuery Mobile or Javascript.

Body:
First, your application is in position to detect the scrolling event.
Do like this.

$(window).scroll(function()
{
   if($(this).scrcollTop()>='somevalue may be your window height')
          location.reload();
});

I think this is gonna work for you.


问:
Django arranging model foreign key attributes after delete()
I have a model like so:

```<code>class RepairOrder(models.Model):
user = models.ForeignKey(User)
ro_number = models.IntegerField(validators=[MaxValueValidator(999999999999)])
service_writer = models.ForeignKey(ServiceWriter, null=True, blank=True)
RO_STATUS_CHOICES = (
    ('P', 'Pending'),
    ('O', 'Open'),
    ('C', 'Closed')
)
ro_status = models.CharField(max_length=10, blank=False, choices=RO_STATUS_CHOICES)
open_date = models.DateTimeField()
closed_date = models.DateTimeField(null=True, blank=True)
mileage = models.IntegerField(blank=False, validators=[MaxValueValidator(999999999999)])
line_number_1 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_1')
line_number_2 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_2')
line_number_3 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_3')
line_number_4 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL
                                  , related_name='line_number_4')
line_number_5 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_5')
line_number_6 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_6')
line_number_7 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_7')
line_number_8 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_8')
line_number_9 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_9')
line_number_10 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                   related_name='line_number_10')
vehicle = models.ForeignKey(Vehicle, blank=False, related_name='vehicle')

def __str__(self):
    return str(self.ro_number)
</code>```

Some of these objects might have

```<code>line_number_(1 through 5)
</code>```

assigned to a JobLine object and the remaining set as Null.
Other RepairOrder objects may only have

```<code>line_number_(1 through 3)
</code>```

assigned to a JobLine object while the remaining are set as Null. But during the creation of a RepairOrder object the

```<code>line_number_(x)
</code>```

attributes are always assigned in ascending order starting from 1.

Here is what I am trying to accomplish:
Lets assume I have a RepairOrder that has

```<code>line_number_(1 through 5)
</code>```

assigned to JobLine objects and the rest are assigned as a Null value. I want to be able to delete the JobLine object assigned to the

```<code>line_number_3
</code>```

attribute of a RepairOrder object and have the remaining filled attributes re arranged to fill the

```<code>line_number_(1-4)
</code>```

attributes of that RepairOrder object.

Here is what I have tried so far:

```<code>views.py
def advanced_delete_line(request, pk, jl):
user = request.user

if request.method == "POST":
    raise PermissionDenied
else:
    # Get RepairOrder object with pk passed in from url
    ro_obj = RepairOrder.objects.get(pk=pk, user=user)
    # Get attribute object of 'line_number_(jl passed in from url)
    ro_line = getattr(ro_obj, "line_number_" + str(jl))
    # Delete this object
    ro_line.delete()
    # Get the object assigned to the next numerically higher attribute or RepairOrder object
    x = int(jl) + 1
    for i in range(10-int(jl)):  # Only loop as many times is needed
        # Get the object assigned to the next numerically higher attribute or RepairOrder object
        line = getattr(ro_obj, "line_number_" + str(x))
        y = x - 1
        # Assign the previously retrieved object to the next lower job_line_attribute
        line_2 = setattr(ro_obj, "line_number_" + str(y), line)
        if line is None:
            pass
        else:
            line_2.save()
        # Do it all over again but starting at the next numerically higher attribute
        x += 1

    return HttpResponseRedirect('/advanced/repair-order/' + str(pk) + "/")
</code>```

I am having little to no luck with this method. Can anyone provide me with a better way to do this?

答:
I think you need to save line_2 after setting it to None the first time.  See if this change in the for-loop helps:</p>

```<code>for i in range(10-int(jl)):  # Only loop as many times is needed
    # Get the object assigned to the next numerically higher attribute or RepairOrder object
    line = getattr(ro_obj, "line_number_" + str(x))
    y = x - 1
    # Assign the previously retrieved object to the next lower job_line_attribute
    line_2 = setattr(ro_obj, "line_number_" + str(y), line)
    line_2.save()
    if line is None:
        break
    else:
        # Do it all over again but starting at the next numerically higher attribute
        x += 1

return HttpResponseRedirect('/advanced/repair-order/' + str(pk) + "/")
</code>```

Body:
I have a model like so:

class RepairOrder(models.Model):
user = models.ForeignKey(User)
ro_number = models.IntegerField(validators=[MaxValueValidator(999999999999)])
service_writer = models.ForeignKey(ServiceWriter, null=True, blank=True)
RO_STATUS_CHOICES = (
    ('P', 'Pending'),
    ('O', 'Open'),
    ('C', 'Closed')
)
ro_status = models.CharField(max_length=10, blank=False, choices=RO_STATUS_CHOICES)
open_date = models.DateTimeField()
closed_date = models.DateTimeField(null=True, blank=True)
mileage = models.IntegerField(blank=False, validators=[MaxValueValidator(999999999999)])
line_number_1 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_1')
line_number_2 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_2')
line_number_3 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_3')
line_number_4 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL
                                  , related_name='line_number_4')
line_number_5 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_5')
line_number_6 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_6')
line_number_7 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_7')
line_number_8 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_8')
line_number_9 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_9')
line_number_10 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                   related_name='line_number_10')
vehicle = models.ForeignKey(Vehicle, blank=False, related_name='vehicle')

def __str__(self):
    return str(self.ro_number)

Some of these objects might have

line_number_(1 through 5)

assigned to a JobLine object and the remaining set as Null.
Other RepairOrder objects may only have

line_number_(1 through 3)

assigned to a JobLine object while the remaining are set as Null. But during the creation of a RepairOrder object the

line_number_(x)

attributes are always assigned in ascending order starting from 1.

Here is what I am trying to accomplish:
Lets assume I have a RepairOrder that has

line_number_(1 through 5)

assigned to JobLine objects and the rest are assigned as a Null value. I want to be able to delete the JobLine object assigned to the

line_number_3

attribute of a RepairOrder object and have the remaining filled attributes re arranged to fill the

line_number_(1-4)

attributes of that RepairOrder object.

Here is what I have tried so far:

views.py
def advanced_delete_line(request, pk, jl):
user = request.user

if request.method == "POST":
    raise PermissionDenied
else:
    # Get RepairOrder object with pk passed in from url
    ro_obj = RepairOrder.objects.get(pk=pk, user=user)
    # Get attribute object of 'line_number_(jl passed in from url)
    ro_line = getattr(ro_obj, "line_number_" + str(jl))
    # Delete this object
    ro_line.delete()
    # Get the object assigned to the next numerically higher attribute or RepairOrder object
    x = int(jl) + 1
    for i in range(10-int(jl)):  # Only loop as many times is needed
        # Get the object assigned to the next numerically higher attribute or RepairOrder object
        line = getattr(ro_obj, "line_number_" + str(x))
        y = x - 1
        # Assign the previously retrieved object to the next lower job_line_attribute
        line_2 = setattr(ro_obj, "line_number_" + str(y), line)
        if line is None:
            pass
        else:
            line_2.save()
        # Do it all over again but starting at the next numerically higher attribute
        x += 1

    return HttpResponseRedirect('/advanced/repair-order/' + str(pk) + "/")

I am having little to no luck with this method. Can anyone provide me with a better way to do this?

Body:
I think you need to save line_2 after setting it to None the first time.  See if this change in the for-loop helps:

for i in range(10-int(jl)):  # Only loop as many times is needed
    # Get the object assigned to the next numerically higher attribute or RepairOrder object
    line = getattr(ro_obj, "line_number_" + str(x))
    y = x - 1
    # Assign the previously retrieved object to the next lower job_line_attribute
    line_2 = setattr(ro_obj, "line_number_" + str(y), line)
    line_2.save()
    if line is None:
        break
    else:
        # Do it all over again but starting at the next numerically higher attribute
        x += 1

return HttpResponseRedirect('/advanced/repair-order/' + str(pk) + "/")


问:
What are options for a global incrementing counter?
I am building a system that would benefit from a global incrementing counter. Basically, a service that increments a counter and returns the value. I've tried Azure Page Blobs (counter increment header), Redis (INCR) and SQL Server (Identity). They all work, but the first two are fairly slow, generally taking on the order of a second to generate 2000-3000 numbers. SQL Server is much faster, but only after the connection is open.

What are other options, either in Azure, AWS, or software (e.g., redis)? Are there any services that are especially good at this?

答:
You can use AWS DynamoDB Atomic Counters to implement the Global Counter.

You can use the UpdateItem operation to implement an atomic counter—a
  numeric attribute that is incremented, unconditionally, without
  interfering with other write requests. (All write requests are applied
  in the order in which they were received.) With an atomic counter, the
  updates are not idempotent. In other words, the numeric value will
  increment each time you call UpdateItem.

This allows to build a reliable counter where you can adjust the throughput depending on your scale (Autoscaling enabled) and also to replicate across the Globe with recently introduced Global Tables(Optionally) which provides fast, local, read and write performance.

Global Tables builds upon DynamoDB’s global footprint to provide you
  with a fully managed, multi-region, and multi-master database that
  provides fast, local, read and write performance for massively scaled,
  global applications. Global Tables replicates your Amazon DynamoDB
  tables automatically across your choice of AWS regions.


答:
You can create a new thread running your method, then:

```<code>thread.Start();
bool success = thread.Join(20000);
</code>```

Join returns true if thread finished successfully before designated time. Obviously, would not abort the method (probably no way to do that directly), but the thread -- but it seems that would accomplish what you desired.

A simple threading code example probably would go something like below. Note I made some assumptions about signature with parameter, all this in some class, etc. For method:

```<code>    public string DoSomethingComplex(int param)
</code>```

and then in the same class:

```<code>public delegate void Callback(string newFoo);

public void ThreadedDoSomethingComplexEnded(string newFoo)
{
    foo = newFoo;
}

private static void ThreadedDoSomethingComplex(ClassFooIsIn fooObject, int param, Callback callback)
{
    var newFoo = fooObject.DoSomethingComplex(param);
    callback(newFoo);
}
</code>```

usage aka code in some other method in ClassFooIsIn:

```<code>var thread = new Thread(() => ThreadedDoSomethingComplex(this, param, ThreadedDoSomethingComplexEnded));
thread.Start();

if (!thread.Join(20000))
{
     foo = "";
}
</code>```

Foo should be initialized before above shown usage, so in reality you could possibly skip foo = ""; line.

Body:
How can I abort the execution of a method if its taking too long to run?

e.g.

string foo = DoSomethingComplex();

but if DoSomethingComplex() is taking too long (20 seconds lets say).
then just set foo to "";

Body:
You can create a new thread running your method, then:

thread.Start();
bool success = thread.Join(20000);

Join returns true if thread finished successfully before designated time. Obviously, would not abort the method (probably no way to do that directly), but the thread -- but it seems that would accomplish what you desired.

A simple threading code example probably would go something like below. Note I made some assumptions about signature with parameter, all this in some class, etc. For method:

    public string DoSomethingComplex(int param)

and then in the same class:

public delegate void Callback(string newFoo);

public void ThreadedDoSomethingComplexEnded(string newFoo)
{
    foo = newFoo;
}

private static void ThreadedDoSomethingComplex(ClassFooIsIn fooObject, int param, Callback callback)
{
    var newFoo = fooObject.DoSomethingComplex(param);
    callback(newFoo);
}

usage aka code in some other method in ClassFooIsIn:

var thread = new Thread(() => ThreadedDoSomethingComplex(this, param, ThreadedDoSomethingComplexEnded));
thread.Start();

if (!thread.Join(20000))
{
     foo = "";
}

Foo should be initialized before above shown usage, so in reality you could possibly skip foo = ""; line.


问:
Geolocation coords not passing from javascript to php
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

```<code>var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};
</code>```

it should send the data to template-userslocation.phpwhere I have this code:

```<code><?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>
</code>```

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

答:
EDIT 2

I have no idea about any WordPress plugins or PHP. Does the lat/lng appear on the network/at the server? Anyway try this: -

```<code>var posZae = function(pos){
                    return {
                                lat: pos.coords.latitude,
                                lng: pos.coords.longitude,
                    }
            };
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var pos = posZae(position);
        var netPOS = JSON.stringify(pos);
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        $.ajax({
            type: 'POST',
            data:  { 'pos' : netPos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};
</code>```

EDIT 1

OK would this ring any bells of familiarity with you?

```<code>    // Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(pos4Net(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : netPOS},
            url: '/wp-content/themes/atripby/template-userslocation.php'
        });
</code>```

ORIGINAL POST:

Not sure where you "pos" is declared. Maybe localizing it with VAR will help instantiate it?

I've had the same/similar problem with the nature of the position object and call the following before trying to transmit it over the network: -

```<code>    var pos4Net =
    function(pos)
    {
        return {
            coords: {
                latitude: pos.coords.latitude,
                longitude: pos.coords.longitude,
                accuracy: pos.coords.accuracy.toFixed()
            },
            timestamp: pos.timestamp
        }
    }
</code>```

So var yourPos = pos4Net(position)

Body:
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};

it should send the data to template-userslocation.phpwhere I have this code:

<?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

Body:
EDIT 2

I have no idea about any WordPress plugins or PHP. Does the lat/lng appear on the network/at the server? Anyway try this: -

var posZae = function(pos){
                    return {
                                lat: pos.coords.latitude,
                                lng: pos.coords.longitude,
                    }
            };
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var pos = posZae(position);
        var netPOS = JSON.stringify(pos);
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        $.ajax({
            type: 'POST',
            data:  { 'pos' : netPos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};

EDIT 1

OK would this ring any bells of familiarity with you?

    // Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(pos4Net(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : netPOS},
            url: '/wp-content/themes/atripby/template-userslocation.php'
        });

ORIGINAL POST:

Not sure where you "pos" is declared. Maybe localizing it with VAR will help instantiate it?

I've had the same/similar problem with the nature of the position object and call the following before trying to transmit it over the network: -

    var pos4Net =
    function(pos)
    {
        return {
            coords: {
                latitude: pos.coords.latitude,
                longitude: pos.coords.longitude,
                accuracy: pos.coords.accuracy.toFixed()
            },
            timestamp: pos.timestamp
        }
    }

So var yourPos = pos4Net(position)


问:
gSOAP: How to compare two value-structs (with JSON-content) in C?
I´m using gSOAP (in C) for a client application, which is calling a Java-webservice. I´m using the function json_call().
I have a request-struct filled with the JSON-input-data and I get a response-struct filled with the JSON-output-data from the Java-service. Both JSONs have the same structure in general, but can have more, less or changed elements.

My task now is to find out, in which elements the response is different from the request. The main-element is a large array with a lot of members, like:

```<code>{
    "objects": [
    {
        "@id": "OBJ00001",
        "name": "value",
        ...
    },
    {
        "@id": "OBJ00002",
        "number": 123,
        ...
    },
    ...
    ]
}
</code>```

I can identify any object of the same kind with the @id field.

It´s simple to iterate the objects array with something like:

```<code>for(i = 0; i < has_size(value_at(response, "objects")); i++)
</code>```

But then I´missing a function, which can compare members ("objects") with the same @id in request and response. Something like "findMemberWithSameField" and then "equal" (which both does not exist!):

```<code>struct member *currentMemberInResponse = NULL;
struct member *memberWithSameField     = NULL;

for(i = 0; i < has_size(value_at(response, "objects")); i++)
{
    /* get the current member out of the response array */
    currentMemberInResponse = nth_value(value_at(response, "objects"), i);

    /* Find member/object with same @id in request */
    memberWithSameField = findMemberWithSameField(value_at(request, "objects"), currentMemberInResponse , "@id"));

    /* equal is true if all fields are the same */
    if(equal(currentMemberInResponse, memberWithSameField))
    {
        /* Do nothing, because nothing changed */
    }
    else
    {
        /* Do something */
    }
}
</code>```

Any idea on that task? Otherwise I have to do write my own "findMemberWithSameField" and "euqal".

Kind regards Daniel

答:
The JSON C++ API defines operator== to compare two objects recursively. The latest version 2.8.55 works (I've tested) to compare two JSON objects, where operator== calls the following function:

```<code>bool json_eqv(const value& x, const value& y)
{
  ...
  switch (x.__type)
  {
    ...
    case SOAP_TYPE__struct:
      if (x.size() != y.size())
        return false;
      else
      {
        const _struct& s = x;
        const _struct& t = y;
        for (_struct::iterator i = s.begin(); i != s.end(); ++i)
        {
          _struct::iterator j;
          for (j = t.begin(); j != t.end(); ++j)
            if (!strcmp(i.name(), j.name()))
              break;
          if (j == t.end() || *i != *j)
            return false;
        }
        return true;
      }
</code>```

This can be rewritten to C with something like:

```<code>int json_eqv(const value *x, const value *y)
{
  if (x->__type != y->__type &&
      (x->__type != SOAP_TYPE__i4 || y->__type != SOAP_TYPE__int) &&
      (x->__type != SOAP_TYPE__int || y->__type != SOAP_TYPE__i4))
    return false;
  switch (x->__type)
  {
    case SOAP_TYPE__boolean:
    case SOAP_TYPE__i4:
    case SOAP_TYPE__int:
      return int_of(x) == int_of(y);
    case SOAP_TYPE__double:
      return double_of(x) == double_of(y);
    case SOAP_TYPE__string:
    case SOAP_TYPE__dateTime_DOTiso8601:
      return !strcmp(string_of(x), string_of(y));
    case SOAP_TYPE__struct:
      if (has_size(x) != has_size(y))
        return 0;
      else
      {
        size_t i, j;
        for (i = 0; i < has_size(x); ++i)
        {
          for (j = 0; j < has_size(y); ++j)
            if (!strcmp(nth_member(x, i), nth_member(y, j))
              break;
          if (j == has_size(y) || !json_eqv(nth_value(x, i), nth_value(y, j))
            return 0;
        }
        return 1;
      }
    case SOAP_TYPE__array:
      if (has_size(x) != has_size(y))
        return 0;
      else
      {
        int i;
        for (i = 0 ; i < has_size(x); ++i)
          if (!json_eqv(nth_nth(x, i), nth_nth(y, i))
            return 0;
        return 1;
      }
    default:
      return 0;
  }
}
</code>```

Body:
I´m using gSOAP (in C) for a client application, which is calling a Java-webservice. I´m using the function json_call().
I have a request-struct filled with the JSON-input-data and I get a response-struct filled with the JSON-output-data from the Java-service. Both JSONs have the same structure in general, but can have more, less or changed elements.

My task now is to find out, in which elements the response is different from the request. The main-element is a large array with a lot of members, like:

{
    "objects": [
    {
        "@id": "OBJ00001",
        "name": "value",
        ...
    },
    {
        "@id": "OBJ00002",
        "number": 123,
        ...
    },
    ...
    ]
}

I can identify any object of the same kind with the @id field.

It´s simple to iterate the objects array with something like:

for(i = 0; i < has_size(value_at(response, "objects")); i++)

But then I´missing a function, which can compare members ("objects") with the same @id in request and response. Something like "findMemberWithSameField" and then "equal" (which both does not exist!):

struct member *currentMemberInResponse = NULL;
struct member *memberWithSameField     = NULL;

for(i = 0; i < has_size(value_at(response, "objects")); i++)
{
    /* get the current member out of the response array */
    currentMemberInResponse = nth_value(value_at(response, "objects"), i);

    /* Find member/object with same @id in request */
    memberWithSameField = findMemberWithSameField(value_at(request, "objects"), currentMemberInResponse , "@id"));

    /* equal is true if all fields are the same */
    if(equal(currentMemberInResponse, memberWithSameField))
    {
        /* Do nothing, because nothing changed */
    }
    else
    {
        /* Do something */
    }
}

Any idea on that task? Otherwise I have to do write my own "findMemberWithSameField" and "euqal".

Kind regards Daniel

Body:
The JSON C++ API defines operator== to compare two objects recursively. The latest version 2.8.55 works (I've tested) to compare two JSON objects, where operator== calls the following function:

bool json_eqv(const value& x, const value& y)
{
  ...
  switch (x.__type)
  {
    ...
    case SOAP_TYPE__struct:
      if (x.size() != y.size())
        return false;
      else
      {
        const _struct& s = x;
        const _struct& t = y;
        for (_struct::iterator i = s.begin(); i != s.end(); ++i)
        {
          _struct::iterator j;
          for (j = t.begin(); j != t.end(); ++j)
            if (!strcmp(i.name(), j.name()))
              break;
          if (j == t.end() || *i != *j)
            return false;
        }
        return true;
      }

This can be rewritten to C with something like:

int json_eqv(const value *x, const value *y)
{
  if (x->__type != y->__type &&
      (x->__type != SOAP_TYPE__i4 || y->__type != SOAP_TYPE__int) &&
      (x->__type != SOAP_TYPE__int || y->__type != SOAP_TYPE__i4))
    return false;
  switch (x->__type)
  {
    case SOAP_TYPE__boolean:
    case SOAP_TYPE__i4:
    case SOAP_TYPE__int:
      return int_of(x) == int_of(y);
    case SOAP_TYPE__double:
      return double_of(x) == double_of(y);
    case SOAP_TYPE__string:
    case SOAP_TYPE__dateTime_DOTiso8601:
      return !strcmp(string_of(x), string_of(y));
    case SOAP_TYPE__struct:
      if (has_size(x) != has_size(y))
        return 0;
      else
      {
        size_t i, j;
        for (i = 0; i < has_size(x); ++i)
        {
          for (j = 0; j < has_size(y); ++j)
            if (!strcmp(nth_member(x, i), nth_member(y, j))
              break;
          if (j == has_size(y) || !json_eqv(nth_value(x, i), nth_value(y, j))
            return 0;
        }
        return 1;
      }
    case SOAP_TYPE__array:
      if (has_size(x) != has_size(y))
        return 0;
      else
      {
        int i;
        for (i = 0 ; i < has_size(x); ++i)
          if (!json_eqv(nth_nth(x, i), nth_nth(y, i))
            return 0;
        return 1;
      }
    default:
      return 0;
  }
}


问:
laravel 5.4 Mailable implements ShouldQueue don't sent email
This work fine and the email is sent to log(MAIL_DRIVER=log) and mailtrap.io(MAIL_DRIVER=smtp) succesfully

```<code>            class VerificationNewAccount extends Mailable
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }
            // in controller
            Mail::to('test@gmail.com')->send(new VerificationNewAccount());
</code>```

When i implement ShouldQueue the email is printed in log(MAIL_DRIVER=log) but when i try to send to mailtrap.io(MAIL_DRIVER=smtp) the email never is sent

```<code>            // running the queue in terminal
            php artisan queue:work --queue
</code>```

then the class implements ShouldQueue

```<code>            class VerificationNewAccount extends Mailable implements ShouldQueue
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }
            // in controller
            Mail::to('test@gmail.com')->send(new VerificationNewAccount());
</code>```

There is no error printed in laravel.log file. i don't know what to do.

答:
Well, after many test this is how i solved the problem.

Dont use ShouldQueue

```<code>            class VerificationNewAccount extends Mailable
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }
</code>```

Instead use the basis ->queue

```<code>            Mail::to('test@gmail.com')->queue(new VerificationNewAccount($ran));
</code>```

now the email is sent to gmail

The weird part is that now the email is not printed in log.
Well i dont care. It woks!

Body:
This work fine and the email is sent to log(MAIL_DRIVER=log) and mailtrap.io(MAIL_DRIVER=smtp) succesfully

            class VerificationNewAccount extends Mailable
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }
            // in controller
            Mail::to('test@gmail.com')->send(new VerificationNewAccount());

When i implement ShouldQueue the email is printed in log(MAIL_DRIVER=log) but when i try to send to mailtrap.io(MAIL_DRIVER=smtp) the email never is sent

            // running the queue in terminal
            php artisan queue:work --queue

then the class implements ShouldQueue

            class VerificationNewAccount extends Mailable implements ShouldQueue
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }
            // in controller
            Mail::to('test@gmail.com')->send(new VerificationNewAccount());

There is no error printed in laravel.log file. i don't know what to do.

Body:
Well, after many test this is how i solved the problem.

Dont use ShouldQueue

            class VerificationNewAccount extends Mailable
            {
                use Queueable, SerializesModels;
                public function __construct()
                {
                }
                public function build()
                {
                    return $this->from('noreply@example.com')
                        ->view('email.verification-request');
                }
            }

Instead use the basis ->queue

            Mail::to('test@gmail.com')->queue(new VerificationNewAccount($ran));

now the email is sent to gmail

The weird part is that now the email is not printed in log.
Well i dont care. It woks!


问:
How can i correctly access the data in my database using room library
```<code>List<Game> gamesList = db.gameDao().getAll();
</code>```

I am trying to iterate through the list and make use of the data in the database, the command successfully receives the rows but how can I use the content of each row

答:
You got the List already. now you can loop through and get the data like this</p>

```<code>for(Game singleGameItem: gameList)
    singleGameItem.memberObj
</code>```

Body:
List<Game> gamesList = db.gameDao().getAll();

I am trying to iterate through the list and make use of the data in the database, the command successfully receives the rows but how can I use the content of each row

Body:
You got the List already. now you can loop through and get the data like this

for(Game singleGameItem: gameList)
    singleGameItem.memberObj