问:
Mapbox GL JS: Style is not done loading
I have a map wher we can classically switch from one style to another, streets to satellite for example.

I want to be informed that the style is loaded to then add a layer.

According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.

That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.

My code is:

```<code>mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v10',
    center: [5,45.5],
    zoom: 7
});

map.on('load', function () {

    loadRegionMask();
});

map.on('styledataloading', function (styledata) {

    if (map.isStyleLoaded()) {
        loadRegionMask();
    }
});

$('#typeMap').on('click', function switchLayer(layer) {
    var layerId = layer.target.control.id;

    switch (layerId) {
        case 'streets':
            map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
        break;

        case 'satellite':
            map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
        break;
    }
});

function loadJSON(callback) {

  var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");

  xobj.open('GET', 'regions.json', true);

  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

function loadRegionMask() {

  loadJSON(function(response) {

    var geoPoints_JSON = JSON.parse(response);

    map.addSource("region-boundaries", {
      'type': 'geojson',
      'data': geoPoints_JSON,
    });

    map.addLayer({
        'id': 'region-fill',
        'type': 'fill',
        'source': "region-boundaries",
        'layout': {},
        'paint': {
            'fill-color': '#C4633F',
            'fill-opacity': 0.5
        },
        "filter": ["==", "$type", "Polygon"]
    });
  });
}
</code>```

And the error is:

```<code>Uncaught Error: Style is not done loading
    at t._checkLoaded (mapbox-gl.js:308)
    at t.addSource (mapbox-gl.js:308)
    at e.addSource (mapbox-gl.js:390)
    at map.js:92 (map.addSource("region-boundaries",...)
    at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
</code>```

Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?

答:
I was facing a similar issue and ended up with this solution:

I created a small function that would check if the style was done loading:

```<code>// Check if the Mapbox-GL style is loaded.
function checkIfMapboxStyleIsLoaded() {
  if (map.isStyleLoaded()) {
    return true; // When it is safe to manipulate layers
  } else {
    return false; // When it is not safe to manipulate layers
  }
}
</code>```

Then whenever I swap or otherwise modify layers in the app I use the function like this:

```<code>function swapLayer() {
  var check = checkIfMapboxStyleIsLoaded();
  if (!check) {
    // It's not safe to manipulate layers yet, so wait 200ms and then check again
    setTimeout(function() {
      swapLayer();
    }, 200);
    return;
  }

  // Whew, now it's safe to manipulate layers!
  the rest of the swapLayer logic goes here...

}
</code>```

Title: Mapbox GL JS: Style is not done loading

Body:
I have a map wher we can classically switch from one style to another, streets to satellite for example.

I want to be informed that the style is loaded to then add a layer.

According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.

That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.

My code is:

mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v10',
    center: [5,45.5],
    zoom: 7
});

map.on('load', function () {

    loadRegionMask();
});

map.on('styledataloading', function (styledata) {

    if (map.isStyleLoaded()) {
        loadRegionMask();
    }
});

$('#typeMap').on('click', function switchLayer(layer) {
    var layerId = layer.target.control.id;

    switch (layerId) {
        case 'streets':
            map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
        break;

        case 'satellite':
            map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
        break;
    }
});

