问:
how to enforce Monotonic Constraints in XGBoost with ScikitLearn?
I build up a XGBoost model using scikit-learn and I am pretty happy with it. As fine tuning to avoid overfitting, I'd like to ensure monotonicity of some features but there I start facing some difficulties...

As far as I understood, there is no documentation in scikit-learn about xgboost (which I confess I am really surprised about - knowing that this situation is lasting for several months). The only documentation I found is directly on http://xgboost.readthedocs.io

On this website, I found out that monotonicity can be enforced using "monotone_constraints" option.
I tried to use it in Scikit-Learn but I got an error message "TypeError: init() got an unexpected keyword argument 'monotone_constraints'"

Do you know a way to do it ?

Here is the code I wrote in python (using spyder):

```<code>grid = {'learning_rate' : 0.01, 'subsample' : 0.5, 'colsample_bytree' : 0.5,
    'max_depth' : 6, 'min_child_weight' : 10, 'gamma' : 1,
    'monotone_constraints' : monotonic_indexes}
#'monotone_constraints' ~ = "(1,-1)"
m07_xgm06 = xgb.XGBClassifier(n_estimators=2000, **grid)
m07_xgm06.fit(X_train_v01_oe, Label_train, early_stopping_rounds=10, eval_metric="logloss",
    eval_set=[(X_test1_v01_oe, Label_test1)])
</code>```

答:
How would you expect monotone constraints to work for a general classification problem where the response might have more than 2 levels? All the examples I've seen relating to this functionality are for regression problems. If your classification response only has 2 levels, try switching to regression on an indicator variable and then choose an appropriate score threshold for classification.

This feature appears to work as of the latest xgboost / scikit-learn, provided that you use an XGBregressor rather than an XGBclassifier and set monotone_constraints via kwargs.

The syntax is like this:

```<code>params = {
    'monotone_constraints':'(-1,0,1)'
}

normalised_weighted_poisson_model = XGBRegressor(**params)
</code>```

In this example, there is a negative constraint on column 1 in the training data, no constraint on column 2, and a positive constraint on column 3. It is up to you to keep track of which is which - you cannot refer to columns by name, only by position, and you must specify an entry in the constraint tuple for every column in your training data.

Body:
I build up a XGBoost model using scikit-learn and I am pretty happy with it. As fine tuning to avoid overfitting, I'd like to ensure monotonicity of some features but there I start facing some difficulties...

As far as I understood, there is no documentation in scikit-learn about xgboost (which I confess I am really surprised about - knowing that this situation is lasting for several months). The only documentation I found is directly on http://xgboost.readthedocs.io

On this website, I found out that monotonicity can be enforced using "monotone_constraints" option.
I tried to use it in Scikit-Learn but I got an error message "TypeError: init() got an unexpected keyword argument 'monotone_constraints'"

Do you know a way to do it ?

Here is the code I wrote in python (using spyder):

grid = {'learning_rate' : 0.01, 'subsample' : 0.5, 'colsample_bytree' : 0.5,
    'max_depth' : 6, 'min_child_weight' : 10, 'gamma' : 1,
    'monotone_constraints' : monotonic_indexes}
#'monotone_constraints' ~ = "(1,-1)"
m07_xgm06 = xgb.XGBClassifier(n_estimators=2000, **grid)
m07_xgm06.fit(X_train_v01_oe, Label_train, early_stopping_rounds=10, eval_metric="logloss",
    eval_set=[(X_test1_v01_oe, Label_test1)])

Body:
How would you expect monotone constraints to work for a general classification problem where the response might have more than 2 levels? All the examples I've seen relating to this functionality are for regression problems. If your classification response only has 2 levels, try switching to regression on an indicator variable and then choose an appropriate score threshold for classification.

This feature appears to work as of the latest xgboost / scikit-learn, provided that you use an XGBregressor rather than an XGBclassifier and set monotone_constraints via kwargs.

The syntax is like this:

params = {
    'monotone_constraints':'(-1,0,1)'
}

normalised_weighted_poisson_model = XGBRegressor(**params)

In this example, there is a negative constraint on column 1 in the training data, no constraint on column 2, and a positive constraint on column 3. It is up to you to keep track of which is which - you cannot refer to columns by name, only by position, and you must specify an entry in the constraint tuple for every column in your training data.


来源: stackexchange

问:
How to only run tests not having a certain tag in scala using flatspec through sbt?
As a scala beginner, I want to tag the integration tests in order to exclude them from running in certain scenarios (as they can be quite slow and might break due to external changes/problems).

I created the tag integration this way:

```<code>import org.scalatest.{FlatSpec, Matchers, Tag}
object integration extends Tag("com.dreamlines.tags.integration")
</code>```

In my test I tag a test like so:

```<code>class SchemaValidation extends FlatSpec with Matchers {
  it should "return valid json" taggedAs (integration) in {
    ...
    assertSchema(response, endpointSchema)
  }
}
</code>```

Yet when reading up on how to filter certain tests based on the tag in the docs, I get highly confused as suddenly I read that I should be using  org.scalatest.tools.Runner

```<code>scala [-cp scalatest-<version>.jar:...] org.scalatest.tools.Runner [arguments]
</code>```

which has the flags I am looking for:

-l  specifies a tag to exclude (Note: only one tag name allowed per -l) -l SlowTests -l PerfTests

Yet I am only used to run my tests via:

```<code>sbt test
</code>```

I have no idea what the scala test runner here is referring to or what goes on under the hood when I run sbt test. I am truly lost.

I was expecting to execute the tests not entirely unlike this:

```<code>sbt test --ignore-tag integration
</code>```

答:
According to the sbt documentation on test options the following should work for you:

```<code>testOnly -- -l integration
</code>```

Or in case ScalaTest uses the fully qualified tag id:

```<code>testOnly -- -l com.dreamlines.tags.integration
</code>```

In case you want to do this by default, you can adjust the testOptions in the build.sbt file.

Edit:

You might consider a different approach for integration test. Instead of tagging them, you might want to put them in the src/it/{scala|resources} folders.

ContentLicense: CC BY-SA 3.0

Body:
As a scala beginner, I want to tag the integration tests in order to exclude them from running in certain scenarios (as they can be quite slow and might break due to external changes/problems).

I created the tag integration this way:

import org.scalatest.{FlatSpec, Matchers, Tag}
object integration extends Tag("com.dreamlines.tags.integration")

In my test I tag a test like so:

class SchemaValidation extends FlatSpec with Matchers {
  it should "return valid json" taggedAs (integration) in {
    ...
    assertSchema(response, endpointSchema)
  }
}

Yet when reading up on how to filter certain tests based on the tag in the docs, I get highly confused as suddenly I read that I should be using  org.scalatest.tools.Runner

scala [-cp scalatest-<version>.jar:...] org.scalatest.tools.Runner [arguments]

which has the flags I am looking for:

-l  specifies a tag to exclude (Note: only one tag name allowed per -l) -l SlowTests -l PerfTests

Yet I am only used to run my tests via:

sbt test

I have no idea what the scala test runner here is referring to or what goes on under the hood when I run sbt test. I am truly lost.

I was expecting to execute the tests not entirely unlike this:

sbt test --ignore-tag integration

Body:
According to the sbt documentation on test options the following should work for you:

testOnly -- -l integration

Or in case ScalaTest uses the fully qualified tag id:

testOnly -- -l com.dreamlines.tags.integration

In case you want to do this by default, you can adjust the testOptions in the build.sbt file.

Edit:

You might consider a different approach for integration test. Instead of tagging them, you might want to put them in the src/it/{scala|resources} folders.


问:
Firebase. Change `username`(email) of registered user
My iOS application uses Firebase login by username and password. But I would like to give a possibility to change the username in settings.

The question is, does Firebase support changing a username?

Update

username means email

答:
If you want to change the displayName you can use this code:

```<code>let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = "DoesData"
changeRequest?.commitChanges { (error) in
  // ...
}
</code>```

If you want to change the email address you can use:

```<code>currentUser?.updateEmail(email) { error in
    if let error = error {
        print(error)
    }
    else {
        // Email updated
    }
}
</code>```

I know you have to reauthenticate if you update a users password, but I'm not sure if you need to do that for email changes as well.
This code can help with authentication:

```<code>let credential = FIREmailPasswordAuthProvider.credentialWithEmail(email, password: password)
let currentUser = FIRAuth.auth()?.currentUser

currentUser?.reauthenticateWithCredential(credential) { error in
   if let error = error {
       // An error happened.
   } else {
      // User re-authenticated.
   }
}
</code>```

You may also want to look at documentation, this question, and this question

Body:
If you want to change the displayName you can use this code:

let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = "DoesData"
changeRequest?.commitChanges { (error) in
  // ...
}

If you want to change the email address you can use:

currentUser?.updateEmail(email) { error in
    if let error = error {
        print(error)
    }
    else {
        // Email updated
    }
}