function loadJSON(callback) {

  var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");

  xobj.open('GET', 'regions.json', true);

  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

function loadRegionMask() {

  loadJSON(function(response) {

    var geoPoints_JSON = JSON.parse(response);

    map.addSource("region-boundaries", {
      'type': 'geojson',
      'data': geoPoints_JSON,
    });

    map.addLayer({
        'id': 'region-fill',
        'type': 'fill',
        'source': "region-boundaries",
        'layout': {},
        'paint': {
            'fill-color': '#C4633F',
            'fill-opacity': 0.5
        },
        "filter": ["==", "$type", "Polygon"]
    });
  });
}

And the error is:

Uncaught Error: Style is not done loading
    at t._checkLoaded (mapbox-gl.js:308)
    at t.addSource (mapbox-gl.js:308)
    at e.addSource (mapbox-gl.js:390)
    at map.js:92 (map.addSource("region-boundaries",...)
    at XMLHttpRequest.xobj.onreadystatechange (map.js:63)

Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?

Body:
I was facing a similar issue and ended up with this solution:

I created a small function that would check if the style was done loading:

// Check if the Mapbox-GL style is loaded.
function checkIfMapboxStyleIsLoaded() {
  if (map.isStyleLoaded()) {
    return true; // When it is safe to manipulate layers
  } else {
    return false; // When it is not safe to manipulate layers
  }
}

Then whenever I swap or otherwise modify layers in the app I use the function like this:

function swapLayer() {
  var check = checkIfMapboxStyleIsLoaded();
  if (!check) {
    // It's not safe to manipulate layers yet, so wait 200ms and then check again
    setTimeout(function() {
      swapLayer();
    }, 200);
    return;
  }

  // Whew, now it's safe to manipulate layers!
  the rest of the swapLayer logic goes here...

}


来源: stackexchange

问:
Typescript string literal union type
I have a class property with a type that's the union of multiple string literals:

```<code>public reaction? : 'haha' | 'wow' | 'angry' | 'sad' | 'like';
</code>```

What I'm trying to do was to have these strings defined somewhere else in some kind of array and then just use the array in the property definition. So something like:

```<code>allowedStrings = ['haha','wow','angry','sad','like'];
public reaction? : allowedStrings;
</code>```

I get that the above is not possible but it's the general idea. Does typescript offer anything that does the job?

答:
It depends on exactly how you intend to use it, but a string enum may give you what you are after:

```<code>enum ReactionKind {
    haha = 'haha',
    wow = 'wow',
    angry = 'angry',
    sad = 'sad',
    like = 'like'
}

const reaction: ReactionKind = ReactionKind.angry;

// Get the string value
const stringValue = ReactionKind[reaction];

// Get the Enum from a string
const enumValue = ReactionKind['wow'];
</code>```

You can still use the plain string values where you need them, but you get to use it as a type and as a runtime value, which seems to be what you are after.

You'll also notice that with string enums, if you use a string key when mapping to an enum, it will get checked... as long as you are using --noImplicitAny.

```<code>// Error
const enumValue = ReactionKind['wat'];
</code>```

ContentLicense: CC BY-SA 3.0

Title: Typescript string literal union type

Body:
I have a class property with a type that's the union of multiple string literals:

public reaction? : 'haha' | 'wow' | 'angry' | 'sad' | 'like';

What I'm trying to do was to have these strings defined somewhere else in some kind of array and then just use the array in the property definition. So something like:

allowedStrings = ['haha','wow','angry','sad','like'];
public reaction? : allowedStrings;

I get that the above is not possible but it's the general idea. Does typescript offer anything that does the job?

Body:
It depends on exactly how you intend to use it, but a string enum may give you what you are after:

enum ReactionKind {
    haha = 'haha',
    wow = 'wow',
    angry = 'angry',
    sad = 'sad',
    like = 'like'
}

const reaction: ReactionKind = ReactionKind.angry;

// Get the string value
const stringValue = ReactionKind[reaction];

// Get the Enum from a string
const enumValue = ReactionKind['wow'];

You can still use the plain string values where you need them, but you get to use it as a type and as a runtime value, which seems to be what you are after.

You'll also notice that with string enums, if you use a string key when mapping to an enum, it will get checked... as long as you are using --noImplicitAny.

// Error
const enumValue = ReactionKind['wat'];


问:
Assign a date to specific text in R
I have a data frame in R as follows called Ident.

```<code>        Date coredata.Ident.
1  2017-09-01            <NA>
2  2017-09-03            <NA>
3  2017-09-04            <NA>
4  2017-09-05               0
5  2017-09-06               0
6  2017-09-07               0
7  2017-09-08               0
8  2017-09-10               0
9  2017-09-11            Doji
10 2017-09-12            <NA>
11 2017-09-13               0
12 2017-09-14  Bull.Engulfing
13 2017-09-15               0
14 2017-09-17               0
15 2017-09-18  Bear.Engulfing
16 2017-09-19            Doji
17 2017-09-20  Bear.Engulfing
18 2017-09-21  Bull.Engulfing
19 2017-09-22               0
20 2017-09-24               0
21 2017-09-25  Bear.Engulfing
22 2017-09-26               0
23 2017-09-27               0
24 2017-09-28               0
25 2017-09-29               0
</code>```

I would like to assign the next date after that there is a Bull.Engulfing to a variable called DateSelect1 and then the second Bull.Engulfing would be assigned to DateSelect2 etc. So that all of the Bull.Engulfing have a date assigned to them.

So in this example, as there is a Bull.Engulfing on 2017-09-14 line 12, DateSelect1 should be 2017-09-15 as it is the next row. Hope this makes sense.

TIA

Title: Assign a date to specific text in R

Body:
I have a data frame in R as follows called Ident.

        Date coredata.Ident.
1  2017-09-01            <NA>
2  2017-09-03            <NA>
3  2017-09-04            <NA>
4  2017-09-05               0
5  2017-09-06               0
6  2017-09-07               0
7  2017-09-08               0
8  2017-09-10               0
9  2017-09-11            Doji
10 2017-09-12            <NA>
11 2017-09-13               0
12 2017-09-14  Bull.Engulfing
13 2017-09-15               0
14 2017-09-17               0
15 2017-09-18  Bear.Engulfing
16 2017-09-19            Doji
17 2017-09-20  Bear.Engulfing
18 2017-09-21  Bull.Engulfing
19 2017-09-22               0
20 2017-09-24               0
21 2017-09-25  Bear.Engulfing
22 2017-09-26               0
23 2017-09-27               0
24 2017-09-28               0
25 2017-09-29               0

I would like to assign the next date after that there is a Bull.Engulfing to a variable called DateSelect1 and then the second Bull.Engulfing would be assigned to DateSelect2 etc. So that all of the Bull.Engulfing have a date assigned to them.

So in this example, as there is a Bull.Engulfing on 2017-09-14 line 12, DateSelect1 should be 2017-09-15 as it is the next row. Hope this makes sense.

TIA

Body:
Assuming the input in the Note subset the data frame and assign each date in that subset to a variable:

dates <- as.Date(subset(DF, coredata.Ident. == "Bull.Engulfing")$Date)
for(i in seq_along(dates)) assign(paste0("DateSelect", i), dates[i])

DateSelect1
## [1] "2017-09-14"
DateSelect2
## [1] "2017-09-21"

Note:  The input in reproducible form is:

Lines <- "
        Date coredata.Ident.
1  2017-09-01            <NA>
2  2017-09-03            <NA>
3  2017-09-04            <NA>
4  2017-09-05               0
5  2017-09-06               0
6  2017-09-07               0
7  2017-09-08               0
8  2017-09-10               0
9  2017-09-11            Doji
10 2017-09-12            <NA>
11 2017-09-13               0
12 2017-09-14  Bull.Engulfing
13 2017-09-15               0
14 2017-09-17               0
15 2017-09-18  Bear.Engulfing
16 2017-09-19            Doji
17 2017-09-20  Bear.Engulfing
18 2017-09-21  Bull.Engulfing
19 2017-09-22               0
20 2017-09-24               0
21 2017-09-25  Bear.Engulfing
22 2017-09-26               0
23 2017-09-27               0
24 2017-09-28               0
25 2017-09-29               0"
DF <- read.table(text = Lines)


问:
nodemon - app crashed - waiting for file changes before starting
I just started learning Node.js. The idea of this small application is to use express and mongosse to store some users in a based cloud database (mongoDB via mlab).

I have two seperate files :

User.js (models/User.js)

```<code>var mongoose = require('mongoose');

module.exports = mongoose.model('User', {

   email : string ,
   pwd : string

});
</code>```

server.js (dossier root)

```<code>var express = require('express')
var cors = require('cors')
var bparser = require('body-parser')
var mongoose = require('mongoose')

var User = require('./models/User.js')

var app = express()

app.use(cors())
app.use(bparser.json())

app.post('/register', (req,res) => {
    userData = req.body;
    var user = new User(userData);

    user.save((err, result) => {
        if(err) console.log('IL YA UNE ERREUR')
        result.sendStatus(200);
    })

})

mongoose.connect('mongodb://user:pwd@ds261755.mlab.com:61755/myapp', { useMongoClient: true } , (erreur) => {
    if(!erreur)
    console.log('Connexion etablie');
})

app.listen(3000)
</code>```

When I execute : nodemon server.js, I get the error below:

```<code>D:\Bureau\MEAN\appBackend\models\User.js:5
   email : string ,
           ^

ReferenceError: string is not defined
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\models\User.js:5:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\server.js:6:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

Do you have any idea about this error?

答:
define

```<code>module.exports = mongoose.model('User', new mongoose.Schema({

   email : 'string' ,
   pwd : 'string'
   })
});
</code>```

There is no string variable in the code .

Body:
I just started learning Node.js. The idea of this small application is to use express and mongosse to store some users in a based cloud database (mongoDB via mlab).

I have two seperate files :

User.js (models/User.js)

var mongoose = require('mongoose');

module.exports = mongoose.model('User', {

   email : string ,
   pwd : string

});

server.js (dossier root)

var express = require('express')
var cors = require('cors')
var bparser = require('body-parser')
var mongoose = require('mongoose')

var User = require('./models/User.js')

var app = express()

app.use(cors())
app.use(bparser.json())

app.post('/register', (req,res) => {
    userData = req.body;
    var user = new User(userData);

    user.save((err, result) => {
        if(err) console.log('IL YA UNE ERREUR')
        result.sendStatus(200);
    })

})

mongoose.connect('mongodb://user:pwd@ds261755.mlab.com:61755/myapp', { useMongoClient: true } , (erreur) => {
    if(!erreur)
    console.log('Connexion etablie');
})

app.listen(3000)

When I execute : nodemon server.js, I get the error below:

D:\Bureau\MEAN\appBackend\models\User.js:5
   email : string ,
           ^

ReferenceError: string is not defined
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\models\User.js:5:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\server.js:6:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
[nodemon] app crashed - waiting for file changes before starting...

Do you have any idea about this error?

Body:
define

module.exports = mongoose.model('User', new mongoose.Schema({

   email : 'string' ,
   pwd : 'string'
   })
});

There is no string variable in the code .


问:
Var condition threads in a specific order
How can I show the threads in a specific order?
I need to print with condition variables the following order of execution, but I do not understand how I can do it.

is order I  need print

1
3
1
2
1

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

struct DatoHilo{int dato;};
void * funhilos(void *);
int turno = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond  = PTHREAD_COND_INITIALIZER;

int main(){
    clock_t t_ini, t_fin;
    double secs;
    int nhilos = 0, i=0;
    pthread_t *pidhilos = NULL;
    struct DatoHilo *datohilo;
    printf("Numero de hilos\n");
    scanf("%d", &nhilos);
    //creacion de hilos
    pidhilos = (pthread_t *) calloc(nhilos, sizeof(pthread_t));
    for(i=0; i<nhilos; i++){
        datohilo = (struct DatoHilo*)malloc(sizeof(struct DatoHilo));
        datohilo->dato = i;
        pthread_create(&pidhilos[i], NULL, funhilos, (void*)datohilo);
    }
    t_ini = clock();
    for(i=0; i<nhilos; i++)
        pthread_join(pidhilos[i], NULL);
    t_fin = clock();
    secs = (double)(t_fin - t_ini) / CLOCKS_PER_SEC;
    printf("%.16g milisegundos\n", secs * 1000.0);

    free(pidhilos);
    return 0;
}

void * funhilos( void *arg){
    int myturno = ((struct DatoHilo *)arg)->dato;

    pthread_mutex_lock(&mutex);
    while(turno != myturno) pthread_cond_wait(&cond, &mutex);
    printf("Hilo turno %d\t[%u]\n", myturno, (unsigned int)pthread_self());
    turno ++;
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);
    free(arg);
    pthread_exit(0);
}
</code>```

答:
If your order is 1 3 1 2 1 3 ... and you really want to use threads then you need three condition variables - one for each thread and each time we will signal to next desirable thread.

This is the basic code for thread N:

```<code>pthread_mutex_lock(m);
while(!awakenedN)
    pthread_cond_wait(condN, m);
printf("thread N"); //Nth thread's work
pthread_cond_signal(...); //awaken next thread
awakened... = 1;
awakenedN = 0;
pthread_mutex_unlock(m);
</code>```

So all you need is to choose what does ... stands for and the choice is pretty obvious:

```<code>int awakened1 = 1, awakened2 = 0, awakened3 = 0;
int turn = 1;

// thread 1
pthread_mutex_lock(m);
while(!awakened1)
    pthread_cond_wait(cond1, m);
printf("thread 1");
// after first thread we can call second or third:
switch(turn) {
    case 1:
        turn = 2;
        awakened3 = 1;
        pthread_cond_signal(cond3);
        break;
    case 2:
        turn = 1;
        awakened2 = 1;
        pthread_cond_signal(cond2);
        break;
}
awakened1 = 0;
pthread_mutex_unlock(m);

// thread 2
pthread_mutex_lock(m);
while(!awakened2)
    pthread_cond_wait(cond2, m);
printf("thread 2");
awakened1 = 1;
awakened2 = 0;
pthread_cond_signal(cond1);
pthread_mutex_unlock(m);

// thread 3
pthread_mutex_lock(m);
while(!awakened3)
    pthread_cond_wait(cond3, m);
printf("thread 3");
awakened1 = 1;
awakened3 = 0;
pthread_cond_signal(cond1);
pthread_mutex_unlock(m);
</code>```

After that you can easily generalize this for N (number of threads) greater than 3.

Body:
How can I show the threads in a specific order?
I need to print with condition variables the following order of execution, but I do not understand how I can do it.

is order I  need print

1
3
1
2
1

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

struct DatoHilo{int dato;};
void * funhilos(void *);
int turno = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond  = PTHREAD_COND_INITIALIZER;

int main(){
    clock_t t_ini, t_fin;
    double secs;
    int nhilos = 0, i=0;
    pthread_t *pidhilos = NULL;
    struct DatoHilo *datohilo;
    printf("Numero de hilos\n");
    scanf("%d", &nhilos);
    //creacion de hilos
    pidhilos = (pthread_t *) calloc(nhilos, sizeof(pthread_t));
    for(i=0; i<nhilos; i++){
        datohilo = (struct DatoHilo*)malloc(sizeof(struct DatoHilo));
        datohilo->dato = i;
        pthread_create(&pidhilos[i], NULL, funhilos, (void*)datohilo);
    }
    t_ini = clock();
    for(i=0; i<nhilos; i++)
        pthread_join(pidhilos[i], NULL);
    t_fin = clock();
    secs = (double)(t_fin - t_ini) / CLOCKS_PER_SEC;
    printf("%.16g milisegundos\n", secs * 1000.0);

    free(pidhilos);
    return 0;
}

void * funhilos( void *arg){
    int myturno = ((struct DatoHilo *)arg)->dato;

    pthread_mutex_lock(&mutex);
    while(turno != myturno) pthread_cond_wait(&cond, &mutex);
    printf("Hilo turno %d\t[%u]\n", myturno, (unsigned int)pthread_self());
    turno ++;
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);
    free(arg);
    pthread_exit(0);
}

Body:
If your order is 1 3 1 2 1 3 ... and you really want to use threads then you need three condition variables - one for each thread and each time we will signal to next desirable thread.

This is the basic code for thread N:

pthread_mutex_lock(m);
while(!awakenedN)
    pthread_cond_wait(condN, m);
printf("thread N"); //Nth thread's work
pthread_cond_signal(...); //awaken next thread
awakened... = 1;
awakenedN = 0;
pthread_mutex_unlock(m);

So all you need is to choose what does ... stands for and the choice is pretty obvious:

int awakened1 = 1, awakened2 = 0, awakened3 = 0;
int turn = 1;

// thread 1
pthread_mutex_lock(m);
while(!awakened1)
    pthread_cond_wait(cond1, m);
printf("thread 1");
// after first thread we can call second or third:
switch(turn) {
    case 1:
        turn = 2;
        awakened3 = 1;
        pthread_cond_signal(cond3);
        break;
    case 2:
        turn = 1;
        awakened2 = 1;
        pthread_cond_signal(cond2);
        break;
}
awakened1 = 0;
pthread_mutex_unlock(m);

// thread 2
pthread_mutex_lock(m);
while(!awakened2)
    pthread_cond_wait(cond2, m);
printf("thread 2");
awakened1 = 1;
awakened2 = 0;
pthread_cond_signal(cond1);
pthread_mutex_unlock(m);

// thread 3
pthread_mutex_lock(m);
while(!awakened3)
    pthread_cond_wait(cond3, m);
printf("thread 3");
awakened1 = 1;
awakened3 = 0;
pthread_cond_signal(cond1);
pthread_mutex_unlock(m);

After that you can easily generalize this for N (number of threads) greater than 3.


问:
One big MySQL DB or a thousand little SQLite databases?
I am working on a Web based organisation tool. I am not aiming the same market as the wonderful Basecamp, but let's say the way users and data interact look like the same.

I will have to deal with user customisation, file uploads and graphical tweaks. There is a fora for each account as well. And I'd like to provide a way to backup easily each account.

I have been thinking how to create a reasonable architecture and have been trained to use beautifully normalized data in a single (yet distributed if needed) MySQL DB. Recently I have been wondering :
is it possible to think about using one SQLITE DB to store the data  for each account and only use MYSQL for the general web site management ?

The pro :

backing up is straightforward  : set version, zip, upload.

don't bother if each account use a massive fora : the mess is in one file for every one of them.

SQLITE is lightening fast, no expensive connection time...

Table scheme is much simplier : no need to make any distinction between account every times

The cons :

don't know if it's scalable

don't know if the hard drive will keep up

don't know if there is a way for SQLITE to not be stored in RAM since it would be quickly a disaster

lots of dir and subdirs : will this be ok ?

maintenance issue : upgrading the live site means upgrading all the db one by one

dev issue : setting a dev / pre prod / prod env will be quite hard

commom data will still require using mysql, so we would end end with 2 DB connections for each page, arg

More cons that pros, still, it makes me wonder (zepplin style).

What do you say ?

答:
I gave it more thoughts, and I see more problems :

If I want to use a common area for all the forum, I am smoked

If I want to search trough all the web sites, it will be apocalyptic

If I want stats, God save my soul

This was a bad idea.

Anyway, writing it on SO forced me to think seriously about it. Better to have a clear mind before starting.

If one day, somebody is as foolish as me, hope he'll hit the page, so it can help him to reconsider

Love this site (even if it's ASP :-p) : quickest way to help yourself, while still helping others.

OwnerDisplayName: e-satis

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Alex Fort

LastEditorDisplayName: Rich B


问:
google sheet generated html form not "lining up"
How do I get dynamic content from multiple google sheets (within one google sheet) into the same html form?

In the code below, I dynamically create the html form from a main sheet. I want to add a form select, from a supplemental sheet. I cannot get the form.select to be part of one html form.

EDIT: (1) updated var html to include div's for each row. (2) moved form and table html into the html page directly. Form values are still not lining up correctly. Should I be using HTML Template instead?

  <form>

</form>
```

答: Put a function in your project that opens up other Spreadsheets with "openById";  Then return the data to your form with google.script.run.withSuccessHandler(functionName);</p>


问:
show and hide doesn't the opposite of it
I have function show and hide,I want to show 300 line and when you press on more it should show the rest of the text but it doesn't the opposite of it, meaning it show all the text and when you click on more it show less.</p>

答:
You need to assign "showcontent" class an initial style of "display:none;", then every thing should work as expected.

```<code>var html = firstcontent + '<p class="showcontent" style="display:none;">' + secondcontent + '</p><a href="" class="morebtn">' + show_more + '</a></p>';
</code>```

Working demo:
https://jsfiddle.net/48r998f6/

Body:
You need to assign "showcontent" class an initial style of "display:none;", then every thing should work as expected.

var html = firstcontent + '<p class="showcontent" style="display:none;">' + secondcontent + '</p><a href="" class="morebtn">' + show_more + '</a></p>';

Working demo:
https://jsfiddle.net/48r998f6/


问:
Fabric (Crashlytics): Newest build not visible in 'Latest release' section
After the new version (3.5.9) of the app has been in production for couple of days, it is visible in Crashlytics secion of Fabric:

but is not in 'Latest Release':

What's interesting, on the top there is an old version of the app that isn't used that much now.

What could be the reason of such behaviour?

答: This might help you, can you see this

Body: This might help you, can you see this


问:
Using C++ struct with virtual members (i.e. non-POD) in C
In questions such as this, compatibility between C++ classes/structs and C structs is explained as possible as long as all members are of the same type, in the same order, and no virtual members are declared.

That's my problem. I have virtual methods, and I would very much like to keep them when manipulating the struct in C++.

Let's examine this toy example. It's meant to be a C and C++ compatible struct defined in a single header file.

mystr.h:

```<code>#ifdef __cplusplus
#include <string>
struct mystr_base {
    virtual ~mystr_base() {}

    virtual std::string toString() = 0;
};
#endif

#ifdef __cplusplus
extern "C" {
#endif

struct mystr
#ifdef __cplusplus
: public mystr_base
#endif
{
    const char* data;

#ifdef __cplusplus
    std::string toString() {
        return std::string(data);
    }
#endif
};

#ifdef __cplusplus
}
#endif
</code>```

This may not be exactly pretty, but will do for the example. In a real scenario, the C and C++ variants may be in separate headers, with the C++ struct extending a POD struct. Regardless of implementation, the issue of alignment is still present.

With this example, if a C program was written that passes an instance of mystr to a C++ function, the vtable will interfere with the alignment:

test.h:

```<code>#include "mystr.h"

#ifdef __cplusplus
extern "C"
#endif
void mycxxfunc(struct mystr str);
</code>```

test.cpp:

```<code>#include <stdio.h>
#include "test.h"

void mycxxfunc(mystr str) {
    printf("mystr: %s\n", str.data);
}
</code>```

main.c:

```<code>#include "test.h"

int main(int argc, char** argv) {
    const char* testString = "abc123";
    struct mystr str;
    str.data = testString;
    mycxxfunc(str);
}

$ g++ -c test.cpp && gcc main.c test.o
$ ./a.out
Segmentation fault (core dumped)
</code>```

(presuming that this is because the C++ function is attempting to read data from beyond the end of the struct's allocated memory)

What's the best way to enable this C-C++ interoperability while still retaining the ability to use virtual functions in C++?

答:
I do not recommend you to clutter your header file with #ifdefs.

The first thing you should do in this case if you want to retain some kind of virtualization and C compatibility at the same time is:

Make your C++ and C type an opaque pointer to the representation.

Put implementation details in a .cpp file.

An idea follows.

Header file:

```<code>struct MyStrImpl;

struct MyStr {
   MyStrImpl * impl;
};

extern "C" MyReturnType myFunction(MyStr myStr);
</code>```

Implementation in .cpp file:

```<code>struct MyCppString {
    virtual ...
};

#ifdef __cplusplus
struct MyStrImpl : public MyCppString {

};
#else
struct MyStrImpl {

};
#endif
MyStr::MyStr() : impl{new MyStrImpl{}} {

}
</code>```

This way you have a type that can be used from both C and C++.

Advantages:

No #ifdef in header file.

Compatible with C/C++ and consumable from both languages.

Disadvantages:

Lose overloading due to extern "C".

Must use a C-style interface (but can implement with C++-like with virtual functions interface in your .cpp file.

You cannot have both a C-compatible type and virtual functions in a header file at the same time without cluttering it with #ifdef, something that I do not recommend since it can be inconvenient if you need to refactor code.

Body:
In questions such as this, compatibility between C++ classes/structs and C structs is explained as possible as long as all members are of the same type, in the same order, and no virtual members are declared.

That's my problem. I have virtual methods, and I would very much like to keep them when manipulating the struct in C++.

Let's examine this toy example. It's meant to be a C and C++ compatible struct defined in a single header file.

mystr.h:

#ifdef __cplusplus
#include <string>
struct mystr_base {
    virtual ~mystr_base() {}

    virtual std::string toString() = 0;
};
#endif

#ifdef __cplusplus
extern "C" {
#endif

struct mystr
#ifdef __cplusplus
: public mystr_base
#endif
{
    const char* data;

#ifdef __cplusplus
    std::string toString() {
        return std::string(data);
    }
#endif
};

#ifdef __cplusplus
}
#endif

This may not be exactly pretty, but will do for the example. In a real scenario, the C and C++ variants may be in separate headers, with the C++ struct extending a POD struct. Regardless of implementation, the issue of alignment is still present.

With this example, if a C program was written that passes an instance of mystr to a C++ function, the vtable will interfere with the alignment:

test.h:

#include "mystr.h"

#ifdef __cplusplus
extern "C"
#endif
void mycxxfunc(struct mystr str);

test.cpp:

#include <stdio.h>
#include "test.h"

void mycxxfunc(mystr str) {
    printf("mystr: %s\n", str.data);
}

main.c:

#include "test.h"

int main(int argc, char** argv) {
    const char* testString = "abc123";
    struct mystr str;
    str.data = testString;
    mycxxfunc(str);
}

$ g++ -c test.cpp && gcc main.c test.o
$ ./a.out
Segmentation fault (core dumped)

(presuming that this is because the C++ function is attempting to read data from beyond the end of the struct's allocated memory)

What's the best way to enable this C-C++ interoperability while still retaining the ability to use virtual functions in C++?

Body:
I do not recommend you to clutter your header file with #ifdefs.

The first thing you should do in this case if you want to retain some kind of virtualization and C compatibility at the same time is:

Make your C++ and C type an opaque pointer to the representation.

Put implementation details in a .cpp file.

An idea follows.

Header file:

struct MyStrImpl;

struct MyStr {
   MyStrImpl * impl;
};

extern "C" MyReturnType myFunction(MyStr myStr);

Implementation in .cpp file:

struct MyCppString {
    virtual ...
};

#ifdef __cplusplus
struct MyStrImpl : public MyCppString {

};
#else
struct MyStrImpl {

};
#endif
MyStr::MyStr() : impl{new MyStrImpl{}} {

}

This way you have a type that can be used from both C and C++.

Advantages:

No #ifdef in header file.

Compatible with C/C++ and consumable from both languages.

Disadvantages:

Lose overloading due to extern "C".

Must use a C-style interface (but can implement with C++-like with virtual functions interface in your .cpp file.

You cannot have both a C-compatible type and virtual functions in a header file at the same time without cluttering it with #ifdef, something that I do not recommend since it can be inconvenient if you need to refactor code.


问:
Event Macro Throws an Error "Object Required"
I have this simple Event Macro, which for some reason throws me an

Object Required

error on this line If Not AppDate Is Nothing Then. Any idea what might be causing this?

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim LastRow As Integer
    Dim ThisRow As String
    Dim AppDate As Variant
    Application.EnableEvents = False

    LastRow = Cells(Rows.Count, "C").End(xlUp).Row
    If Target.Column = 3 Then
        ThisRow = Target.Row
        AppDate = Target.Value
        If Not AppDate Is Nothing Then
            (...) Recalculate Date in Column F
        Else
        End If
    End If

    Application.EnableEvents = True
End Sub
</code>```

Any suggestions would be greatly appreciated. Thank you!

答:
Use:

```<code>…
If Not IsEmpty(AppDate)
…
</code>```

To help clarify, here is a lengthy tutorial about Nothing.  lol

Body:
I have this simple Event Macro, which for some reason throws me an

Object Required

error on this line If Not AppDate Is Nothing Then. Any idea what might be causing this?

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim LastRow As Integer
    Dim ThisRow As String
    Dim AppDate As Variant
    Application.EnableEvents = False

    LastRow = Cells(Rows.Count, "C").End(xlUp).Row
    If Target.Column = 3 Then
        ThisRow = Target.Row
        AppDate = Target.Value
        If Not AppDate Is Nothing Then
            (...) Recalculate Date in Column F
        Else
        End If
    End If

    Application.EnableEvents = True
End Sub

Any suggestions would be greatly appreciated. Thank you!

Body:
Use:

…
If Not IsEmpty(AppDate)
…

To help clarify, here is a lengthy tutorial about Nothing.  lol


问:
How can you get indexes of visible rows for an NSOutlineView?
How can you get a indexes of visible rows for an NSOutlineView?
I need to know which level and which rows are visible.

[EDIT]
What I'm actually looking for is an NSOutlineView equivalent to CocoaTouch/UITableView - (NSArray *)indexPathsForVisibleRows

答: NSOutlineView is an NSTableView subclass. Therefore -rowsInRect: can be combined with -visibleRect (from NSView). Use -levelForRow: to determine the level.


问:
Laravel Backpack Admin CRUD Views returning 404
I had this working on a local dev environment, but now that I'm pushing it live I'm running into an error:

When I try to access my CRUD pages (/admin/images or similar), I get taken to my websites 404 page.

I uploaded the /routes/admin.php file, all my resource files, controllers, models, vendor files, public/vendor files, and probably some others I'm forgetting to mention.

Not sure if theres something in the config files for backpack I need to edit or what. Looking for some direction.

Note: I am able to access the default routes from Backpack (dashboard, login, logout)

RouteServiceProvider.php

```<code>protected function mapWebRoutes()
{
    Route::middleware('web')
         ->namespace($this->namespace)
         ->group(base_path('routes/web.php'));
}

protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

protected function mapAdminRoutes()
{
    Route::middleware(['web', 'admin'])
         ->prefix('admin') // or use the prefix from CRUD config
         ->namespace($this->namespace.'\Admin')
         ->group(base_path('routes/admin.php'));
}
</code>```

Found this error in the error logs:

exception 'Illuminate\Database\Eloquent\RelationNotFoundException'
  with message 'Call to undefined relationship [wheels] on model
  [App\Models\WheelFinishes].' in
  laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:20

But I have the relationship defined in my WheelFinishes model

```<code>namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class WheelFinishes extends Model
{
    use CrudTrait;

    public function wheels()
    {
        return $this->belongsTo('App\Models\Wheels', 'wheel_id');
    }

    ...
}
</code>```

Wheels Model

```<code>namespace App\Models;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
use App\User;

class Wheels extends Model
{
use CrudTrait;

protected $table = "wheels";
protected $primaryKey = 'id';

...

public function tips()
{
    return $this->hasMany('App\Models\WheelTips', 'wheel_id');
}

public function finishes()
{
    return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}

public function factoryFinishes()
{
    return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->where('factory_finish', '=', '1')->orderBy('order');
}

public function wheelImages()
{
    return $this->hasMany('App\Models\WheelImages', 'wheel_id');
}

public function wheelImage()
{
    return $this->hasOne('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}

public function profile()
{
    return $this->BelongsTo('App\Models\Profile');
}

public function series()
{
    return $this->BelongsTo('App\Models\Series');
}

public function vehicles()
{
    return $this->hasMany('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order')->take(3);
}

public function vehicle()
{
    return $this->hasOne('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}
</code>```

}