I know you have to reauthenticate if you update a users password, but I'm not sure if you need to do that for email changes as well.
This code can help with authentication:

let credential = FIREmailPasswordAuthProvider.credentialWithEmail(email, password: password)
let currentUser = FIRAuth.auth()?.currentUser

currentUser?.reauthenticateWithCredential(credential) { error in
   if let error = error {
       // An error happened.
   } else {
      // User re-authenticated.
   }
}

You may also want to look at documentation, this question, and this question


问:
the firebase getToken() function
Do you need to register the user first in order to use the getIdToken() Javascript function?
Can someone give an example of how to use this function and where.
I have my index.html and in it I have included:

```<code> https://www.gstatic.com/firebasejs/4.6.2/firebase.js`.
</code>```

I have this code:-

```<code> firebase.auth().currentUser.getToken(true).then(function(idToken) {
 alert(idToken);
 }).catch(function (error) {
 });
</code>```

but this gives me

currentUser is null error.

答:
If you don't want to get user credentials but still want to distinguish them,
you can take a look at Anonymous Authentication.

```<code>firebase.auth().signInAnonymously();
</code>```

is enough to log an user in.

Title: the firebase getToken() function

Body:
Do you need to register the user first in order to use the getIdToken() Javascript function?
Can someone give an example of how to use this function and where.
I have my index.html and in it I have included:

 https://www.gstatic.com/firebasejs/4.6.2/firebase.js`.

I have this code:-

 firebase.auth().currentUser.getToken(true).then(function(idToken) {
 alert(idToken);
 }).catch(function (error) {
 });

but this gives me

currentUser is null error.

Body:
If you don't want to get user credentials but still want to distinguish them,
you can take a look at Anonymous Authentication.

firebase.auth().signInAnonymously();

is enough to log an user in.


问:
Create HTML5 Canvas programmatically
I have the following HTML code snippets

```<code><body onload="main()" >
    ...
    <canvas id="myId" class="myClass"></canvas>
    ...
</body>
</code>```

It works as expected. I can display the output correctly.

I then remove

```<code><canvas id="myId" class="myClass"></canvas>
</code>```

Because I want to create it programmatically with the following JavaScript code snippet

```<code>var canvas = document.createElement("canvas");
canvas.className  = "myClass";
canvas.id = "myId";
</code>```

Unfortunately, it didn't work. I cannot display anything with this.

I am wondering if I miss something. Any help is appreciated.
Thanks in advance for your help.

答:
You need to insert the new <canvas> element into the DOM. To put it at the end of the body, use:

```<code>document.body.appendChild(canvas);
</code>```

with the code that creates it. (If you want to put it inside a different element, use that instead of document.body.)

ContentLicense: CC BY-SA 2.5

Title: Create HTML5 Canvas programmatically

Body:
I have the following HTML code snippets

    ...
    <canvas id="myId" class="myClass"></canvas>
    ...

It works as expected. I can display the output correctly.

I then remove

<canvas id="myId" class="myClass"></canvas>

Because I want to create it programmatically with the following JavaScript code snippet

var canvas = document.createElement("canvas");
canvas.className  = "myClass";
canvas.id = "myId";

Unfortunately, it didn't work. I cannot display anything with this.

I am wondering if I miss something. Any help is appreciated.
Thanks in advance for your help.

Body:
You need to insert the new <canvas> element into the DOM. To put it at the end of the body, use:

document.body.appendChild(canvas);

with the code that creates it. (If you want to put it inside a different element, use that instead of document.body.)


问:
How to write a generic method that takes any java object and convert it into a json string
I was writing some ajax controllers for my spring mvc based application. Now in a single class, I have three methods for three separate ajax call handlers with same root url (That is why I placed them inside a single class). Now in each of the controller I have to return a Json(stringified) and I am using Object Mapper to achieve it. But when I saw that the all three methods look exactly similar apart from the argument type, it struck me that whether there is way to make the code more elegant.

Methods called by ajax controllers

```<code>private String translateGetABCResponseToString(ABC response) {
        try {
            return mapper.writeValueAsString(response);
        } catch (JsonProcessingException ex) {
            throw new ValidationException(ex);
        }
    }

private String translateGetDEFResponseToString(DEF response) {
            try {
                return mapper.writeValueAsString(response);
            } catch (JsonProcessingException ex) {
                throw new ValidationException(ex);
            }
        }

private String translateGetXYZResponseToString(XYZ response) {
            try {
                return mapper.writeValueAsString(response);
            } catch (JsonProcessingException ex) {
                throw new ValidationException(ex);
            }
        }
</code>```

Now, What I want is that is there a way to make a single method as all three methods are essentially doing the same thing.

答:
Just use Object:

```<code>private String translateObjectToString(Object obj) {
    try {
        return mapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new ValidationException(ex);
    }
}
</code>```

Mapper doesn't care what you give it. It will all work just fine.

Body:
I was writing some ajax controllers for my spring mvc based application. Now in a single class, I have three methods for three separate ajax call handlers with same root url (That is why I placed them inside a single class). Now in each of the controller I have to return a Json(stringified) and I am using Object Mapper to achieve it. But when I saw that the all three methods look exactly similar apart from the argument type, it struck me that whether there is way to make the code more elegant.

Methods called by ajax controllers

private String translateGetABCResponseToString(ABC response) {
        try {
            return mapper.writeValueAsString(response);
        } catch (JsonProcessingException ex) {
            throw new ValidationException(ex);
        }
    }

private String translateGetDEFResponseToString(DEF response) {
            try {
                return mapper.writeValueAsString(response);
            } catch (JsonProcessingException ex) {
                throw new ValidationException(ex);
            }
        }

private String translateGetXYZResponseToString(XYZ response) {
            try {
                return mapper.writeValueAsString(response);
            } catch (JsonProcessingException ex) {
                throw new ValidationException(ex);
            }
        }

Now, What I want is that is there a way to make a single method as all three methods are essentially doing the same thing.

Body:
Just use Object:

private String translateObjectToString(Object obj) {
    try {
        return mapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new ValidationException(ex);
    }
}

Mapper doesn't care what you give it. It will all work just fine.


问:
Ionic 2, use google maps in ion-segments
I have a slight problem. Google maps is not showing in ionic 2 segments but showing outside of segments. I am using the following code,

```<code> <div [ngSwitch]="report_details">
    <div *ngSwitchCase="'details'">
        <div #map id="map"></div>
    </div>
 </div>
</code>```

I have tried the following solutions but did not work:

use height and width of 100% on outer div.

use timeout on map load function.

答:
I had the same problem as you point out, Google Maps is showing perfectly outside segments. So following the approach suggested by biranchi125 in Ionic forum you can place the map outside the segments and handle when to show it whith the selection variable, like this:

```<code><div [ngSwitch]="report_details">
  <div *ngSwitchCase="'details'">
    <!-- you can place other elements here if you want -->
  </div>
  <div [style.display]="report_details == 'details' ? 'block' : 'none'">
     <div #map id="map"></div>
  </div>
</div>
</code>```

and it works : )

Body:
I have a slight problem. Google maps is not showing in ionic 2 segments but showing outside of segments. I am using the following code,

I have tried the following solutions but did not work:

use height and width of 100% on outer div.

use timeout on map load function.

Body:
I had the same problem as you point out, Google Maps is showing perfectly outside segments. So following the approach suggested by biranchi125 in Ionic forum you can place the map outside the segments and handle when to show it whith the selection variable, like this:

<div [ngSwitch]="report_details">
  <div *ngSwitchCase="'details'">
    <!-- you can place other elements here if you want -->
  </div>
  <div [style.display]="report_details == 'details' ? 'block' : 'none'">
     <div #map id="map"></div>
  </div>
</div>

and it works : )


问:
Handling async situations in an .NET MVC application
I wanted to get some basic .NET MVC understanding so I started working on a very simple application that is somewhat similar to Yelp.  It consists of a User object and Business object.  A user can add businesses to their "watch list" and when someone creates a review for that business the application would look through a table of "user id-business id" relations and email the users that are watching that business for new reviews (so that they can respond to them).

In my ReviewsController, I have a Create action that creates a review.  Before that action returns, I would like to run a method that checks if there are any watches for the business the review was just created for.

This is where I get stuck because I'm not sure what would be a good way of doing this in MVC setting(?).

What I do know is that the user who is creating the review does not need to wait for the application to look through the "user-business" relation table.

Would it be a good idea to create this lookup functionality as an async method? I also looked into events but seems like events are not ideal in MVC setting. Are there any well-established patters in MVC world for situations like these?

答:
Another way of doing it, is to use ajax in View. Ajax is designed to be async, therefore, it is suitable for your use.

Whenever the post review button is clicked, an ajax request is sent to server to perform the CheckWatches action in parallel.

Here is a link to a simple example of an ajax call:

Making a Simple Ajax call to controller in asp.net mvc


答:
You need to actually attach the canvas to the document. Before you do so, it's just a detached element that the browser does not render.</p>

```<code>var canvas = /* ... */;
/* ... */
document.getElementsByTagName('body')[0].appendChild(canvas);
</code>```

Title: Create HTML5 Canvas programmatically

Body:
You need to actually attach the canvas to the document. Before you do so, it's just a detached element that the browser does not render.

var canvas = /* ... */;
/* ... */
document.getElementsByTagName('body')[0].appendChild(canvas);


问:
the server responded with a status of 404 (Not Found) Failed to load resource
I am facing issue in accessing public folder of laravel.

I am on ubuntu 17.10.

I am trying to run the app on localhost.

I am accessing like this:

```<code><img src="{{URL::asset('public/assets/img/person.jpg')}}"/>
</code>```

Also when checking the its source , its path is shown correct :

It may seem duplicate but I've tried most of the solutions present on net.

答:
You shoud use Storage::get() to retrive the file url. See the docs

anyway, you don't need that public in the path:

Switch

```<code><img src="{{URL::asset('public/assets/img/person.jpg')}}"/>
</code>```

to

```<code><img src="{{URL::asset('assets/img/person.jpg')}}"/>
</code>```

Body:
I am facing issue in accessing public folder of laravel.

I am on ubuntu 17.10.

I am trying to run the app on localhost.

I am accessing like this:

Also when checking the its source , its path is shown correct :

It may seem duplicate but I've tried most of the solutions present on net.

Body:
You shoud use Storage::get() to retrive the file url. See the docs

anyway, you don't need that public in the path:

Switch

<img src="{{URL::asset('public/assets/img/person.jpg')}}"/>

to

<img src="{{URL::asset('assets/img/person.jpg')}}"/>


问:
Why predict is not delivering the expected result?
```<code>data <- data.frame(day_type = c("weekend", "weekend", "weekend","weekend",
                                "weekday", "weekday", "weekday", "weekday"),
                   vehicle = c("car", "car", "car", "car",
                               "bus", "bus", "bus", "bus"))

library(naivebayes)

model <- naive_bayes(vehicle ~ day_type, data = data)

predict(model, data.frame(day_type = "weekend"))
    [1] bus
Levels: bus car
</code>```

<p>Expected answer should be car here, but I am getting bus as answer. Please help to identify the error. </p>

答:
This will help you understand the issue:

```<code>data <- data.frame(day_type = c("weekend", "weekend", "weekend","weekend",
                                "weekday", "weekday", "weekday", "weekday"),
                   vehicle = c("car", "car", "car", "car",
                               "bus", "bus", "bus", "bus"))

library(naivebayes)

model <- naive_bayes(vehicle ~ day_type, data = data)

dt_test1 = data.frame(day_type = "weekend")
dt_test2 = data.frame(day_type = "weekday")
dt_test3 = data.frame(day_type = c("weekend","weekday"))

predict(model, newdata = dt_test1)

# [1] bus
# Levels: bus car

predict(model, newdata = dt_test2)

# [1] bus
# Levels: bus car

predict(model, newdata = dt_test3)

# [1] car bus
# Levels: bus car
</code>```

Test datasets 1 and 2 have 1 level and they assign the value 1 to "weekend" and "weekday" respectively. Then the model understands values 1 and 2 (based on what you have in your original dataset data) and doesn't care about the labels (weekday/weekend).
However, in test dataset 3 you have two labels and they get the correct values (wwekend/weekday -> 1/2).

As an extreme case scenario check this:

```<code>dt_test4 = data.frame(day_type = c("January","February"))

predict(model, newdata = dt_test4)

# [1] car bus
# Levels: bus car
</code>```

You will still get predictions! Because those values, that the model doesn't even understand, are coded to 1 and 2.

Therefore, as @Aaron suggested, make sure you make sure the factor levels match, or use character variables instead of factor variables.

Body:
data <- data.frame(day_type = c("weekend", "weekend", "weekend","weekend",
                                "weekday", "weekday", "weekday", "weekday"),
                   vehicle = c("car", "car", "car", "car",
                               "bus", "bus", "bus", "bus"))

library(naivebayes)

model <- naive_bayes(vehicle ~ day_type, data = data)

predict(model, data.frame(day_type = "weekend"))
    [1] bus
Levels: bus car

Expected answer should be car here, but I am getting bus as answer. Please help to identify the error.

Body:
This will help you understand the issue:

data <- data.frame(day_type = c("weekend", "weekend", "weekend","weekend",
                                "weekday", "weekday", "weekday", "weekday"),
                   vehicle = c("car", "car", "car", "car",
                               "bus", "bus", "bus", "bus"))

library(naivebayes)

model <- naive_bayes(vehicle ~ day_type, data = data)

dt_test1 = data.frame(day_type = "weekend")
dt_test2 = data.frame(day_type = "weekday")
dt_test3 = data.frame(day_type = c("weekend","weekday"))

predict(model, newdata = dt_test1)

# [1] bus
# Levels: bus car

predict(model, newdata = dt_test2)

# [1] bus
# Levels: bus car

predict(model, newdata = dt_test3)

# [1] car bus
# Levels: bus car

Test datasets 1 and 2 have 1 level and they assign the value 1 to "weekend" and "weekday" respectively. Then the model understands values 1 and 2 (based on what you have in your original dataset data) and doesn't care about the labels (weekday/weekend).
However, in test dataset 3 you have two labels and they get the correct values (wwekend/weekday -> 1/2).

As an extreme case scenario check this:

dt_test4 = data.frame(day_type = c("January","February"))

predict(model, newdata = dt_test4)

# [1] car bus
# Levels: bus car

You will still get predictions! Because those values, that the model doesn't even understand, are coded to 1 and 2.

Therefore, as @Aaron suggested, make sure you make sure the factor levels match, or use character variables instead of factor variables.


问:
determining the unused Angular modules at the app.module.ts file
I've inherited an angular app that imports everything under the sun causing the vendor.bundle.js to be 8mb.

Is there a utility to let me know which modules are not in use, and can safely be removed?

Or does the AOT takes care of that?

Also, do I need to remove the node_modules folder if there is no import related to it? Or is it that it would not hurt to leave it there cause AOT won't take it anyway?

答:
As far as I know, AOT only removes code that isn't used or imported into an NgModule. And code that isn't imported anywhere (including node_modules) won't be included in the bundle. There are a few ways you can find code that isn't used.

Configure TypeScript to complain about unused imports

Using the --noUnusedLocals compiler option will cause unused imports and local variables to throw a typescript error. Most of these should already be handled by AOT but there is a chance that you'll find an unused import that AOT thought might be necessary.

Exploring The Bundle

Exploring the bundle is helpful to see what files take up the most size. It won't show you what dependencies triggered their import but it will help you prioritize.

Add the --sourceMap and --statsJson flags to your ng build.

Use webpack-bundle-analyzer to read the dist/stats.json file to see what is in your bundle

To explore the modules that were combined during the prod build, use the `source-map-explorer'

Trial and Error

While this is the least automated way of looking for unused code, the Angular compiler by default does a good job of checking to ensure that needed components are included in the bundle before you run your application. Therefore if you've done a search of your files and don't think a module is used, try removing the import and see if the CLI throws a compilation error.

ContentLicense: CC BY-SA 4.0


问:
Replacing C code macros and defining constants in C++ code

Essentials of my problem: My project consists of both C and C++ files, some string constants (they are hardcoded in C part of project with #define) are required to connect to computer via USB, but if I connect two or more of same type devices, they stop responding because those constants are same. Solution to this problem would be assigning those constants dynamically, from C++ files, so that variable from C++ code could reach C part, where those values are used.

What I have now: Values are defined in C headers as #define IDENTIFIER VALUE (hardcoded), where both VALUE is a C primitive constant an int like 0x1234 or char array like "Some string". For instance:

#define IDENTIFIER1 0x1234
#define IDENTIFIER2 0x5678
#define IDENTIFIER3 "Some string"
#define IDENTIFIER4 "Another string"
```

<p>I know that methods in C use those identifiers with other macros such as <code>LOBYTE</code> and <code>HIBYTE</code>, also values are passed to some functions.</p>

<p>I tried approaching this problem by replacing the string <code>defines</code> with <code>static cast char[]</code> variable definition wrapped in <code>#ifndef</code>, but compiler noted that the identifiers are initializing non-const variables in some functions or is passed as a parameter.</p>

<p>I successfully compiled code in which i changed defining strings from <code>#define IDENTIFIER VALUE</code> to <code>static const unsigned char IDENTIFIER[] = VALUE;</code>, but I still need to define them in C++.</p>

<p>However I struggle to define hexadecimal numbers like <code>0x1234</code>. I've found other question including something related to my problem, so far I've tried to define hexadecimal values in following ways (found out that uint8_t is just a typedef of unsigned char, also found some questions about casting numbers to <code>unsigned char</code> and some answers to questions about casting types):</p>