routes.php

```<code><?php

// Backpack\CRUD: Define the resources for the entities you want to CRUD.
CRUD::resource('video', 'VideoCrudController');
CRUD::resource('wheels', 'WheelCrudController');
Route::get('finishes/ajax-finishes-options', 'FinishCrudController@wheelsOptions');
CRUD::resource('finishes', 'FinishCrudController');
Route::get('albums/ajax-albums-options', 'AlbumCrudController@albumsOptions');
CRUD::resource('albums', 'AlbumCrudController');
CRUD::resource('heros', 'HeroCrudController');
</code>```

答:
If you have a separate route file you probably need to register it in RouteServiceProvider:</p>

```<code>    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
        require base_path('routes/admin.php');
    });
</code>```

Body:
I had this working on a local dev environment, but now that I'm pushing it live I'm running into an error:

When I try to access my CRUD pages (/admin/images or similar), I get taken to my websites 404 page.

I uploaded the /routes/admin.php file, all my resource files, controllers, models, vendor files, public/vendor files, and probably some others I'm forgetting to mention.

Not sure if theres something in the config files for backpack I need to edit or what. Looking for some direction.

Note: I am able to access the default routes from Backpack (dashboard, login, logout)

RouteServiceProvider.php

protected function mapWebRoutes()
{
    Route::middleware('web')
         ->namespace($this->namespace)
         ->group(base_path('routes/web.php'));
}

protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

protected function mapAdminRoutes()
{
    Route::middleware(['web', 'admin'])
         ->prefix('admin') // or use the prefix from CRUD config
         ->namespace($this->namespace.'\Admin')
         ->group(base_path('routes/admin.php'));
}

Found this error in the error logs:

exception 'Illuminate\Database\Eloquent\RelationNotFoundException'
  with message 'Call to undefined relationship [wheels] on model
  [App\Models\WheelFinishes].' in
  laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:20

But I have the relationship defined in my WheelFinishes model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class WheelFinishes extends Model
{
    use CrudTrait;

    public function wheels()
    {
        return $this->belongsTo('App\Models\Wheels', 'wheel_id');
    }

    ...
}

Wheels Model

namespace App\Models;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
use App\User;

class Wheels extends Model
{
use CrudTrait;

protected $table = "wheels";
protected $primaryKey = 'id';

...

public function tips()
{
    return $this->hasMany('App\Models\WheelTips', 'wheel_id');
}

public function finishes()
{
    return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}

public function factoryFinishes()
{
    return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->where('factory_finish', '=', '1')->orderBy('order');
}

public function wheelImages()
{
    return $this->hasMany('App\Models\WheelImages', 'wheel_id');
}

public function wheelImage()
{
    return $this->hasOne('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}

public function profile()
{
    return $this->BelongsTo('App\Models\Profile');
}

public function series()
{
    return $this->BelongsTo('App\Models\Series');
}

public function vehicles()
{
    return $this->hasMany('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order')->take(3);
}

public function vehicle()
{
    return $this->hasOne('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}

}

routes.php

<?php

// Backpack\CRUD: Define the resources for the entities you want to CRUD.
CRUD::resource('video', 'VideoCrudController');
CRUD::resource('wheels', 'WheelCrudController');
Route::get('finishes/ajax-finishes-options', 'FinishCrudController@wheelsOptions');
CRUD::resource('finishes', 'FinishCrudController');
Route::get('albums/ajax-albums-options', 'AlbumCrudController@albumsOptions');
CRUD::resource('albums', 'AlbumCrudController');
CRUD::resource('heros', 'HeroCrudController');

Body:
If you have a separate route file you probably need to register it in RouteServiceProvider:

    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
        require base_path('routes/admin.php');
    });


问:
Error implementing Vimeo-networking
I have tried many different ways of getting Vimeo networking into my app, but nothing has worked. If I remove the implementation it works just fine so I know this is the issue.
compile 'com.vimeo.networking:vimeo-networking:1.1.1'

gives me this error

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  > java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

I have searched all over and have yet to find a solution (yes I have tried cleaning and rebuilding the project)

答:
SOLUTION: anthonycr's answer was perfect, but I also had to do this:</p>

```<code>implementation ("org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version") {
    exclude group: 'org.jetbrains', module: 'annotations'
}

implementation ('com.vimeo.networking:vimeo-networking:1.1.1') {
    exclude group: 'org.jetbrains', module: 'annotations'
}
</code>```

Title: Error implementing Vimeo-networking

Body:
SOLUTION: anthonycr's answer was perfect, but I also had to do this:

implementation ("org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version") {
    exclude group: 'org.jetbrains', module: 'annotations'
}

implementation ('com.vimeo.networking:vimeo-networking:1.1.1') {
    exclude group: 'org.jetbrains', module: 'annotations'
}


问:
How to get subtraction between next and prev values in PHP array
I have got array with data like this:

```<code>$array = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25];
</code>```

What I want to get is array of absolute subtraction values between next value and prev:

```<code>[0.0-0.19, 0.19-0.5, 0.5-0.75, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25]
</code>```

Result should be an array with absolute values like:

```<code>$result = [0.19, 0.31, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25];
</code>```

Maybe there's any native function or good looking solution?

Body:
I have got array with data like this:

$array = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25];

What I want to get is array of absolute subtraction values between next value and prev:

[0.0-0.19, 0.19-0.5, 0.5-0.75, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25]

Result should be an array with absolute values like:

$result = [0.19, 0.31, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25];

Maybe there's any native function or good looking solution?

Body:
Try iterating like this:

$array = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25];