<pre class="lang-cpp prettyprint-override"><code>static uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = (uint8_t*)0x1234;

static const uint16_t identifier_int = 0x1234;
static const unsigned char IDENTIFIER[3] = identifier_int;
</code>```

there is a function which uses IDENTIFIERs as arguments, its prototype looks like this:

```<code>void foo (uint8_t *bar, /*other arguments*/);
</code>```

and later this is called like that:

```<code>foo(IDENTIFIER, /*other arguments*/)
</code>```

What I want to achieve: Values should be defined in C++ code, where it should use some method to pass those values to C code.

Questions:

What is best way to pass values from C++ code to C code? What alternatives there are?

Please inform me if I could increase clarity of my question!

Great thanks to @AhmedMasud for helping me out in defining my problem more clearly and giving few tips to clarify questions.

答:
Values should be defined in C++ code, where it should use some method
  to pass those values to C code and then define them.

You can certainly do that in a general sense, but making it work with your existing C code will require changes to that code.  Those changes could be distinctly non-trivial.

If I understand
  correctly macros change all places where IDENTIFIER is used to VALUE
  before compilation,

Yes, that's a reasonably good characterization.

therefore I think that macros shouldn't be used
  anymore.

I take you to mean that because you want to set values at run time, you cannot use macros.  That's quite right.  The least disruptive way to accommodate this in your C code would probably be to declare and use external variables to hold the values.  Note well, however, that there is a considerable variety of problems that you might need to solve to convert your C code to work that way.

I expect code to look something like

```<code>void setIdentifier(identifier)
{
#ifndef IDENTIFIER
static const unsigned char IDENTIFIER[] = identifier;
#endif
}
</code>```

as far as I know const should already do it.

No, it won't look much like that at all.

In the first place, you said, reasonably, that you don't want to use macros.  In that case the #ifndef IDENTIFIER and #endif have no role to play.

In the second place, you have declared variable IDENTIFIER inside a function, so it has no linkage.  You need an external variable if you want one function to set it and a different function to read it.

In the third place, since you'll need an external variable, you'll not be able to use an initializer to set its value.  If you declare the variable as a char array (as opposed to a char *), then, you'll need to use strcpy() or a similar function to copy the argument's characters into that array.  You can use simple assignment for numeric or pointer variables, however.

I don't know much about interacting with C code from C++ yet, what is best way to pass values from C++ code to C code? What
  alternatives there are?

Pretty much the same alternatives you have for passing around values inside C++ code: store the value in an accessible variable, or pass it as a function argument.  C has no "methods", but for this purpose, C++ methods can be considered a kind of function.

What precautions should I take when assigning those "constants"? I noticed that it is recommended to use static const instead of
  #define, as mentioned above using macros in this situation probably is unlikely.

The question does not make sense.  If you have a constant then you cannot assign a value to it (noting that assigning to is different from initializing).  You might use a file-scope const or static const variable if you wanted to set its value at compile time, but the macros in use already accomplish that anyway.  Why go to all the work to change?

On the other hand, you need non-const variables if you want to assign to them at runtime.  Moreover, you need external variables (non-static) if you want to assign values in one source file that will be read from a different one.

Would static const defined in C++ program be seen in C code?

At file / namespace scope, no, because preventing that is the exact purpose of static in that context.  Inside a function or method, no, because the local variables of functions / methods are not visible outside the function / method in which they are declared.  So, no.

If you want a variable to which one function or method can write and from which another function or method can read, and at least one of the functions accessing the variable is implemented in C, then you need a file-scope external variable.  Such a variable is declared to all users (both C and C++) with a file-scope declaration of this form:

```<code>/* "extern" is essential */
extern int IDENTIFIER1;
</code>```

That would normally be placed in a header file that all sources that access the variable include.  Additionally, exactly one source file in the project must define the variable, with code of this form:

```<code>/*
 * either the initializer or the absence of "extern" is essential;
 * both together is good form.
 */
int IDENTIFIER1 = 0x1234;
</code>```

Body:
Essentials of my problem: My project consists of both C and C++ files, some string constants (they are hardcoded in C part of project with #define) are required to connect to computer via USB, but if I connect two or more of same type devices, they stop responding because those constants are same. Solution to this problem would be assigning those constants dynamically, from C++ files, so that variable from C++ code could reach C part, where those values are used.

What I have now: Values are defined in C headers as #define IDENTIFIER VALUE (hardcoded), where both VALUE is a C primitive constant an int like 0x1234 or char array like "Some string". For instance:

#define IDENTIFIER1 0x1234
#define IDENTIFIER2 0x5678
#define IDENTIFIER3 "Some string"
#define IDENTIFIER4 "Another string"

I know that methods in C use those identifiers with other macros such as LOBYTE and HIBYTE, also values are passed to some functions.

I tried approaching this problem by replacing the string defines with static cast char[] variable definition wrapped in #ifndef, but compiler noted that the identifiers are initializing non-const variables in some functions or is passed as a parameter.

I successfully compiled code in which i changed defining strings from #define IDENTIFIER VALUE to static const unsigned char IDENTIFIER[] = VALUE;, but I still need to define them in C++.

However I struggle to define hexadecimal numbers like 0x1234. I've found other question including something related to my problem, so far I've tried to define hexadecimal values in following ways (found out that uint8_t is just a typedef of unsigned char, also found some questions about casting numbers to unsigned char and some answers to questions about casting types):

static uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = {0x12, 0x34, 0};

static const uint8_t IDENTIFIER[] = (uint8_t*)0x1234;

static const uint16_t identifier_int = 0x1234;
static const unsigned char IDENTIFIER[3] = identifier_int;

there is a function which uses IDENTIFIERs as arguments, its prototype looks like this:

void foo (uint8_t *bar, /*other arguments*/);

and later this is called like that:

foo(IDENTIFIER, /*other arguments*/)

What I want to achieve: Values should be defined in C++ code, where it should use some method to pass those values to C code.

Questions:

What is best way to pass values from C++ code to C code? What alternatives there are?

Please inform me if I could increase clarity of my question!

Great thanks to @AhmedMasud for helping me out in defining my problem more clearly and giving few tips to clarify questions.

Body:
Values should be defined in C++ code, where it should use some method
  to pass those values to C code and then define them.

You can certainly do that in a general sense, but making it work with your existing C code will require changes to that code.  Those changes could be distinctly non-trivial.

If I understand
  correctly macros change all places where IDENTIFIER is used to VALUE
  before compilation,

Yes, that's a reasonably good characterization.

therefore I think that macros shouldn't be used
  anymore.

I take you to mean that because you want to set values at run time, you cannot use macros.  That's quite right.  The least disruptive way to accommodate this in your C code would probably be to declare and use external variables to hold the values.  Note well, however, that there is a considerable variety of problems that you might need to solve to convert your C code to work that way.

I expect code to look something like

void setIdentifier(identifier)
{
#ifndef IDENTIFIER
static const unsigned char IDENTIFIER[] = identifier;
#endif
}

as far as I know const should already do it.

No, it won't look much like that at all.

In the first place, you said, reasonably, that you don't want to use macros.  In that case the #ifndef IDENTIFIER and #endif have no role to play.

In the second place, you have declared variable IDENTIFIER inside a function, so it has no linkage.  You need an external variable if you want one function to set it and a different function to read it.

In the third place, since you'll need an external variable, you'll not be able to use an initializer to set its value.  If you declare the variable as a char array (as opposed to a char *), then, you'll need to use strcpy() or a similar function to copy the argument's characters into that array.  You can use simple assignment for numeric or pointer variables, however.

I don't know much about interacting with C code from C++ yet, what is best way to pass values from C++ code to C code? What
  alternatives there are?

Pretty much the same alternatives you have for passing around values inside C++ code: store the value in an accessible variable, or pass it as a function argument.  C has no "methods", but for this purpose, C++ methods can be considered a kind of function.

What precautions should I take when assigning those "constants"? I noticed that it is recommended to use static const instead of
  #define, as mentioned above using macros in this situation probably is unlikely.

The question does not make sense.  If you have a constant then you cannot assign a value to it (noting that assigning to is different from initializing).  You might use a file-scope const or static const variable if you wanted to set its value at compile time, but the macros in use already accomplish that anyway.  Why go to all the work to change?

On the other hand, you need non-const variables if you want to assign to them at runtime.  Moreover, you need external variables (non-static) if you want to assign values in one source file that will be read from a different one.

Would static const defined in C++ program be seen in C code?

At file / namespace scope, no, because preventing that is the exact purpose of static in that context.  Inside a function or method, no, because the local variables of functions / methods are not visible outside the function / method in which they are declared.  So, no.

If you want a variable to which one function or method can write and from which another function or method can read, and at least one of the functions accessing the variable is implemented in C, then you need a file-scope external variable.  Such a variable is declared to all users (both C and C++) with a file-scope declaration of this form:

/* "extern" is essential */
extern int IDENTIFIER1;

That would normally be placed in a header file that all sources that access the variable include.  Additionally, exactly one source file in the project must define the variable, with code of this form:

/*
 * either the initializer or the absence of "extern" is essential;
 * both together is good form.
 */
int IDENTIFIER1 = 0x1234;


问:
WebSocket URL variable is not defined
I have this JS code, that're trying connecting to a WebSocket, but I have a problem with the URL variable.

var tipoChat = 1;
var escolherWebSocket = 1;
var unidade = prompt('Qual o IP do Provador?');
var loja = prompt('Qual o codigo da Loja?');
var url;
ws = new WebSocket(url);

// tipoChat 1 Produto
// tipoChat 2 Vendedor
// tipoChat 3 Atendente

function chatProduto() {
    tipoChat = 1;

    $("#btnProduto").addClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").removeClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function chatVendedor() {
    tipoChat = 2;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").addClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat2");
     $("#provador-produto").removeClass("show-chat1");

}

function chatAtendente() {
    tipoChat = 3;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").addClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function conectar() {
    $('#btnConectar').hide();
    $('#btnDesconectar').show();

                ws.onopen = function () {

                    $('#messages').prepend('Connected
');
                    $('#cmdSend').click(function () {

                        ws.send($('#txtMessage').val());

                        $('#txtMessage').val('');

                    });

}
}

switch (tipoChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}```
</div>
</div>
</p>

<p>And This is my error on console:</p>

<p><strong>Uncaught DOMException: Failed to construct 'WebSocket': The URL 'undefined' is invalid.</strong></p>

<p>Someone can say say why the Switch is not setting the Url variable?
It works only when I assign a value on console.</p>

<p><strong>EDIT</strong>:<br>
For some reason, when I call URL variable on console, the result is undefined, even I initializing WebSocket after switch. I really don't know why URL variable is not being defined </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var typeChat = 1;
var escolherWebSocket = 1;
var url;

switch (typeChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}

ws = new WebSocket(url);</code>```

答:
You can't initialize WebSocket with an undefined URL, like you are here:

```<code>var url;
ws = new WebSocket(url);
</code>```

You should do your switch statement before initializing new WebSocket(url).

```<code>var url;
switch (tipoChat) {
    case 1:
        url = 'foo';
}
ws = new WebSocket(url);
</code>```

Title: WebSocket URL variable is not defined

Body:
I have this JS code, that're trying connecting to a WebSocket, but I have a problem with the URL variable.

var tipoChat = 1;
var escolherWebSocket = 1;
var unidade = prompt('Qual o IP do Provador?');
var loja = prompt('Qual o codigo da Loja?');
var url;
ws = new WebSocket(url);

// tipoChat 1 Produto
// tipoChat 2 Vendedor
// tipoChat 3 Atendente

function chatProduto() {
    tipoChat = 1;

    $("#btnProduto").addClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").removeClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function chatVendedor() {
    tipoChat = 2;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").addClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat2");
     $("#provador-produto").removeClass("show-chat1");

}

function chatAtendente() {
    tipoChat = 3;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").addClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function conectar() {
    $('#btnConectar').hide();
    $('#btnDesconectar').show();

                ws.onopen = function () {

                    $('#messages').prepend('Connected
');
                    $('#cmdSend').click(function () {

                        ws.send($('#txtMessage').val());

                        $('#txtMessage').val('');

                    });

}
}

switch (tipoChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}

And This is my error on console:

Uncaught DOMException: Failed to construct 'WebSocket': The URL 'undefined' is invalid.

Someone can say say why the Switch is not setting the Url variable?
It works only when I assign a value on console.

EDIT:

For some reason, when I call URL variable on console, the result is undefined, even I initializing WebSocket after switch. I really don't know why URL variable is not being defined

var typeChat = 1;
var escolherWebSocket = 1;
var url;

switch (typeChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}

ws = new WebSocket(url);

Body:
You can't initialize WebSocket with an undefined URL, like you are here:

var url;
ws = new WebSocket(url);

You should do your switch statement before initializing new WebSocket(url).

var url;
switch (tipoChat) {
    case 1:
        url = 'foo';
}
ws = new WebSocket(url);


问:
DataTables constructing input data via Javascript dynamically does not work
I'm trying to fill up a table dynamically. Following is my code. dataTest contains the final output of dataSet after the for loop. Using dataTest as the input for the table, the table works properly and it fills up. But, using dataSet throws out the error DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1.. I've tried looking at https://datatables.net/manual/tech-notes/4 about this, but am not able to figure out. dataSet and dataTest essentially have the same value. Why does dataTest work but dataSet doesn't?

dataSet = "[";
for (prop = 0; prop < 26; prop++)
{
   test = "['" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "'],";

    test = test.replace(/'/g, '"');
    // console.log(test);
    dataSet = dataSet.concat(test);
    // console.log(test.replace(/'/g, '"'));
    // test = "'" + String(array0[prop]) + "' : '"  + String(array1[prop]) + "'";
    // console.log(JSON.stringify(test));
}
  end = "]";
  dataSet = dataSet.concat(end);
  console.log(dataSet);

var dataTest = [["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2"],["3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3"],["4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4"],["5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5"],["6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6"],["7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7"],["8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8"],["9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9"],["10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10"],["11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11"],["12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12"],["13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13"],["14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14"],["15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15"],["16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16"],["17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17"],["18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18"],["19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19"],["20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20"],["21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21"],["22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22"],["23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23"],["24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24"],["25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25"],]

  $(document).ready(function() {
    $('#example').DataTable({
      data: dataSet,
      columns: [{
          title: "C1"
        },
        {
          title: "C2"
        },
        {
          title: "C3"
        },
        {
          title: "C4"
        },
        {
          title: "C5"
        },
        {
          title: "C6"
        },
        {
          title: "C7"
        },
        {
          title: "C8"
        },
        {
          title: "C9"
        },
        {
          title: "C10"
        },
        {
          title: "C11"
        },
        {
          title: "C12"
        },
        {
          title: "C13"
        },
        {
          title: "C14"
        },
        {
          title: "C15"
        },
        {
          title: "C16"
        },
        {
          title: "C17"
        },
        {
          title: "C18"
        },
        {
          title: "C19"
        },
        {
          title: "C20"
        },
      ]
      // columns: [
      //     { title: "Name" },
      //     { title: "Position" },
      //     { title: "Office" },
      //     { title: "Extn." },
      //     { title: "Start date" },
      //     { title: "Salary" }
      // ]
    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.js"></script>

<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" width="100%"></table></code>```

答:
Looking at your doc link it seems you saw an array and decided to markup an array as a String (no good since data table expects an array and not a string that looks like an array). What you should have done is create the array using JavaScript arrays.

It worked with you variable dataTest because that is an actual array, and (again) not a string that looks like an array

Below is a example of how you can create the data properly for the data table.