$result = [];
for ($i = 1; $i < count($array); $i++) {
    $result[] = abs($array[$i - 1] - $array[$i]);
}


问:
enum as parameter in c function
I am writing a Library to load and save ascii and binary images. I defined an Enum containing 4 different flags for 4 different ways to save a bitmap:

```<code>enum jmpr_PNMMode
{
    BINARY_PPM,             /* Binary Portable Pixmap (P6)  */
    ASCII_PPM,          /* Portable pixmap ASCII (P3)   */
    BINARY_PGM,         /* Portable Graymap binary (P5) */
    ASCII_PGM            /* Portable Graymap ASCII (P2) */
};
</code>```

I pass those to my save-function as a parameter:

```<code>void jmpr_savePNM(char* filename, jmpr_Image* img, enum jmpr_PNMMode mode)
{

}
</code>```

Now how can I check which distinct instance of the enum I got? it doesn't work with:

```<code>if (strcmp(mode, "ASCII_PPM") != 0)
</code>```

since the second parameter is technically not a char*.

答:
enums are not strings, so you should not use strcmp. They are basically integers under the hood.  You need to change your if statement to...

```<code>if (ASCII_PPM == mode)
</code>```

or you can use switch statement, E.g.

```<code>switch (mode)
{
    case ASCII_PPM:
        ProcessAsciiPpm();
        break;

    case BINARY_PPM:
        ProcessBinaryPpm();
        break;

    default:
        break;
}
</code>```

Title: enum as parameter in c function

Body:
I am writing a Library to load and save ascii and binary images. I defined an Enum containing 4 different flags for 4 different ways to save a bitmap:

enum jmpr_PNMMode
{
    BINARY_PPM,             /* Binary Portable Pixmap (P6)  */
    ASCII_PPM,          /* Portable pixmap ASCII (P3)   */
    BINARY_PGM,         /* Portable Graymap binary (P5) */
    ASCII_PGM            /* Portable Graymap ASCII (P2) */
};

I pass those to my save-function as a parameter:

void jmpr_savePNM(char* filename, jmpr_Image* img, enum jmpr_PNMMode mode)
{

}

Now how can I check which distinct instance of the enum I got? it doesn't work with:

if (strcmp(mode, "ASCII_PPM") != 0)

since the second parameter is technically not a char*.

Body:
enums are not strings, so you should not use strcmp. They are basically integers under the hood.  You need to change your if statement to...

if (ASCII_PPM == mode)

or you can use switch statement, E.g.

switch (mode)
{
    case ASCII_PPM:
        ProcessAsciiPpm();
        break;

    case BINARY_PPM:
        ProcessBinaryPpm();
        break;

    default:
        break;
}


问:
SVN commands does not appear in context menu
I've just downloaded and installed SVN Tortoise, but no commands appear on the menu.
How is that possible?</p>

答:
It can be fixed by repairing TortoiseSVN and immediate re-booting the OS. Make sure that your are using the correct version for your OS ( 32bit || 64 bit).

I faced the same problem with Window Server 2003 R2 when I upgraded to TortoiseSVN to version
TortoiseSVN-1.6.12.20536-win32-svn-1.6.15. Now it's solved.

OwnerDisplayName: sdfgdfg


问:
Laravel 5.5 - Only log 500 error, never send error details via api?
I made the below controller to demonstrate the issue of handling 500 errors I am having with the api. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

```<code>class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}
</code>```

This is what the client sees:

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

答:
You have app/Exception/Handler.php class to do this. For example you can use code similar to this:

```<code>public function render($request, Exception $e)
{
    $exception_class = get_class($e);

    if (!in_array($exception_class, [ValidationException::class, ModelNotFoundException::class] ) {
       return response()->json(['info' => 'Error occurred'], 500);
    }

   return parent::render();
}
</code>```

but as you see you should exclude some exception classes that you would like to be rendered in normal way, here are only some sample exception classes.

Obviously in case you are designing API probably there is no point to use parent::render() at all and you should handle custom exception classes in custom way and then finally for other exceptions just return 500 response with the message you want.

Body:
I made the below controller to demonstrate the issue of handling 500 errors I am having with the api. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}

This is what the client sees:

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

Body:
You have app/Exception/Handler.php class to do this. For example you can use code similar to this:

public function render($request, Exception $e)
{
    $exception_class = get_class($e);

    if (!in_array($exception_class, [ValidationException::class, ModelNotFoundException::class] ) {
       return response()->json(['info' => 'Error occurred'], 500);
    }

   return parent::render();
}

but as you see you should exclude some exception classes that you would like to be rendered in normal way, here are only some sample exception classes.

Obviously in case you are designing API probably there is no point to use parent::render() at all and you should handle custom exception classes in custom way and then finally for other exceptions just return 500 response with the message you want.


问:
Get dataset value from input tag upon click and display as HTML
I would like to get the value from the data-price dataset in the radio button after the user has clicked a different option and display it below in the label tag.  I am doing something wrong.  Any help would be very much appreciated.

Here is my code:

(function (){
    var radios_price = document.getElementById('lbl-011');
    console.log(radios_price.dataset.price);
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = this.value;
        }
    }
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

<p>Price (data-price):<label id="priceLabel"> $39</label></code>```

答:
You can't have an id assigned to more than one element. Lots of tutorials always put a descriptive text as both id and name attribute, and in the case of radio buttons you do need them all to have the same name, but the id must be unique to an element.

(function (){
    document.querySelectorAll('#lbl-011 input').forEach((inp) => {
      inp.onclick = function () {
        document.getElementById('priceLabel').innerText = "$" + this.dataset.price;
      };
    });
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="lbl-011">
  <input class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

  <input class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

  <input class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">
</div>

<p>Price (data-price): <span id="priceLabel">$39</span></code>```

I also turned the  into a  and move the whitespace outside of it.

Body:
I would like to get the value from the data-price dataset in the radio button after the user has clicked a different option and display it below in the label tag.  I am doing something wrong.  Any help would be very much appreciated.

Here is my code:

(function (){
    var radios_price = document.getElementById('lbl-011');
    console.log(radios_price.dataset.price);
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = this.value;
        }
    }
})();

<input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

Price (data-price): $39

Body:
You can't have an id assigned to more than one element. Lots of tutorials always put a descriptive text as both id and name attribute, and in the case of radio buttons you do need them all to have the same name, but the id must be unique to an element.

(function (){
    document.querySelectorAll('#lbl-011 input').forEach((inp) => {
      inp.onclick = function () {
        document.getElementById('priceLabel').innerText = "$" + this.dataset.price;
      };
    });
})();

<div id="lbl-011">
  <input class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

  <input class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

  <input class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">
</div>

<p>Price (data-price): <span id="priceLabel">$39</span>

I also turned the <label> into a <span> and move the whitespace outside of it.


问:
Spring v3 no declaration can be found for element 'mvc:resources'

Currently Running

Tomcat: v6

Spring Tools Suite: v2.7.2

Spring Framework: spring-webmvc-3.0.5

Servlet XML

```<code> <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/mvc/spring-mvc
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd">

      <mvc:annotation-driven />

      <mvc:resources mapping="/resources/**" location="/resources" />

      <context:component-scan base-package="com.app.mvc" />

 </beans>
</code>```

web.xml partial code

```<code><servlet-mapping>
    <servlet-name>duckapp</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

Servlet Purpose

web.xml maps all urls to the servlet with the exception of mvc:resources mapping static files.

Bugs

cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:annotation-driven'.    app-servlet.xml /app/www/WEB-INF

cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:resources'.    app-servlet.xml /app/www/WEB-INF

Known Issues

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd doesn't contain the element resource

If replaced by http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd still doesn't work and may not be working according to jar files of spring 3.05

mvc:resources appeared in spring v3.0.4, but has no new xsd

Question

How can I fix the compile errors to get mvc:resources working correctly?

I've been digging around 2 hours for this, no solid answer yet...

答:
I have enroled for spring course on udemy. I followed every step that my instructor show me to do.
So if you are using spring mvc and hibernate you may encounter this error
Failed to read schema document 'http://www.springframework.org/schema/tx/spring-tx.xsd' etc for:

```<code><mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" /> elements
</code>```

in my spring configuration file i had these two urls

```<code>    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
</code>```

in xsi:schemaLocation, which i replaced with

```<code>    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
</code>```

actually i visited these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd

So, in my opinion specifying version no explicitly is a good practice.
It worked for me, hope this works for you too.
Thank you.

Body:
Currently Running

Tomcat: v6

Spring Tools Suite: v2.7.2

Spring Framework: spring-webmvc-3.0.5

Servlet XML

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/mvc/spring-mvc
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd">

      <mvc:annotation-driven />

      <mvc:resources mapping="/resources/**" location="/resources" />

      <context:component-scan base-package="com.app.mvc" />

 </beans>

web.xml partial code

<servlet-mapping>
    <servlet-name>duckapp</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Servlet Purpose

web.xml maps all urls to the servlet with the exception of mvc:resources mapping static files.

Bugs

cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:annotation-driven'.    app-servlet.xml /app/www/WEB-INF

cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:resources'.    app-servlet.xml /app/www/WEB-INF

Known Issues

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd doesn't contain the element resource

If replaced by http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd still doesn't work and may not be working according to jar files of spring 3.05

mvc:resources appeared in spring v3.0.4, but has no new xsd

Question

How can I fix the compile errors to get mvc:resources working correctly?

I've been digging around 2 hours for this, no solid answer yet...

Body:
I have enroled for spring course on udemy. I followed every step that my instructor show me to do.
So if you are using spring mvc and hibernate you may encounter this error
Failed to read schema document 'http://www.springframework.org/schema/tx/spring-tx.xsd' etc for:

<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" /> elements

in my spring configuration file i had these two urls

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd

in xsi:schemaLocation, which i replaced with

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

actually i visited these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd

So, in my opinion specifying version no explicitly is a good practice.
It worked for me, hope this works for you too.
Thank you.


问:
Use a template to get a value and assign a substring of that value to the attribute
I need to apply a substring to the value that is returned from calling a template.
This is a working example:

```<code>        <xsl:attribute name="sportname">
            <xsl:call-template name="sport-mapping">
                <xsl:with-param name="prodParam" select="Sport" />
            </xsl:call-template>
        </xsl:attribute>