$(document).ready(function() {

  var dataSet = [];
  for (var prop = 0; prop < 5; prop++) {
    var innerArray = [];
    for (var innerProp = 0; innerProp < 3; innerProp++) {
      innerArray.push(innerProp);
    }
    dataSet.push(innerArray);
  }
  //console.log(dataSet);

  $('#example').DataTable({
    data: dataSet,
    columns: [{
        title: "C1"
      },
      {
        title: "C2"
      },
      {
        title: "C3"
      }
    ]
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.js"></script>

<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" width="100%"></table></code>```

Body:
I'm trying to fill up a table dynamically. Following is my code. dataTest contains the final output of dataSet after the for loop. Using dataTest as the input for the table, the table works properly and it fills up. But, using dataSet throws out the error DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1.. I've tried looking at https://datatables.net/manual/tech-notes/4 about this, but am not able to figure out. dataSet and dataTest essentially have the same value. Why does dataTest work but dataSet doesn't?

dataSet = "[";
for (prop = 0; prop < 26; prop++)
{
   test = "['" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "','" + String(prop) + "'],";

    test = test.replace(/'/g, '"');
    // console.log(test);
    dataSet = dataSet.concat(test);
    // console.log(test.replace(/'/g, '"'));
    // test = "'" + String(array0[prop]) + "' : '"  + String(array1[prop]) + "'";
    // console.log(JSON.stringify(test));
}
  end = "]";
  dataSet = dataSet.concat(end);
  console.log(dataSet);

var dataTest = [["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2","2"],["3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3","3"],["4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4","4"],["5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5"],["6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6","6"],["7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7","7"],["8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8","8"],["9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9","9"],["10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10","10"],["11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11","11"],["12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12","12"],["13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13","13"],["14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14","14"],["15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15","15"],["16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16","16"],["17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17","17"],["18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18","18"],["19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19","19"],["20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20","20"],["21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21","21"],["22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22","22"],["23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23","23"],["24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24","24"],["25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25","25"],]

  $(document).ready(function() {
    $('#example').DataTable({
      data: dataSet,
      columns: [{
          title: "C1"
        },
        {
          title: "C2"
        },
        {
          title: "C3"
        },
        {
          title: "C4"
        },
        {
          title: "C5"
        },
        {
          title: "C6"
        },
        {
          title: "C7"
        },
        {
          title: "C8"
        },
        {
          title: "C9"
        },
        {
          title: "C10"
        },
        {
          title: "C11"
        },
        {
          title: "C12"
        },
        {
          title: "C13"
        },
        {
          title: "C14"
        },
        {
          title: "C15"
        },
        {
          title: "C16"
        },
        {
          title: "C17"
        },
        {
          title: "C18"
        },
        {
          title: "C19"
        },
        {
          title: "C20"
        },
      ]
      // columns: [
      //     { title: "Name" },
      //     { title: "Position" },
      //     { title: "Office" },
      //     { title: "Extn." },
      //     { title: "Start date" },
      //     { title: "Salary" }
      // ]
    });
  });

<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

Body:
Looking at your doc link it seems you saw an array and decided to markup an array as a String (no good since data table expects an array and not a string that looks like an array). What you should have done is create the array using JavaScript arrays.

It worked with you variable dataTest because that is an actual array, and (again) not a string that looks like an array

Below is a example of how you can create the data properly for the data table.

$(document).ready(function() {

  var dataSet = [];
  for (var prop = 0; prop < 5; prop++) {
    var innerArray = [];
    for (var innerProp = 0; innerProp < 3; innerProp++) {
      innerArray.push(innerProp);
    }
    dataSet.push(innerArray);
  }
  //console.log(dataSet);

  $('#example').DataTable({
    data: dataSet,
    columns: [{
        title: "C1"
      },
      {
        title: "C2"
      },
      {
        title: "C3"
      }
    ]
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.js"></script>

<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" width="100%"></table>


问:
How to split a column in two base of the 8 first number of a value in this column
I want to split a columns in two base of the 8 first number of each row. For example, my column look like this

```<code>       Col1
    7002500101
    7002500104
    7002500103
    7002600101
    7002500101
    7002500102
</code>```

And i want to separate de 8 first number for the other like this.

```<code>      Col1            Col2
    70025001           01
    70025001           04
    70025001           03
    70026001           01
    70025001           01
    70025001           02

</code>```

I find how to do it when we already have separation sign ( -,_,; etc.), but not for my situation.

答:
If you have a dataframe df containing your col1, you can use gsub and regular expressions to achieve the desired result:

```<code>df$newcol1 =  gsub("(^\\d{8}).*","\\1",df$col1)
df$newcol2 = gsub("^\\d{8}(.*)","\\1",df$col1))
        col1  newcol1 newcol2
1 7002500101 70025001      01
2 7002500104 70025001      04
3 7002500103 70025001      03
4 7002600101 70026001      01
5 7002500101 70025001      01
6 7002500102 70025001      02
</code>```

The first expression keeps the first 8 digits (^\\d{8}), while the second expression keeps whatever comes after the first 8 digits (.*).
The newcol1 and newcol2 columns will be of type character. If you want them as numeric, wrap the gsub in as.numeric(..).

Body:
I want to split a columns in two base of the 8 first number of each row. For example, my column look like this

       Col1
    7002500101
    7002500104
    7002500103
    7002600101
    7002500101
    7002500102

And i want to separate de 8 first number for the other like this.

      Col1            Col2
    70025001           01
    70025001           04
    70025001           03
    70026001           01
    70025001           01
    70025001           02

I find how to do it when we already have separation sign ( -,_,; etc.), but not for my situation.

Body:
If you have a dataframe df containing your col1, you can use gsub and regular expressions to achieve the desired result:

df$newcol1 =  gsub("(^\\d{8}).*","\\1",df$col1)
df$newcol2 = gsub("^\\d{8}(.*)","\\1",df$col1))
        col1  newcol1 newcol2
1 7002500101 70025001      01
2 7002500104 70025001      04
3 7002500103 70025001      03
4 7002600101 70026001      01
5 7002500101 70025001      01
6 7002500102 70025001      02

The first expression keeps the first 8 digits (^\\d{8}), while the second expression keeps whatever comes after the first 8 digits (.*).
The newcol1 and newcol2 columns will be of type character. If you want them as numeric, wrap the gsub in as.numeric(..).


问:
FtpWebRequest "The remote certificate is invalid according to the validation procedure"
I have a .NET client application that tries to ftp over a file to an FTP site which has a self-signed TLS/SSL certificate. This FTP site is running on Windows 7 Enterprise, IIS 7. I am getting the following error:

The remote certificate is invalid according to the validation procedure

I have tried installing the certificate in the trusted root certificates but that still does not work.

I have used the delegate call back in the code that is mentioned some of the posts here - it works. But I do not want to use that in my production code.

Also in production some of our customers are using self-signed certificates.

Any ideas on how to fix this issue?

答: You also get this error if you try to connect to IP address instead of domain name. Since certificate is issued to the domain name, IP address wont work.</p>


问:
Grails String to BigDecimal
I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

I'm doing:

```<code>person.salary = params.number
</code>```

But I got a error.

```<code>*salary is a BigDecimal and params.number is always a string.
</code>```

答:
You can try </p>

```<code>person.salary = params.number.toBigDecimal()
</code>```

Title: Grails String to BigDecimal

Body:
I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

I'm doing:

person.salary = params.number

But I got a error.

*salary is a BigDecimal and params.number is always a string.

Body:
You can try

person.salary = params.number.toBigDecimal()


问:
How to get current module object from model in Yii2
I have module ticket.

Module class has propery UserClassName (string).

In this module I have model called Dialog.

Within this model, I want to get access to the module property UserClassName.

How I can get module object from my model Dialog?

P.S. From controllers I can do next: $this->module.

答:
we can identify the module,controller and action method as follows in yii2

Yii::$app->controller->module->id;(For Getting Module ID)

Yii::$app->controller->id;(For Getting Controller ID)

Yii::$app->controller->action->id;(For Getting Controller action ID)


问:
How to store a password without a database (PHP)?
I would like to have a page that requires a password to login, but without a dataabase.

I was thinking of having it hard coded in the page, ie:

```<code>$password = "something"
</code>```

Or encrypt it and store it in a text file?

Any advice is appreciated.

答:
if you want to store in text file or hardcoded in php script I will recomended to hash it

first echo sha1('your password');

result string (not readeable) copy and paste in script or text file

when compare use if ( sha1($password) == '543f3fc32c232c32') ...

you can use also md5 for hashing

Both methods are one way encripting so "make sure you will remember your password"

Body:
I would like to have a page that requires a password to login, but without a dataabase.

I was thinking of having it hard coded in the page, ie:

$password = "something"

Or encrypt it and store it in a text file?

Any advice is appreciated.


问:
Dict with curly braces and OrderedDict
I thought I set out a simple project for myself but I guess not. I think im using the Ordered dict function long because I keep getting:

```<code> ValueError: too many values to unpack (expected 2)
</code>```

Code:

```<code>import random
import _collections

shop = {
    'bread': 2,
    'chips': 4,
    'tacos': 5,
    'tuna': 4,
    'bacon': 8,
}

print(shop)

'''
items = list(shop.keys())
random.shuffle(items)
_collections.OrderedDict(items)
'''

n = random.randrange(0, len(shop.keys()))
m = random.randrange(n, len(shop.keys()))

if m <= n:
    m += 1

print(n, " ", m)

for key in shop.keys():
    value = shop[key] * random.uniform(0.7,2.3)
    print(key, "=", int(value))
    if n < m:
        n += 1
    else:
        break
</code>```

I would like for this code to mix up the dictionary, then multiply the values by 0.7 - 2.3. Then loop within the range 0-5 times in order to give me few random keys from the dictionary.

I have placed ''' ''' over the code that I struggle with and gives me the errors.

答:
```<code>d = collections.OrderedDict.fromkeys(items)
</code>```

And then use newly created dict d as you wish.

Title: Dict with curly braces and OrderedDict

Body:
I thought I set out a simple project for myself but I guess not. I think im using the Ordered dict function long because I keep getting:

 ValueError: too many values to unpack (expected 2)

Code:

import random
import _collections

shop = {
    'bread': 2,
    'chips': 4,
    'tacos': 5,
    'tuna': 4,
    'bacon': 8,
}

print(shop)

'''
items = list(shop.keys())
random.shuffle(items)
_collections.OrderedDict(items)
'''

n = random.randrange(0, len(shop.keys()))
m = random.randrange(n, len(shop.keys()))

if m <= n:
    m += 1

print(n, " ", m)

for key in shop.keys():
    value = shop[key] * random.uniform(0.7,2.3)
    print(key, "=", int(value))
    if n < m:
        n += 1
    else:
        break

I would like for this code to mix up the dictionary, then multiply the values by 0.7 - 2.3. Then loop within the range 0-5 times in order to give me few random keys from the dictionary.

I have placed ''' ''' over the code that I struggle with and gives me the errors.

Body:
d = collections.OrderedDict.fromkeys(items)

And then use newly created dict d as you wish.


问:
nav-bar link's color is not working in bootstrap
I am trying to change link color on nav-bar but after the changing it seems the same. What is wrong? Why its not working? Here is the code:

```<code><nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav">

  <a class="navbar-brand" href="#page-top">
    <span class="d-block d-lg-none">Start Bootstrap</span>
    <span class="d-none d-lg-block">
      <img class="img-fluid img-profile rounded-circle mx-auto mb-2" src="img/profile.jpg" alt="">
    </span>
  </a>

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#about">About</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#experience">Experience</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#education">Education</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#skills">Skills</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#interests">Interests</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#awards">Awards</a>
      </li>
    </ul>
  </div>

</nav>
</code>```

CSS

```<code>.bg-primary {
  background-color: #BD5D38 !important;
}

,
.nav-link {
  color: #222222 !important;
}

.nav-link:hover,
.nav-link:focus,
.nav-link:active {
  color: #ffffff;
}

#sideNav .navbar-nav .nav-item .nav-link {
  font-weight: 600;
  text-transform: uppercase;
}

@media (min-width: 992px) {
  #sideNav {
    text-align: center;
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    width: 17rem;
    height: 100vh;
  }
  #sideNav .navbar-brand {
    display: flex;
    margin: auto auto 0;
    padding: 0.5rem;
  }
  #sideNav .navbar-brand .img-profile {
    max-width: 10rem;
    max-height: 10rem;
    border: 0.5rem solid rgba(255, 255, 255, 0.2);
  }
  #sideNav .navbar-collapse {
    display: flex;
    align-items: flex-start;
    flex-grow: 0;
    width: 100%;
    margin-bottom: auto;
  }
  #sideNav .navbar-collapse .navbar-nav {
    flex-direction: column;
    width: 100%;
  }
  #sideNav .navbar-collapse .navbar-nav .nav-item {
    display: block;
  }
  #sideNav .navbar-collapse .navbar-nav .nav-item .nav-link {
    display: block;
  }
}
</code>```

I changed it on the .nav-link  class but it's not working.  While nav-link lass is inside  tag. I don't want to use  tags for defining hover and link colors because on my site other links will have other colors while only nav-links must have this color. That is why I am trying to use nav-link class for it. How can I make it worked?
Thanks in advance!

答:
I think you have an unneeded comma after closing .bg-primary in your css.  Right now it looks like:

```<code>.bg-primary {
  background-color: #BD5D38 !important; },
</code>```

Remove the comma at the end so it should be:

```<code>.bg-primary {
  background-color: #BD5D38 !important; }
</code>```

I think the comma is messing with the following lines of code.  And the important in your color css is preventing the hover, focus and active states to work.

Here is how the top part of your css should look:

```<code>.bg-primary {
  background-color: #BD5D38 !important; }
.nav-link {
  color: #222222;
}
.nav-link:hover, .nav-link:focus, .nav-link:active {color:#ffffff}
</code>```

Also if you are linking to the new beta version of bootstrap 4 you need to be more specific and add the .navbar-dark .navbar-nav so it would look like:

```<code>.bg-primary {
  background-color: #BD5D38 !important;
}
.navbar-dark .navbar-nav .nav-link {
  color: #222222;
}
.navbar-dark .navbar-nav .nav-link:hover,
.navbar-dark .navbar-nav .nav-link:focus,
.navbar-dark .navbar-nav .nav-link:active {
  color:#ffffff
}
</code>```

Body:
I am trying to change link color on nav-bar but after the changing it seems the same. What is wrong? Why its not working? Here is the code:

    Start Bootstrap

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        About

        Experience

        Education

        Skills

        Interests

        Awards

CSS

.bg-primary {
  background-color: #BD5D38 !important;
}

,
.nav-link {
  color: #222222 !important;
}

.nav-link:hover,
.nav-link:focus,
.nav-link:active {
  color: #ffffff;
}

#sideNav .navbar-nav .nav-item .nav-link {
  font-weight: 600;
  text-transform: uppercase;
}

@media (min-width: 992px) {
  #sideNav {
    text-align: center;
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    width: 17rem;
    height: 100vh;
  }
  #sideNav .navbar-brand {
    display: flex;
    margin: auto auto 0;
    padding: 0.5rem;
  }
  #sideNav .navbar-brand .img-profile {
    max-width: 10rem;
    max-height: 10rem;
    border: 0.5rem solid rgba(255, 255, 255, 0.2);
  }
  #sideNav .navbar-collapse {
    display: flex;
    align-items: flex-start;
    flex-grow: 0;
    width: 100%;
    margin-bottom: auto;
  }
  #sideNav .navbar-collapse .navbar-nav {
    flex-direction: column;
    width: 100%;
  }
  #sideNav .navbar-collapse .navbar-nav .nav-item {
    display: block;
  }
  #sideNav .navbar-collapse .navbar-nav .nav-item .nav-link {
    display: block;
  }
}

I changed it on the .nav-link  class but it's not working.  While nav-link lass is inside  tag. I don't want to use  tags for defining hover and link colors because on my site other links will have other colors while only nav-links must have this color. That is why I am trying to use nav-link class for it. How can I make it worked?
Thanks in advance!

Body:
I think you have an unneeded comma after closing .bg-primary in your css.  Right now it looks like:

.bg-primary {
  background-color: #BD5D38 !important; },

Remove the comma at the end so it should be:

.bg-primary {
  background-color: #BD5D38 !important; }

I think the comma is messing with the following lines of code.  And the important in your color css is preventing the hover, focus and active states to work.

Here is how the top part of your css should look:

.bg-primary {
  background-color: #BD5D38 !important; }
.nav-link {
  color: #222222;
}
.nav-link:hover, .nav-link:focus, .nav-link:active {color:#ffffff}

Also if you are linking to the new beta version of bootstrap 4 you need to be more specific and add the .navbar-dark .navbar-nav so it would look like:

.bg-primary {
  background-color: #BD5D38 !important;
}
.navbar-dark .navbar-nav .nav-link {
  color: #222222;
}
.navbar-dark .navbar-nav .nav-link:hover,
.navbar-dark .navbar-nav .nav-link:focus,
.navbar-dark .navbar-nav .nav-link:active {
  color:#ffffff
}


问:
Game Center vs OpenFeint
I would like to add a global leaderboard for my games score.

Would you recommend Game Center or OpenFeint for implementing this?

What is needed to setup a global leaderboard? Is the server hosted by the service?

Thanks

答:
Game Center definitely.

It's officially supported by Apple so it's really well integrated into the sdk and there's no guarantee Apple will not prohibit all third-party game networks at some point in the future.

The servers are hosted by the service (for Game Center at least)

Title: Game Center vs OpenFeint


问:
SQL query that brings all records that doesn't includes a join with a given value
Lets suppose we have

```<code>Owners
id

Dogs
id
owner_id
trained (boolean)
</code>```

I want to get all owners who don't have any trained dog, including those who don't have a dog.

So if one owner has one trained dog, and one dog non trained, that owner should not appear, because already has a trained dog.

I tried with something like this:

```<code>SELECT * FROM owners o
LEFT JOIN dogs d on d.owner_id = o.id
WHERE
  d.trained = false OR d.trained IS NULL.
</code>```

But this query returns records including owners that have dogs trained, as long as they have a non trained dog.

I wan't to get only:

Owners who don't have a single trained dog

Owner who don't have dogs.

答:
The not exists operator does exactly that:

```<code>SELECT *
FROM   owners o
WHERE  NOT EXISTS (SELECT *
                   FORM   dogs d
                   WHERE  trained = true AND d.owner_id = o.id)
</code>```

Body:
Lets suppose we have

Owners
id

Dogs
id
owner_id
trained (boolean)

I want to get all owners who don't have any trained dog, including those who don't have a dog.

So if one owner has one trained dog, and one dog non trained, that owner should not appear, because already has a trained dog.

I tried with something like this:

SELECT * FROM owners o
LEFT JOIN dogs d on d.owner_id = o.id
WHERE
  d.trained = false OR d.trained IS NULL.

But this query returns records including owners that have dogs trained, as long as they have a non trained dog.

I wan't to get only:

Owners who don't have a single trained dog

Owner who don't have dogs.

Body:
The not exists operator does exactly that:

SELECT *
FROM   owners o
WHERE  NOT EXISTS (SELECT *
                   FORM   dogs d
                   WHERE  trained = true AND d.owner_id = o.id)


问:
React-native, how to resize the image based on the original size of image?
I have list of images to be displayed, wherein size of the image is unknown, how can I display the image fully without any transparent spaces in top and bottom of the image? (I tried getting image size from getSize method, which is eventually giving lot of spaces in top and bottom) I wanted image to resized and fit in like this,

But I'm getting white spaces if I put resize mode to contain, and if I put resize mode to stretch the size of small image is loosing its quality

how can I resize the image so that the white spaces are removed, and fit itself

答:
```<code>    import React, { Component } from "react";
    import { Dimensions, Image } from "react-native";

    const { width, height } = Dimensions.get("window");

    export default class ResizedImage extends Component {
      constructor(props) {
        super(props);
        this.state = {
          height: 0
        };
      }

      componentDidMount() {
        Image.getSize(
          this.props.source.uri,
          (srcWidth, srcHeight) => {
            const ratio = Math.min(width / srcWidth, height / srcHeight);
            this.setState({ height: srcHeight * ratio });
          },
          error => console.log(error)
        );
      }
      componentWillUnmount() {
        this.setState({ height: 0 });
      }

      render() {
        const { source} = this.props;
        return (
          <Image
            source={{ uri: source.uri }}
            style={{
              width: width * 0.9,
              height: this.state.height
            }}
            resizeMode={"cover"}
          />
        );
      }
    }
</code>```

You can use this as component and pass the URI as props and everything is done.

Body:
    import React, { Component } from "react";
    import { Dimensions, Image } from "react-native";

    const { width, height } = Dimensions.get("window");

    export default class ResizedImage extends Component {
      constructor(props) {
        super(props);
        this.state = {
          height: 0
        };
      }

      componentDidMount() {
        Image.getSize(
          this.props.source.uri,
          (srcWidth, srcHeight) => {
            const ratio = Math.min(width / srcWidth, height / srcHeight);
            this.setState({ height: srcHeight * ratio });
          },
          error => console.log(error)
        );
      }
      componentWillUnmount() {
        this.setState({ height: 0 });
      }

      render() {
        const { source} = this.props;
        return (
          <Image
            source={{ uri: source.uri }}
            style={{
              width: width * 0.9,
              height: this.state.height
            }}
            resizeMode={"cover"}
          />
        );
      }
    }

You can use this as component and pass the URI as props and everything is done.


问:
Boolean equals method
Writing an abstract class project. Abstract class is the parent class and include a the equals method. Part of my project is to create a Boolean equals method that compares the client IDs (long) of 3 subclasses to make sure that their are not any duplicates IDs. Having an issue implementing the code. Below is what I have so far

```<code>public static boolean equals(Object A, Object B, Object C) {
    if(A.equals(B) || A.equals(C) || B.equals(C))
        return true;
    else
        return false;
}
</code>```

Need help dropping the 3 class values for client ID into the code and then incorporating the code into a toString() method.

答:
I didn't get what you want, but I'll take a shot:</p>

```<code>static class Client {
    private long id;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (getClass() != obj.getClass()) return false;
        Client oth = (Client) obj;
        return oth.id == this.id;
    }

    Client(long id) {
        this.id = id;
    }
}

public static boolean equals(Object A, Object B, Object C) {
    return A.equals(B) || A.equals(C) || B.equals(C);
}

public static void main(String[] args) {
    Object c1 = new Client(4);
    Object c2 = new Client(3);
    Object c3 = new Client(2);

    equals(c1, c2, c3);
}
</code>```

Title: Boolean equals method

Body:
Writing an abstract class project. Abstract class is the parent class and include a the equals method. Part of my project is to create a Boolean equals method that compares the client IDs (long) of 3 subclasses to make sure that their are not any duplicates IDs. Having an issue implementing the code. Below is what I have so far

public static boolean equals(Object A, Object B, Object C) {
    if(A.equals(B) || A.equals(C) || B.equals(C))
        return true;
    else
        return false;
}

Need help dropping the 3 class values for client ID into the code and then incorporating the code into a toString() method.

Body:
I didn't get what you want, but I'll take a shot:

static class Client {
    private long id;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (getClass() != obj.getClass()) return false;
        Client oth = (Client) obj;
        return oth.id == this.id;
    }

    Client(long id) {
        this.id = id;
    }
}

public static boolean equals(Object A, Object B, Object C) {
    return A.equals(B) || A.equals(C) || B.equals(C);
}

public static void main(String[] args) {
    Object c1 = new Client(4);
    Object c2 = new Client(3);
    Object c3 = new Client(2);

    equals(c1, c2, c3);
}


问:
Replace a string with another string within a file in Python
You will be provided a file path for input I, a file path for output O, a string S, and a string T.

Read the contents of I, replacing each occurrence of S with T and write the resulting information to file O.

You should replace O if it already exists.

```<code># Get the filepath from the command line
import sys
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')

file2.replace(S, T)

file1.close()
file2.close()

file2= open('O', 'r')

print(file2)
</code>```

Here's the error I keep getting:

Traceback (most recent call last):
  File "write-text-file.py", line 15, in
    file2.replace(S, T)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

答:
Here is the code (Modified)

```<code># Get the filepath from the command line
import sys
import re
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
data = file1.read()
data = data.replace(S, T)
file2.write(data)

file1.close()
file2.close()

file2= open(O, 'r')
data = file2.read()
print(data)
</code>```

Body:
You will be provided a file path for input I, a file path for output O, a string S, and a string T.

Read the contents of I, replacing each occurrence of S with T and write the resulting information to file O.

You should replace O if it already exists.

# Get the filepath from the command line
import sys
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')

file2.replace(S, T)

file1.close()
file2.close()

file2= open('O', 'r')

print(file2)

Here's the error I keep getting:

Traceback (most recent call last):
  File "write-text-file.py", line 15, in
    file2.replace(S, T)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

Body:
Here is the code (Modified)

# Get the filepath from the command line
import sys
import re
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
data = file1.read()
data = data.replace(S, T)
file2.write(data)

file1.close()
file2.close()

file2= open(O, 'r')
data = file2.read()
print(data)


问:
Current and next props are the same in componentWillReceiveProps call
I am updating my redux store variables and pass them as props to a component but in this piece of code both current and next props are the same, equal to new ones when I change them via dispatch from outside.

```<code>componentWillReceiveProps (nextProps) {
    console.log(this.props.data);
    console.log(nextProps.data);
}
</code>```

Why does it happen so? Should they be different at all if changed via dispatch?

答:
According to the official docs:

Note that React may call this method even if the props have not
  changed, so make sure to compare the current and next values if you
  only want to handle changes. This may occur when the parent component
  causes your component to re-render.

So you should be seeing at least one set of different props (the actual change) but not necessarily on every log.

Body:
I am updating my redux store variables and pass them as props to a component but in this piece of code both current and next props are the same, equal to new ones when I change them via dispatch from outside.

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

Why does it happen so? Should they be different at all if changed via dispatch?


答:
You are very close, but you cannot just give the list of keys ot the new OrderedDict, you must give the values too... try this:

```<code>import random
import collections

shop = {
    'bread': 2,
    'chips': 4,
    'tacos': 5,
    'tuna': 4,
    'bacon': 8,
}

print(shop)

items = list(shop.keys())
random.shuffle(items)

print(items)

ordered_shop = collections.OrderedDict()
for item in items:
    ordered_shop[item] = shop[item]

print(ordered_shop)
</code>```

Example output:

{'chips': 4, 'tuna': 4, 'bread': 2, 'bacon': 8, 'tacos': 5}
['bacon', 'chips', 'bread', 'tuna', 'tacos']
OrderedDict([('bacon', 8), ('chips', 4), ('bread', 2), ('tuna', 4), ('tacos', 5)])
```

<hr>

<p>You could also do this like this (as pointed out by @ShadowRanger):</p>

<pre class="lang-py prettyprint-override"><code>items = list(shop.items())
random.shuffle(items)
oshop = collections.OrderedDict(items)
</code>```

This works because the OrderedDict constructor takes a list of key-value tuples. On reflection, this is probably what you were after with your initial approach - swap keys() for items().

Title: Dict with curly braces and OrderedDict

Body:
You are very close, but you cannot just give the list of keys ot the new OrderedDict, you must give the values too... try this:

import random
import collections

shop = {
    'bread': 2,
    'chips': 4,
    'tacos': 5,
    'tuna': 4,
    'bacon': 8,
}

print(shop)

items = list(shop.keys())
random.shuffle(items)

print(items)

ordered_shop = collections.OrderedDict()
for item in items:
    ordered_shop[item] = shop[item]

print(ordered_shop)

Example output:

{'chips': 4, 'tuna': 4, 'bread': 2, 'bacon': 8, 'tacos': 5}
['bacon', 'chips', 'bread', 'tuna', 'tacos']
OrderedDict([('bacon', 8), ('chips', 4), ('bread', 2), ('tuna', 4), ('tacos', 5)])

You could also do this like this (as pointed out by @ShadowRanger):

items = list(shop.items())
random.shuffle(items)
oshop = collections.OrderedDict(items)

This works because the OrderedDict constructor takes a list of key-value tuples. On reflection, this is probably what you were after with your initial approach - swap keys() for items().