</code>```

Let's imagine that sportname gets the value "goal". I only want the first two characters from the start, so I will apply a substring similar to this

```<code>select="substring(<STRING-TO-MANIPULTE>,2,2)
</code>```

Can you help me achieve this behaviour?
Thanks

答:
Put the results of the call-template in a variable...</p>

```<code>   <xsl:attribute name="sportname">
      <xsl:variable name="results">
         <xsl:call-template name="sport-mapping">
            <xsl:with-param name="prodParam" select="Sport" />
         </xsl:call-template>
      </xsl:variable>
      <xsl:value-of select="substring($results,1,2)" />
   </xsl:attribute>
</code>```

Body:
I need to apply a substring to the value that is returned from calling a template.
This is a working example:

        <xsl:attribute name="sportname">
            <xsl:call-template name="sport-mapping">
                <xsl:with-param name="prodParam" select="Sport" />
            </xsl:call-template>
        </xsl:attribute>

Let's imagine that sportname gets the value "goal". I only want the first two characters from the start, so I will apply a substring similar to this

select="substring(<STRING-TO-MANIPULTE>,2,2)

Can you help me achieve this behaviour?
Thanks

Body:
Put the results of the call-template in a variable...

   <xsl:attribute name="sportname">
      <xsl:variable name="results">
         <xsl:call-template name="sport-mapping">
            <xsl:with-param name="prodParam" select="Sport" />
         </xsl:call-template>
      </xsl:variable>
      <xsl:value-of select="substring($results,1,2)" />
   </xsl:attribute>


问:
Xamarin project -- implement interface on iOS 11 only
I am working on a Xamarin app. I want a certain object to implement the interface IUIDropInteractionDelegate if and only if the app is running on an iOS 11 device. On iOS 10 or earlier, the interface is not available. The app also supports iOS 10. How do I do that?</p>

答:
There are answers on dealing with new features and backward compatibility here.

Regarding Xamarin, it's worth to try out IntroducedAttribute class.

```<code>[Introduced(PlatformName.iOS, 11, 0)]
</code>```

You probably see it a lot while creating binding library. Class reference could be found here.

Body:
There are answers on dealing with new features and backward compatibility here.

Regarding Xamarin, it's worth to try out IntroducedAttribute class.

[Introduced(PlatformName.iOS, 11, 0)]

You probably see it a lot while creating binding library. Class reference could be found here.


问:
Get values from an array of objects
I am looping through my array to get the corresponding field value:

```<code>var someFun = function (nm) {
    var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];

    for (var i=0; i < names.length; i++) {
        if (names[i].name === nm) return names[i].age;
    }
};

var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)
</code>```

How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.

答:
From Array.prototype.find()

The find() method returns the value of the first element in the array
  that satisfies the provided testing function.

If there are multiples objects with the same name?

With Array.prototype.filter()

var names = [{
    name: 'joe',
    age: 9
  },
  {
    name: 'tom',
    age: 10
  },
  {
    name: 'frank',
    age: 9
  },
  {
    name: 'joe',
    age: 15
  }
];

function getData(arr, search) {
  // Filter array of objects by a search pair
  return arr.filter(o => o[search[0]] === search[1]);
}

function listBy(arr, k) {
  // Output values from an array of objects by a key as a comma separated string
  return arr.map(o => o[k]).join(",");
}

console.log(getData(names, ["name", "joe"]));
console.log(listBy(getData(names, ["name", "tom"]), "age"));
console.log(listBy(getData(names, ["age", 9]), "name"));```

Title: Get values from an array of objects

Body:
I am looping through my array to get the corresponding field value:

var someFun = function (nm) {
    var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];

    for (var i=0; i < names.length; i++) {
        if (names[i].name === nm) return names[i].age;
    }
};

var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)

How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.


问:
hijri to gregorian date, why 30/02/1436 doesn't exist in SQL?
I have being confused as SQL cannot convert (Saudi Arabian dates) Hijra to Gregorian calendar as cannot convert the 30/02/1436.

2nd month is called Safar. Does Safar has 30 or 29 days?

Tank you for your time,
Regards,

答:
PS: Safar in year 1436 only had 29 days

Does this work for you?

CONVERT date format 130 and 131 are for Hijri datetimes

```<code>DECLARE @DateTimeNow DATETIME = GETUTCDATE() ;
-- Get Gregorian UTC datetime
SELECT @DateTimeNow --2017-11-15 17:10:52.110

-- Get Hijri datetime
SELECT CONVERT(nchar, @DateTimeNow, 131) --26/02/1439  5:10:52:110PM

--Convert back again
SELECT CONVERT(datetime, CONVERT(nchar, @DateTimeNow, 131), 131) --2017-11-15 17:10:52.110
</code>```

Body:
PS: Safar in year 1436 only had 29 days

Does this work for you?

CONVERT date format 130 and 131 are for Hijri datetimes

DECLARE @DateTimeNow DATETIME = GETUTCDATE() ;
-- Get Gregorian UTC datetime
SELECT @DateTimeNow --2017-11-15 17:10:52.110

-- Get Hijri datetime
SELECT CONVERT(nchar, @DateTimeNow, 131) --26/02/1439  5:10:52:110PM

--Convert back again
SELECT CONVERT(datetime, CONVERT(nchar, @DateTimeNow, 131), 131) --2017-11-15 17:10:52.110


问:
valgrind reports memory leak in gsoap
Valgrind is detecting some memory leaks in Gsoap. This is a very basic example code:

```<code>//file hr.cpp
#include "soapH.h"
#include "ns1.nsmap"

int main()
{
    struct soap *soap_ = soap_new();

    soap_destroy(soap_);
    soap_end(soap_);
    //soap_done(soap_);
    soap_free(soap_);

    return 0;
}
</code>```

To compile this code, I use this :

```<code>g++ -D DEBUG -g -std=c++0x -o hr hr.cpp soapC.cpp stdsoap2.cpp
</code>```

And these are the memory leaks reported by Valgrind:

```<code>==5290== HEAP SUMMARY:
==5290==     in use at exit: 72,800 bytes in 4 blocks
==5290==   total heap usage: 18 allocs, 14 frees, 244,486 bytes allocated
==5290==
==5290== 32 bytes in 1 blocks are definitely lost in loss record 1 of 4
==5290==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5290==    by 0x41D6FF: soap_track_malloc (stdsoap2.cpp:8952)
==5290==    by 0x421347: soap_set_logfile (stdsoap2.cpp:10022)
==5290==    by 0x421402: soap_set_test_logfile (stdsoap2.cpp:10062)
==5290==    by 0x422391: soap_init_REQUIRE_lib_v20851 (stdsoap2.cpp:10405)
==5290==    by 0x43DD31: soap::soap() (stdsoap2.cpp:20074)
==5290==    by 0x41AF2E: soap_new_REQUIRE_lib_v20851 (stdsoap2.cpp:8109)
==5290==    by 0x40238C: main (hr.cpp:6)
==5290==
==5290== 32 bytes in 1 blocks are definitely lost in loss record 2 of 4
==5290==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5290==    by 0x41D6FF: soap_track_malloc (stdsoap2.cpp:8952)
==5290==    by 0x421347: soap_set_logfile (stdsoap2.cpp:10022)
==5290==    by 0x4213DA: soap_set_sent_logfile (stdsoap2.cpp:10050)
==5290==    by 0x4223A2: soap_init_REQUIRE_lib_v20851 (stdsoap2.cpp:10406)
==5290==    by 0x43DD31: soap::soap() (stdsoap2.cpp:20074)
==5290==    by 0x41AF2E: soap_new_REQUIRE_lib_v20851 (stdsoap2.cpp:8109)
==5290==    by 0x40238C: main (hr.cpp:6)
==5290==
==5290== 32 bytes in 1 blocks are definitely lost in loss record 3 of 4
==5290==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5290==    by 0x41D6FF: soap_track_malloc (stdsoap2.cpp:8952)
==5290==    by 0x421347: soap_set_logfile (stdsoap2.cpp:10022)
==5290==    by 0x4213B2: soap_set_recv_logfile (stdsoap2.cpp:10038)
==5290==    by 0x4223B3: soap_init_REQUIRE_lib_v20851 (stdsoap2.cpp:10407)
==5290==    by 0x43DD31: soap::soap() (stdsoap2.cpp:20074)
==5290==    by 0x41AF2E: soap_new_REQUIRE_lib_v20851 (stdsoap2.cpp:8109)
==5290==    by 0x40238C: main (hr.cpp:6)
==5290==
==5290== LEAK SUMMARY:
==5290==    definitely lost: 96 bytes in 3 blocks
==5290==    indirectly lost: 0 bytes in 0 blocks
==5290==      possibly lost: 0 bytes in 0 blocks
==5290==    still reachable: 72,704 bytes in 1 blocks
==5290==         suppressed: 0 bytes in 0 blocks
==5290== Reachable blocks (those to which a pointer was found) are not shown.
==5290== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==5290==
==5290== For counts of detected and suppressed errors, rerun with: -v
==5290== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
</code>```

What am I doing wrong?
Am I missing any instruction? I have read through gsoap documentation and internet but I did not found anything.

Thanks a lot!

答:
Do not compile your code with -DDEBUG to test with valgrind, because it activates gSOAP's internal memory leak checker. This may interfere with valgrind.

EDIT:

I verified this with the latest release 2.8.61 which shows no leak in DEBUG mode or otherwise. I suggest to upgrade to gSOAP 2.8.61.

Title: valgrind reports memory leak in gsoap

Body:
Valgrind is detecting some memory leaks in Gsoap. This is a very basic example code:

//file hr.cpp
#include "soapH.h"
#include "ns1.nsmap"

int main()
{
    struct soap *soap_ = soap_new();

    soap_destroy(soap_);
    soap_end(soap_);
    //soap_done(soap_);
    soap_free(soap_);

    return 0;
}

To compile this code, I use this :

g++ -D DEBUG -g -std=c++0x -o hr hr.cpp soapC.cpp stdsoap2.cpp

And these are the memory leaks reported by Valgrind:

==5290== HEAP SUMMARY:
==5290==     in use at exit: 72,800 bytes in 4 blocks
==5290==   total heap usage: 18 allocs, 14 frees, 244,486 bytes allocated
==5290==
==5290== 32 bytes in 1 blocks are definitely lost in loss record 1 of 4
==5290==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5290==    by 0x41D6FF: soap_track_malloc (stdsoap2.cpp:8952)
==5290==    by 0x421347: soap_set_logfile (stdsoap2.cpp:10022)
==5290==    by 0x421402: soap_set_test_logfile (stdsoap2.cpp:10062)
==5290==    by 0x422391: soap_init_REQUIRE_lib_v20851 (stdsoap2.cpp:10405)
==5290==    by 0x43DD31: soap::soap() (stdsoap2.cpp:20074)
==5290==    by 0x41AF2E: soap_new_REQUIRE_lib_v20851 (stdsoap2.cpp:8109)
==5290==    by 0x40238C: main (hr.cpp:6)
==5290==
==5290== 32 bytes in 1 blocks are definitely lost in loss record 2 of 4
==5290==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5290==    by 0x41D6FF: soap_track_malloc (stdsoap2.cpp:8952)
==5290==    by 0x421347: soap_set_logfile (stdsoap2.cpp:10022)
==5290==    by 0x4213DA: soap_set_sent_logfile (stdsoap2.cpp:10050)
==5290==    by 0x4223A2: soap_init_REQUIRE_lib_v20851 (stdsoap2.cpp:10406)
==5290==    by 0x43DD31: soap::soap() (stdsoap2.cpp:20074)
==5290==    by 0x41AF2E: soap_new_REQUIRE_lib_v20851 (stdsoap2.cpp:8109)
==5290==    by 0x40238C: main (hr.cpp:6)
==5290==
==5290== 32 bytes in 1 blocks are definitely lost in loss record 3 of 4
==5290==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5290==    by 0x41D6FF: soap_track_malloc (stdsoap2.cpp:8952)
==5290==    by 0x421347: soap_set_logfile (stdsoap2.cpp:10022)
==5290==    by 0x4213B2: soap_set_recv_logfile (stdsoap2.cpp:10038)
==5290==    by 0x4223B3: soap_init_REQUIRE_lib_v20851 (stdsoap2.cpp:10407)
==5290==    by 0x43DD31: soap::soap() (stdsoap2.cpp:20074)
==5290==    by 0x41AF2E: soap_new_REQUIRE_lib_v20851 (stdsoap2.cpp:8109)
==5290==    by 0x40238C: main (hr.cpp:6)
==5290==
==5290== LEAK SUMMARY:
==5290==    definitely lost: 96 bytes in 3 blocks
==5290==    indirectly lost: 0 bytes in 0 blocks
==5290==      possibly lost: 0 bytes in 0 blocks
==5290==    still reachable: 72,704 bytes in 1 blocks
==5290==         suppressed: 0 bytes in 0 blocks
==5290== Reachable blocks (those to which a pointer was found) are not shown.
==5290== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==5290==
==5290== For counts of detected and suppressed errors, rerun with: -v
==5290== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)

What am I doing wrong?
Am I missing any instruction? I have read through gsoap documentation and internet but I did not found anything.

Thanks a lot!


答:
strcmp is used for strings. enum is actually a type of int, so mode == ASCII_PPM will be the right way of comparison

6.7.2.2 Enumeration specifiers

The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted.

Title: enum as parameter in c function


问:
Adding items in Producer/Consumer pattern async using BlockingCollection
I'm following this guide on BlockingCollection to implement a Producer/Consumer pattern but still can't get my tasks to execute in parallel on the producer side.

The problem is my foreach block is executing sequentially.  From this question, I understand that I have to project the collection of PropertyLien<T> as Tasks.  How is that done?

```<code>// PropertyLien<T> is a class that models an asset (house/building/etc)
var googleAddresses = new BlockingCollection<Tuple<PropertyLien<string>, IEnumerable<GoogleAddress>>>()

// Consumer Threads
var consumer = Task.Run(() => {
    while(!googleAddresses.IsCompleted) {
        var adr = googleAddresses.Take();
        // Do work
    }

    Console.WriteLine("No more addresses to process");
});

// Producer Threads
var producer = Task.Factory.StartNew(async () => {
    // TODO: PROBLEM here, this is executing synchronously
    foreach(PropertyLien<string> property in properties) {
        try {
            // See: https://www.nuget.org/packages/Geocoding.net/
            await geocoder.GeocodeAsync(property.Address)
                .ContinueWith(task => {
                    var googResults = task.Result;
                    googleAddresses.Add(property, googResults);
                });
        }
        catch {}
    }
    googleAddresses.CompleteAdding();
});

// Need to wait for both tasks to complete.
Task.WaitAll(producer, consumer);
</code>```

答:
Thanks to @Evk, this is the answer:</p>

```<code>// Producer Threads
var producer = Task.Factory.StartNew(async () => {
    var tasks = properties.Select(property => {
        return geocoder.GeocodeAsync(property.Address)
            .ContinueWith(task => {
                // Do work
            });
    });

    await Task.WhenAll(tasks);
    googleAddresses.CompleteAdding();
});
</code>```

Body:
I'm following this guide on BlockingCollection to implement a Producer/Consumer pattern but still can't get my tasks to execute in parallel on the producer side.

The problem is my foreach block is executing sequentially.  From this question, I understand that I have to project the collection of PropertyLien<T> as Tasks.  How is that done?

// PropertyLien<T> is a class that models an asset (house/building/etc)
var googleAddresses = new BlockingCollection<Tuple<PropertyLien<string>, IEnumerable<GoogleAddress>>>()

// Consumer Threads
var consumer = Task.Run(() => {
    while(!googleAddresses.IsCompleted) {
        var adr = googleAddresses.Take();
        // Do work
    }

    Console.WriteLine("No more addresses to process");
});

// Producer Threads
var producer = Task.Factory.StartNew(async () => {
    // TODO: PROBLEM here, this is executing synchronously
    foreach(PropertyLien<string> property in properties) {
        try {
            // See: https://www.nuget.org/packages/Geocoding.net/
            await geocoder.GeocodeAsync(property.Address)
                .ContinueWith(task => {
                    var googResults = task.Result;
                    googleAddresses.Add(property, googResults);
                });
        }
        catch {}
    }
    googleAddresses.CompleteAdding();
});

// Need to wait for both tasks to complete.
Task.WaitAll(producer, consumer);

Body:
Thanks to @Evk, this is the answer:

// Producer Threads
var producer = Task.Factory.StartNew(async () => {
    var tasks = properties.Select(property => {
        return geocoder.GeocodeAsync(property.Address)
            .ContinueWith(task => {
                // Do work
            });
    });

    await Task.WhenAll(tasks);
    googleAddresses.CompleteAdding();
});


答:
You can use try ... catch

```<code>try{
   .....
}catch(\Exception $e){
  if($e->getCode() == 500){
      return response()->json(["error"=>'$e->getCode()'],500);
  }
}
</code>```

Title: Laravel 5.5 - Only log 500 error, never send error details via api?

Body:
You can use try ... catch

try{
   .....
}catch(\Exception $e){
  if($e->getCode() == 500){
      return response()->json(["error"=>'$e->getCode()'],500);
  }
}


问:
Array Of Number And Finding SubArray
Input = 5 4 5 5 6 7 8 8 8 7 6

In This Input, The longest subarray is [6, 10] where maximum=8 and minimum are 7 and difference is 1. Difference Should be Less And Equal To 1.

a subarray such that the difference between the minimum and the maximum value in that range is at most 1

Output Should Be 7 8 8 8 7
Please Suggest Me How To Code?

```<code>#THIS IS MY CODE
n = int(input())
data = []

for _ in range(n):
    data.append(int(input()))

for i in range(0,n):
    maxi = max(data[i+1:])
    mini = min(data[i+1:])
    diff = maxi - mini

    if diff <= 1:
       print(data[i:])
       l = len(data[i:])
       print(l)
       break
</code>```

答:
Here is a naive solution. Make every possible sub-list and filter out those that meet your condition.

```<code>import numpy as np
a = [5,4,5,5,6,7,8,8,8,7,6]
max_diff = 1
sub_arrays = [x for x in [a[i:j] for i in range(len(a)) for j in range(i+1, len(a))] if (max(x)-min(x) <= max_diff)]
max_sub_array = sub_arrays[np.argmax([len(sa) for sa in sub_arrays])]
</code>```

On your sample input, the output is:

```<code>[7, 8, 8, 8, 7]
</code>```

Title: Array Of Number And Finding SubArray

Body:
Input = 5 4 5 5 6 7 8 8 8 7 6

In This Input, The longest subarray is [6, 10] where maximum=8 and minimum are 7 and difference is 1. Difference Should be Less And Equal To 1.

a subarray such that the difference between the minimum and the maximum value in that range is at most 1

Output Should Be 7 8 8 8 7
Please Suggest Me How To Code?

#THIS IS MY CODE
n = int(input())
data = []

for _ in range(n):
    data.append(int(input()))

for i in range(0,n):
    maxi = max(data[i+1:])
    mini = min(data[i+1:])
    diff = maxi - mini

    if diff <= 1:
       print(data[i:])
       l = len(data[i:])
       print(l)
       break

Body:
Here is a naive solution. Make every possible sub-list and filter out those that meet your condition.

import numpy as np
a = [5,4,5,5,6,7,8,8,8,7,6]
max_diff = 1
sub_arrays = [x for x in [a[i:j] for i in range(len(a)) for j in range(i+1, len(a))] if (max(x)-min(x) <= max_diff)]
max_sub_array = sub_arrays[np.argmax([len(sa) for sa in sub_arrays])]

On your sample input, the output is:

[7, 8, 8, 8, 7]


问:
React componentWillReceiveProps check not working if API responds too quick
I have a React container component which on page load dispatches an action (using the componentDidMount lifecycle method). The action calls an API, a successful API call results in the data being added to my Redux store via a reducer.

I have some other API's which require data from the response of the initial  API call. I have these in the componentWillReceiveProps lifecycle method and I'm comparing this.props against nextProps to work out whether I have the data ready to call the API's.

90% of the time this code works and the API calls inside of componentWillReceiveProps are successfully called, but the other 10% of the API's don't get called because the code inside of the if statement which compares this.props to nextProps doesn't execute.

From testing I think I've found the issue... If the initial API call returns fast enough, the very first time componentWillReceiveProps is called this.props is already populated with data from the API call rather than returning my initial state, at which point the if statement doesn't execute.

What is the best way of bulletproofing this?

```<code><Route
  path={'Content/:id'}
  component={DrillPage}
/>

class DrillPage extends Component {
  componentDidMount() {
    this.props.actions.getLoggedInUser();
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props);
    console.log(nextProps);

    // Don't fire if user isn't logged in
    if (this.props.loggedInUser.id !== nextProps.loggedInUser.id) {
      this.props.actions.isFavourite(this.props.content.id, this.props.content.type);
      this.props.actions.doIFollow([this.props.content.author.id]);
    }
  }
}

function mapStateToProps(state, ownProps) {
  return {
    contentId: ownProps.params.id,
    loggedInUser: state.loggedInUser,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Object.assign({}, contentActions, userActions), dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(DrillPage);
</code>```

答: Maybe you can try a solution without using the React lifecycle and handle your logic in your sagas since, as I understand you're using componentWillReceiveProps to fire other API calls only if you have a userId

Body:
I have a React container component which on page load dispatches an action (using the componentDidMount lifecycle method). The action calls an API, a successful API call results in the data being added to my Redux store via a reducer.

I have some other API's which require data from the response of the initial  API call. I have these in the componentWillReceiveProps lifecycle method and I'm comparing this.props against nextProps to work out whether I have the data ready to call the API's.

90% of the time this code works and the API calls inside of componentWillReceiveProps are successfully called, but the other 10% of the API's don't get called because the code inside of the if statement which compares this.props to nextProps doesn't execute.

From testing I think I've found the issue... If the initial API call returns fast enough, the very first time componentWillReceiveProps is called this.props is already populated with data from the API call rather than returning my initial state, at which point the if statement doesn't execute.

What is the best way of bulletproofing this?

<Route
  path={'Content/:id'}
  component={DrillPage}
/>

class DrillPage extends Component {
  componentDidMount() {
    this.props.actions.getLoggedInUser();
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props);
    console.log(nextProps);

    // Don't fire if user isn't logged in
    if (this.props.loggedInUser.id !== nextProps.loggedInUser.id) {
      this.props.actions.isFavourite(this.props.content.id, this.props.content.type);
      this.props.actions.doIFollow([this.props.content.author.id]);
    }
  }
}

function mapStateToProps(state, ownProps) {
  return {
    contentId: ownProps.params.id,
    loggedInUser: state.loggedInUser,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Object.assign({}, contentActions, userActions), dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(DrillPage);


问:
How do I style an embded PowerBI dashboard?
I have managed to embed a PowerBi Dashboard into a webpage.

Unfortunately, it looks hideous. For example, the padding is ridiculous; The title is stuck in the top-left corner, which I'd like to remove; all the content is loaded into an iFrame, which if I do not set the height and width, makes the dashboard near-invisible and non-responsive (in terms of window scaling); nothing is centred...

I have tried overriding the CSS. For example, I tried to set the display: none !important; property on the header (to remove the title), but it has no effect. I also tried changing the background color of the iFrame from grey to match the color of the webpage, but that too did not work.

Does anyone know how I can style my PowerBI dashboard and embed it without an iFrame (is this even possible?)?

答:
As far as I know, at the moment, it's not possible to embed anything from PowerBI to a web page without an IFrame.

Do you really need a dashboard, maybe a report would do it? At least you'd be able to place the components as you like.


问:
Struct data assignment error: closure cannot implicitly capture a mutating self parameter
I'm trying to get a json thanks to the computed properties of "struct" and it gives error: Closure can not implicitly capture a mutating self parameter</p>

```<code>struct getData: Encodable, Decodable {
    var dataAPI: ItemsStruct

    init(url: String!) {
        let task = URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, error) in
            guard let data = data else { return }
            do {
                // Convert the data to JSON
                let jsonSerialized = try? JSONDecoder().decode(ItemsStruct.self, from: data)

                self.dataAPI = jsonSerialized!   <--error: closure cannot implicitly capture a mutating self parameter

            }
        }
        task.resume()
    }
}
</code>```

答:
Just to explain why you have this error.
You have a structure called getData. As you may know a struct is value type passed and not a referenced type as a class.

Meaning that if you change your data model through a function in a structure basically you are changing the structure itself. Here in your init in your closure, you are changing dataAPI which is part of your data model for your struct. That's the meaning of a mutating self parameter. The compiler knows that you are changing the structure by mutating dataAPI parameter.

If you want to keep as a struct, I recommand you to create a mutating func where you initialize your dataAPI variable.

Body:
I'm trying to get a json thanks to the computed properties of "struct" and it gives error: Closure can not implicitly capture a mutating self parameter

struct getData: Encodable, Decodable {
    var dataAPI: ItemsStruct

    init(url: String!) {
        let task = URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, error) in
            guard let data = data else { return }
            do {
                // Convert the data to JSON
                let jsonSerialized = try? JSONDecoder().decode(ItemsStruct.self, from: data)

                self.dataAPI = jsonSerialized!   <--error: closure cannot implicitly capture a mutating self parameter

            }
        }
        task.resume()
    }
}


问:
How to change zsh-autosuggestions color
I am new at zsh.

I've installed the plugin zsh-autosuggestions in oh-my-zsh using instruction mentioned here. I am using Linux (Fedora 26).

What my problem is I want to change the color of the text which comes in suggestion because the current one is not visible in Solarized dark color scheme.

It is visible in light theme

And it works fine as I can pick the current suggestion by pressing → key.

My question is that how can I change this suggested text color?
I read here that there is a constant ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE, but I am unable to locate that nither in ~/.zshrc file nor in $ZSH_CUSTOM/plugins/zsh-autosuggestions directory.

Can anyone tell me where can I find that and how can I change that? Also please suggest the color which will be suitable for both dark and light theme.

Also please correct if I am going wrong.

Regards.

答:
You can edit your ~/.zshrc and change/add the variable: ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=value'

I have just tested the value from fg=8 to fg=5. I think fg stands for Foreground.

ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=5'

**OBS: Add the above line at the end of your zshrc (after loading the plugin) **

I have found another reference here.

Title: How to change zsh-autosuggestions color

ContentLicense: CC BY-SA 4.0


问:
Azure LocalCache not setting the Ready environment variable on ASE
I have moved my WebApp to the Azure App Service Environment and have enabled the new LocalCache option as documented at https://azure.microsoft.com/en-us/documentation/articles/app-service-local-cache/

However, the environment variable that is supposed to tell you that the cache is ready does not exist.

If I use Kudo and go to Process Explorer, Click on properties for the w3wp (without the scm label) process, then click on Environment Variables the only variables I see are:

```<code>WEBSITE_LOCAL_CACHE_OPTION  Always
APPSETTING_WEBSITE_LOCAL_CACHE_OPTION   Always
WEBSITE_LOCAL_CACHE_SIZEINMB    1000
APPSETTING_WEBSITE_LOCAL_CACHE_SIZEINMB 1000
WEBSITE_LOCALCACHE_ENABLED  True
</code>```

But not the one I need:

```<code>WEBSITE_LOCALCACHE_READY
</code>```

I am stuck as to what is happening; can anyone give any ideas for me to try?

答:
The correct answer here is this:

As the documentation you referenced mentioned:

How can I tell if my site has switched to using Local Cache?

If you're using the Local Cache feature with Staging Environments, the swap operation does not complete until Local Cache is warmed up. To check if your site is running against Local Cache, you can check the worker process environment variable WEBSITE_LOCALCACHE_READY. Use the instructions on the worker process environment variable page to access the worker process environment variable on multiple instances.

You stated:
If I use Kudo and go to Process Explorer, Click on properties for the w3wp (without the scm label) process, then click on Environment Variables the only variables I see are:

WEBSITE_LOCAL_CACHE_OPTION  Always

APPSETTING_WEBSITE_LOCAL_CACHE_OPTION   Always

WEBSITE_LOCAL_CACHE_SIZEINMB    1000

APPSETTING_WEBSITE_LOCAL_CACHE_SIZEINMB 1000

WEBSITE_LOCALCACHE_ENABLED  True

This environment variable WEBSITE_LOCALCACHE_READY is part of the "Worker Process", not the host process w3wp.exe

You need to get a memory dump of the worker process as outlined here:
https://github.com/projectkudu/kudu/wiki/Process-Threads-list-and-minidump-gcdump-diagsession#process-environment-variable

Start with:

GET /api/processes/0 => detail process information of scm site's w3wp.exe.
Or use -1 for main site.
https://(kudu-site).scm.azurewebsites.net/api/processes/0
(Shows the w3wp.exe process)

The "main site" is the worker process.
https://(kudu-site).scm.azurewebsites.net/api/processes/-1

This shows a full process dump, in the contents you will see your variable:
"WEBSITE_LOCALCACHE_ENABLED":"True","WEBSITE_LOCALCACHE_READY":"TRUE"

I have this running in an ASEv2 as well, so I don't think the comment earlier from cory-fowler that this isn't supported in an ASE is correct.  Maybe it was when he wrote it, but currently it is supported.

Body:
I have moved my WebApp to the Azure App Service Environment and have enabled the new LocalCache option as documented at https://azure.microsoft.com/en-us/documentation/articles/app-service-local-cache/

However, the environment variable that is supposed to tell you that the cache is ready does not exist.

If I use Kudo and go to Process Explorer, Click on properties for the w3wp (without the scm label) process, then click on Environment Variables the only variables I see are:

WEBSITE_LOCAL_CACHE_OPTION  Always
APPSETTING_WEBSITE_LOCAL_CACHE_OPTION   Always
WEBSITE_LOCAL_CACHE_SIZEINMB    1000
APPSETTING_WEBSITE_LOCAL_CACHE_SIZEINMB 1000
WEBSITE_LOCALCACHE_ENABLED  True

But not the one I need:

WEBSITE_LOCALCACHE_READY

I am stuck as to what is happening; can anyone give any ideas for me to try?