问:
thycotic REST call returns http instead of json
We have two Secret Server servers - prod with cert from CA and test with self signed cert.

We've been developing on the test one with self signed cert ignoring ssl warnings (showed here as curl with --insecure). And all works fine – e.g.:

Unauthenticated GET call (returns 403):

```<code>curl --header "Content-Type: application/json" --request GET --insecure https://192.168.100.191/secretserver/api/v1/users

{
  "message": "Authentication failed or expired token."
}
</code>```

Authentication token request:

```<code>curl --header "Content-Type: application/x-www-form-urlencoded" --request POST --data "username=Admin&password=passw0rd&grant_type=password" --insecure https://192.168.100.191/secretserver/oauth2/token

{"access_token":"XRVpc2S7SotSAVDv...GH8GZtw","token_type":"bearer","expires_in":1199}
</code>```

However we can not get working the same requests on the prod env with cert from CA. Whatever service we call, we get 200 with html document in the body – e.g. (the same examples as above):

Unauthenticated GET call (supposed to get 403, but getting 200 with html):

```<code>curl --header "Content-Type: application/json" --request GET https://ssserver.com/secretserver/api/v1/users

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/Login.aspx?ReturnUrl=%2fsecretserver%2fapi%2fv1%2fusers">here</a>.</h2>
</body></html>
</code>```

Authentication token request:

```<code>curl --header "Content-Type: application/x-www-form-urlencoded" --request POST --data "username=Admin&password=passw0rd&grant_type=password" https://ssserver.com/secretserver/oauth2/token

<html><head><title>Object moved</title></head><body> <h2>Object moved to <a href="/Login.aspx?ReturnUrl=%2fsecretserver%2foauth2%2ftoken">here</a>.</h2> </body></html>
</code>```

答: The problem was that the server use non default URL ,which I wasn't aware of.</p>

Body:
We have two Secret Server servers - prod with cert from CA and test with self signed cert.

We've been developing on the test one with self signed cert ignoring ssl warnings (showed here as curl with --insecure). And all works fine – e.g.:

Unauthenticated GET call (returns 403):

curl --header "Content-Type: application/json" --request GET --insecure https://192.168.100.191/secretserver/api/v1/users

{
  "message": "Authentication failed or expired token."
}

Authentication token request:

curl --header "Content-Type: application/x-www-form-urlencoded" --request POST --data "username=Admin&password=passw0rd&grant_type=password" --insecure https://192.168.100.191/secretserver/oauth2/token

{"access_token":"XRVpc2S7SotSAVDv...GH8GZtw","token_type":"bearer","expires_in":1199}

However we can not get working the same requests on the prod env with cert from CA. Whatever service we call, we get 200 with html document in the body – e.g. (the same examples as above):

Unauthenticated GET call (supposed to get 403, but getting 200 with html):

curl --header "Content-Type: application/json" --request GET https://ssserver.com/secretserver/api/v1/users

<title>Object moved</title>

Object moved to here.

Authentication token request:

curl --header "Content-Type: application/x-www-form-urlencoded" --request POST --data "username=Admin&password=passw0rd&grant_type=password" https://ssserver.com/secretserver/oauth2/token

<title>Object moved</title>
Object moved to here.


来源: stackexchange

问:
Node js authentication in cross domain
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

```<code>var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;
</code>```

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.

答:
If I understand the problem correctly here, you want the user's session to be stateless on the server. So that whenever the user logs in, the session can be re-used in any instance of the server when you scale your application, or even if you were to just reboot your application.

To achieve this, what you need is to configure the express-session with a database solution. You can do this with mongo using this package https://github.com/jdesboeufs/connect-mongo.

However, best practice is to use something a bit more robust for this sort of use-case, like redis using this package https://github.com/tj/connect-redis.

ContentLicense: CC BY-SA 3.0

Title: Node js authentication in cross domain

Body:
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.


问:
Data persistence through NSUserDefaults
Is data persisted in NSUserDefaults between app launches? I want some small data to be persisted even if I quit and relaunch the app.</p>

答:
Data will persist. But, NSUserDefaults is used primarily for preferences. Users expect that it is okay to delete the preference file without affecting their documents and created data.

If the data is not a preference, you may want to store the data in a file inside ~/Library/Application Support/[your application's name]/ instead.

ContentLicense: CC BY-SA 2.5

Title: Data persistence through NSUserDefaults


问:
Does tidytext::unnest_tokens works with spanish characters?
I am trying to use unnest_tokens with spanish text. It works fine with unigrams, but breaks the special characters with bigrams.

The code works fine on Linux. I added some info on the locale.

```<code>library(tidytext)
library(dplyr)

df <- data_frame(
  text = "César Moreira Nuñez"
)

# works ok:
df %>%
  unnest_tokens(word, text)

# # A tibble: 3 x 1
# word
# <chr>
# 1 césar
# 2 moreira
# 3 nuñez

# breaks é and ñ
df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2 )

# # A tibble: 2 x 1
# bigram
# <chr>
# 1 cã©sar moreira
# 2 moreira nuã±ez

> Sys.getlocale()
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United
States.1252;LC_MONETARY=English_United
States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
</code>```

答:
Digging in the source code for tidytext, it looks like the words and ngrams are split using the tokenizer package. Those functions use different methods: tokenize_words uses stri_split, whereas tokenize_ngrams uses custom C++ code.

I imagine the final step -- switching between R and C++ data types -- garbles the diacritics, although I can't explain why precisely.

Body:
I am trying to use unnest_tokens with spanish text. It works fine with unigrams, but breaks the special characters with bigrams.

The code works fine on Linux. I added some info on the locale.

library(tidytext)
library(dplyr)

df <- data_frame(
  text = "César Moreira Nuñez"
)

# works ok:
df %>%
  unnest_tokens(word, text)

# # A tibble: 3 x 1
# word
# <chr>
# 1 césar
# 2 moreira
# 3 nuñez

# breaks é and ñ
df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2 )

# # A tibble: 2 x 1
# bigram
# <chr>
# 1 cã©sar moreira
# 2 moreira nuã±ez

> Sys.getlocale()
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United
States.1252;LC_MONETARY=English_United
States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"


问:
need to store ajax response to a global variable
I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

```<code>var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });
</code>```

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{
'something': { 'act1': 'act1a','act2': 'act2a'},
 'something2': { 'act1': 'act1a','act2': 'act2a'}
}

anyone have any suggestions on how to achieve that?

PS:
I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format

答:
```<code>var array;
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);
                function_ThatNeeds_Thearray();

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });
</code>```

Body:
I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{
'something': { 'act1': 'act1a','act2': 'act2a'},
 'something2': { 'act1': 'act1a','act2': 'act2a'}
}

anyone have any suggestions on how to achieve that?

PS:
I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format


问:
How to display Arabic dates in the Gregorian calendar?
I have a multilingual ASP.NET site; one of the languages is Arabic (ar-SA). To switch between cultures, I use this code:

```<code>Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Name)
Thread.CurrentThread.CurrentUICulture = New CultureInfo(Name)
</code>```

When displaying the date of an article, for example, I just do this, and the localization API takes care of everything:

```<code><%#Eval("DatelineDate","{0:d MMMM yyyy}")%>
</code>```

The problem is that this displays dates using the Hijiri (Islamic) calendar (e.g. the year 2008 is rendered as 1429). The client wants to display the dates using the Gregorian calendar (still rendering the month names and everything else in Arabic, of course). How can I do this?

答: You can just use another Arabic locale, The only difference between them is the Date format...</p>

OwnerDisplayName: Herb Caudill

Body:
I have a multilingual ASP.NET site; one of the languages is Arabic (ar-SA). To switch between cultures, I use this code:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Name)
Thread.CurrentThread.CurrentUICulture = New CultureInfo(Name)

When displaying the date of an article, for example, I just do this, and the localization API takes care of everything:

<%#Eval("DatelineDate","{0:d MMMM yyyy}")%>

The problem is that this displays dates using the Hijiri (Islamic) calendar (e.g. the year 2008 is rendered as 1429). The client wants to display the dates using the Gregorian calendar (still rendering the month names and everything else in Arabic, of course). How can I do this?

OwnerDisplayName: Osama ALASSIRY


问:
Count Rows in Excel on conditionAND {condition OR condition<c>}
no matter how hard I reconfigure COUNTIF and COUNTIFS I can't get the output to work, here is a table example :

I cannot get a function that will count Where Severity = High AND (Customer !="" OR Case Info !="")

In the table example I should get a return of 5.

The closest I have got so far is with =COUNTIFS('8.2'!C:C,"High",'8.2'!A:A,"<>",'8.2'!B:B,"<>"), But that only returns 3.

What excel function could do what I need?

答:
With COUNTIFS() you will need to do three:

```<code>=COUNTIFS(C:C,"High",A:A,"<>")+COUNTIFS(C:C,"High",B:B,"<>")-COUNTIFS(C:C,"High",A:A,"<>",B:B,"<>")
</code>```

Or as XORLX showed:

```<code>=SUM(COUNTIFS(C:C,"High",A:A,{"<>","","<>"},B:B,{"","<>","<>"}))
</code>```

But this requires that the cells be true blank, no formulas that return and empty string

SUMPRODUCT is slightly shorter but it requires that you specify the data range to avoid unnecessary iterations as it is an array type formula:

```<code>=SUMPRODUCT((C2:C17="high")*((A2:A17<>"")+(B2:B17<>"")-((A2:A17<>"")*(B2:B17<>""))))
</code>```

Or this one by XORLX, who has forgotten more about excel formulas than I will ever know:

```<code>=SUMPRODUCT((C1:C20="high")*((A1:A20<>"")+(B1:B20<>"")>0))
</code>```

Title: Count Rows in Excel on condition<a>AND {condition<b> OR condition<c>}

Body:
With COUNTIFS() you will need to do three:

=COUNTIFS(C:C,"High",A:A,"<>")+COUNTIFS(C:C,"High",B:B,"<>")-COUNTIFS(C:C,"High",A:A,"<>",B:B,"<>")

Or as XORLX showed:

=SUM(COUNTIFS(C:C,"High",A:A,{"<>","","<>"},B:B,{"","<>","<>"}))

But this requires that the cells be true blank, no formulas that return and empty string

SUMPRODUCT is slightly shorter but it requires that you specify the data range to avoid unnecessary iterations as it is an array type formula:

=SUMPRODUCT((C2:C17="high")*((A2:A17<>"")+(B2:B17<>"")-((A2:A17<>"")*(B2:B17<>""))))

Or this one by XORLX, who has forgotten more about excel formulas than I will ever know:

=SUMPRODUCT((C1:C20="high")*((A1:A20<>"")+(B1:B20<>"")>0))


问:
Deserialise Json file with newtonsoft and query with linq
I'm new to Newtonsoft and I'm trying to deserialise my json file then query specific data points from it. Here is a sample of the json.

```<code>[
    {
        "reward_type": "1",
        "rejected": "0",
        "user_id": "538653",
        "granted": "0"
    },
    {
        "reward_type": "5",
        "rejected": "0",
        "user_id": "536345",
        "granted": "1"
    },
    {
        "reward_type": "5",
        "rejected": "0",
        "user_id": "539493",
        "granted": "1"
    }
]
</code>```

I'm trying to query the values after each type. I've been trying to wrap my head around the documentation for Json.net for a few days, but I'm having trouble finding examples for deserializing files.

Here is what I've been using to parse the file.

```<code>InitializeComponent();
        JArray adData1 = JArray.Parse(File.ReadAllText(@"c:\ads.json"));
        using (StreamReader file = File.OpenText(@"c:\ads.json"))
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            JsonSerializer serializer = new JsonSerializer();
            JArray adData2 = (JArray)serializer.Deserialize(file, typeof(JArray));

            JObject rewardType = (JObject)adData2[1];
            label1.Text = rewardType.ToString();
        }
</code>```

Any help is appreciated.

答:
From the suggestions:

Its only useable if the data have a common structure. You can Replace the DataTypes in the POCO, if you like

The POCO

```<code>public class Stuff {
    public string reward_type { get; set; }
    public string rejected { get; set; }
    public string user_id { get; set; }
    public string granted { get; set; }
}
</code>```

How to use:

```<code>public void doThings() {
// var s = File.ReadAllText("yourfilename.json");
    var s = @"{
""reward_type"": ""1"",
""rejected"": ""0"",
""user_id"": ""538653"",
""granted"": ""0""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""536345"",
""granted"": ""1""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""539493"",
""granted"": ""1""
}";
    // [] is needed to make it recognize it as list
    var listOfStuff = JsonConvert.DeserializeObject<List<Stuff>>("["+s+"]");
    foreach (var item in listOfStuff)
    {
        Console.WriteLine(item.user_id);
    }

}
</code>```

Body:
I'm new to Newtonsoft and I'm trying to deserialise my json file then query specific data points from it. Here is a sample of the json.

[
    {
        "reward_type": "1",
        "rejected": "0",
        "user_id": "538653",
        "granted": "0"
    },
    {
        "reward_type": "5",
        "rejected": "0",
        "user_id": "536345",
        "granted": "1"
    },
    {
        "reward_type": "5",
        "rejected": "0",
        "user_id": "539493",
        "granted": "1"
    }
]

I'm trying to query the values after each type. I've been trying to wrap my head around the documentation for Json.net for a few days, but I'm having trouble finding examples for deserializing files.

Here is what I've been using to parse the file.

InitializeComponent();
        JArray adData1 = JArray.Parse(File.ReadAllText(@"c:\ads.json"));
        using (StreamReader file = File.OpenText(@"c:\ads.json"))
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            JsonSerializer serializer = new JsonSerializer();
            JArray adData2 = (JArray)serializer.Deserialize(file, typeof(JArray));

            JObject rewardType = (JObject)adData2[1];
            label1.Text = rewardType.ToString();
        }

Any help is appreciated.

Body:
From the suggestions:

Its only useable if the data have a common structure. You can Replace the DataTypes in the POCO, if you like

The POCO

public class Stuff {
    public string reward_type { get; set; }
    public string rejected { get; set; }
    public string user_id { get; set; }
    public string granted { get; set; }
}

How to use:

public void doThings() {
// var s = File.ReadAllText("yourfilename.json");
    var s = @"{
""reward_type"": ""1"",
""rejected"": ""0"",
""user_id"": ""538653"",
""granted"": ""0""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""536345"",
""granted"": ""1""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""539493"",
""granted"": ""1""
}";
    // [] is needed to make it recognize it as list
    var listOfStuff = JsonConvert.DeserializeObject<List<Stuff>>("["+s+"]");
    foreach (var item in listOfStuff)
    {
        Console.WriteLine(item.user_id);
    }

}


问:
Why can I only Input a "1,5" but not a "1.5"
I coded a little program to calculate a tax, but I have a problem. The problem multiplies the number that I put in by 0.9975, but I can only put in a double number with a "," and not with a dot ".".</p>

```<code>import java.util.Scanner;

public class Bitrex {
    public static void main(String[] args) {
        Scanner Bitcoin = new Scanner (System.in);
        double num1;
        double num2=0.9975;
        double answer;

        System.out.println("Enter Expected Price: ");
        num1 = Bitcoin.nextDouble();
        answer = num1 * num2;
        System.out.println(answer);
    } // end of main
}
</code>```

答:
You probably are in Germany and Scanner uses the default Locale, that is, , is used as the decimal separator for parsing. See the Javadoc of Scanner.

You should set the Locale you want to use like in

```<code>...

Scanner Bitcoin = new Scanner (System.in);
Bitcoin.useLocale(Locale.US);  // or Locale.ROOT  or  new Locale("pt", "BR")

...
</code>```

(do not forget import java.util.Locale;)

Eventually it is better to set the default Locale for the whole application using Locale.setDefault(Locale.ROOT);

Body:
I coded a little program to calculate a tax, but I have a problem. The problem multiplies the number that I put in by 0.9975, but I can only put in a double number with a "," and not with a dot ".".

import java.util.Scanner;

public class Bitrex {
    public static void main(String[] args) {
        Scanner Bitcoin = new Scanner (System.in);
        double num1;
        double num2=0.9975;
        double answer;

        System.out.println("Enter Expected Price: ");
        num1 = Bitcoin.nextDouble();
        answer = num1 * num2;
        System.out.println(answer);
    } // end of main
}

Body:
You probably are in Germany and Scanner uses the default Locale, that is, , is used as the decimal separator for parsing. See the Javadoc of Scanner.

You should set the Locale you want to use like in

...

Scanner Bitcoin = new Scanner (System.in);
Bitcoin.useLocale(Locale.US);  // or Locale.ROOT  or  new Locale("pt", "BR")

...

(do not forget import java.util.Locale;)

Eventually it is better to set the default Locale for the whole application using Locale.setDefault(Locale.ROOT);


问:
HMAC Auth Approach in WebAPI / Web Applications
I am recently working on a WebAPI project where I will be opening up some endpoints for other intranet web applications to select some of my data within my OracleDB tablespace. One of my top concerns now is securing the WebAPI against invalid calls to my API.

I am looking at the HMAC approach where I share unique keys with different authorized web apps that can call my API.

My question is,

Assuming I share Key A with WebApp A and Key B with WebApp B, can the developer of WebApp A use Key A with his another WebApp C to gain access to my API and make 'authorized' calls? The key shared to them is susceptible to abuse in other applications.

答: Of course, your keys could be used everywhere. In general, HMAC approach is designed to authenticate messages. In other words, when you are using HMAC, you are 100% sure, that the key owner (except scenario when key was compromised) has sent you a request. Nothing can stop key-owner from sharing this key. But, the main thing is, that from perspective of your "host"-API, all the requests signed with particular key should be considered as the same client, independently of are they physically the same application or not.


问:
Why am I not receiving a console.log that a new socket user has connected?
I'm more or less following the socket.io documentation and trying to apply it to my slightly different project but I believe I'm making some mistake. I've used express-generator to create my project's skeleton and therefore I got app.js file, www file and route files.

I've put this code in www file:

```<code>var io = require('socket.io')(http);
console.log('Socket is running!');
io.on('connection', function(socket){
    console.log('A User Has Connected: ' + socket.id);
});
</code>```

This code in my footer file:

```<code><script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-3.2.1.min.js"></script>
<script src="/javascripts/javascript.js"></script>
</body>
</html>
</code>```

And this in my JavaScript file:

```<code>$(document).ready(function(){

    var socket = io();

});
</code>```

Now I understand that when a request is made, the console should log "A User Has Connected: " + the id of the socket but I'm not getting anything other than "Socket is running!". I assume I'm missing something but can't figure it out and the documentation is using the same code.

```<code>var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
</code>```

答:
You have to use the same server instance express-generator creates, which is the following line in www file

```<code>var server = http.createServer(app);
</code>```

To use that, change

```<code>var io = require('socket.io')(http);
</code>```

to

```<code>var io = require('socket.io')(server);
</code>```

Body:
I'm more or less following the socket.io documentation and trying to apply it to my slightly different project but I believe I'm making some mistake. I've used express-generator to create my project's skeleton and therefore I got app.js file, www file and route files.

I've put this code in www file:

var io = require('socket.io')(http);
console.log('Socket is running!');
io.on('connection', function(socket){
    console.log('A User Has Connected: ' + socket.id);
});

This code in my footer file:

And this in my JavaScript file:

$(document).ready(function(){

    var socket = io();

});

Now I understand that when a request is made, the console should log "A User Has Connected: " + the id of the socket but I'm not getting anything other than "Socket is running!". I assume I'm missing something but can't figure it out and the documentation is using the same code.

var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

Body:
You have to use the same server instance express-generator creates, which is the following line in www file

var server = http.createServer(app);

To use that, change

var io = require('socket.io')(http);

to

var io = require('socket.io')(server);


问:
Help me find the problem with my solution to Project Euler #12 in Haskell
I'm a total newbie to Haskell, and programming in general, but I'm trying to work through some Project Euler problems because I do like problem solving.  However, I have a problem with problem #12.

I devised a solution I thought would work, but alas, it does not.

Can you help me by opening my eyes to the problem with my code,
and maybe push me in the right direction towards fixing it?  Thank you.

Here is the code:

```<code>triangleNumber = scanl1 (+) [1..]

factors n = [x | x <- [1..n], n `mod` x == 0]

numFactors = length . factors

eulerTwelve = find ((>500) . numFactors) triangleNumber
</code>```

Thank you very much!  :)

答:
I assume the problem you're alluding to is that eulerTwelve takes way too long to terminate; your code is correct, it's just inefficient. The bottleneck is your factors function, which is trying every number between 1 and n to see if it's a divisor of n. Here's a faster way to find the divisors of a number, using efficient prime factorization and a nifty implementation of the power set:

```<code>import Data.Numbers.Primes (primeFactors)

powerSet = filterM (const [True, False])

factors = map product . nub . powerSet . primeFactors
</code>```

Even this is pretty inefficient; you can instead calculate numFactors directly from primeFactors like so:

```<code>numFactors = product . map ((+1) . length) . group . primeFactors
</code>```

When I replace your numFactors with this one I obtain the result instantly.

Body:
I'm a total newbie to Haskell, and programming in general, but I'm trying to work through some Project Euler problems because I do like problem solving.  However, I have a problem with problem #12.

I devised a solution I thought would work, but alas, it does not.

Can you help me by opening my eyes to the problem with my code,
and maybe push me in the right direction towards fixing it?  Thank you.

Here is the code:

triangleNumber = scanl1 (+) [1..]

factors n = [x | x <- [1..n], n `mod` x == 0]

numFactors = length . factors

eulerTwelve = find ((>500) . numFactors) triangleNumber

Thank you very much!  :)

Body:
I assume the problem you're alluding to is that eulerTwelve takes way too long to terminate; your code is correct, it's just inefficient. The bottleneck is your factors function, which is trying every number between 1 and n to see if it's a divisor of n. Here's a faster way to find the divisors of a number, using efficient prime factorization and a nifty implementation of the power set:

import Data.Numbers.Primes (primeFactors)

powerSet = filterM (const [True, False])

factors = map product . nub . powerSet . primeFactors

Even this is pretty inefficient; you can instead calculate numFactors directly from primeFactors like so:

numFactors = product . map ((+1) . length) . group . primeFactors

When I replace your numFactors with this one I obtain the result instantly.


问:
Invariant Violation: Native component for "RNSVGSvgView" does not exist
After days of research on the internet I still haven't solved my problem yet.
I am using react-native-svg and I am having the same issues:
No component found for view with the name "RNSVGPath"

Or this one:
Invariant Violation: Native component for "RNSVGSvgView" does not exist

I tried a lot of things, including:

```<code>react-native unlink react-native-svg
npm uninstall react-native-svg
npm install react-native-svg
react-native link react-native-svg
react-native run-ios
</code>```

Also:

```<code>pod 'RNSVG', :path => '../node_modules/react-native-svg'
rm -rf node_modules
npm install
react-native run-ios
</code>```

But still nothing...
Here's the versions I am using:

```<code>"dependencies": {
    "react": "16.1.1",
    "react-native": "0.50.3",
    "react-native-svg": "^6.0.1-rc.1"
}
</code>```

I tried to build it from XCode directly and still nothing...

Thanks for your help guys !

答:
You should try to do this:

```<code>npm install react-native-svg --save //(again)
react-native link react-native-svg //(again)
watchman watch-del-all
rm -rf node_modules/ && yarn cache clean && yarn install
</code>```

Then in another terminal

```<code>npm start -- --reset-cache
</code>```

Before starting your ios app with react-native run-ios, you have to add libRNSVG.a manually to your Linked Frameworks and Libraries in Xcode

And then ... Tada

Body:
After days of research on the internet I still haven't solved my problem yet.
I am using react-native-svg and I am having the same issues:
No component found for view with the name "RNSVGPath"

Or this one:
Invariant Violation: Native component for "RNSVGSvgView" does not exist

I tried a lot of things, including:

react-native unlink react-native-svg
npm uninstall react-native-svg
npm install react-native-svg
react-native link react-native-svg
react-native run-ios

Also:

pod 'RNSVG', :path => '../node_modules/react-native-svg'
rm -rf node_modules
npm install
react-native run-ios

But still nothing...
Here's the versions I am using:

"dependencies": {
    "react": "16.1.1",
    "react-native": "0.50.3",
    "react-native-svg": "^6.0.1-rc.1"
}

I tried to build it from XCode directly and still nothing...

Thanks for your help guys !

Body:
You should try to do this:

npm install react-native-svg --save //(again)
react-native link react-native-svg //(again)
watchman watch-del-all
rm -rf node_modules/ && yarn cache clean && yarn install

Then in another terminal

npm start -- --reset-cache

Before starting your ios app with react-native run-ios, you have to add libRNSVG.a manually to your Linked Frameworks and Libraries in Xcode

And then ... Tada


问:
For loop in python - beginner
I'm trying to solve a project where i have to count the years in a list but I`m having problems understanding the difference between

```<code>years = [n[1] for n in data]
</code>```

and

```<code>for n in data:
         years = n[1]
</code>```

here is the rest of the body

```<code>for m in years:
    if m not in year_counts:
        year_counts[m] = 0
    year_counts[m] += 1

print(year_counts)
</code>```

So if I use the first sentence then the code will run normally and will show the proper answer but if i use the second code it will give me random numbers I don't know from where.

答:
This code years = [n[1] for n in data] output is list.
This code

```<code>for n in data:
     years = n[1]
</code>```

output is a single variable that contains last value.

Title: For loop in python - beginner

Body:
I'm trying to solve a project where i have to count the years in a list but I`m having problems understanding the difference between

years = [n[1] for n in data]

and

for n in data:
         years = n[1]

here is the rest of the body

for m in years:
    if m not in year_counts:
        year_counts[m] = 0
    year_counts[m] += 1

print(year_counts)

So if I use the first sentence then the code will run normally and will show the proper answer but if i use the second code it will give me random numbers I don't know from where.

Body:
This code years = [n[1] for n in data] output is list.
This code

for n in data:
     years = n[1]

output is a single variable that contains last value.


问:
QTreeWidget how to add check boxes to children?
I'm trying to add some check boxes to the children in a QTreeViewWidget, but they are not showing.

```<code>TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item1', 'Item2', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        parent.addChild(child)
</code>```

The TreeViewList populates as it should, but the checkboxes are not there, any ideas?

答:
You have to set a value to the checkbox:

```<code>child.setCheckState(0, Qt.Unchecked)
</code>```

In your case:

```<code>app = QApplication(sys.argv)

TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item1', 'Item2', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)
tree.show()

sys.exit(app.exec_())
</code>```

Body:
I'm trying to add some check boxes to the children in a QTreeViewWidget, but they are not showing.

TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item1', 'Item2', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        parent.addChild(child)

The TreeViewList populates as it should, but the checkboxes are not there, any ideas?

Body:
You have to set a value to the checkbox:

child.setCheckState(0, Qt.Unchecked)

In your case:

app = QApplication(sys.argv)

TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item1', 'Item2', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)
tree.show()

sys.exit(app.exec_())


问:
Modal created in JavaScript do not disappear on mobile
I have assembled a modal with embedded video using Iframe.
It opens and closes on desktop but does not close on mobile.

Here is the code:

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close");

function toggleModal() {
  modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
  if (event.target === modal) {
    toggleModal();
    var iframe = document.getElementById('demo');
    var iframeSrc = iframe.src;
    iframe.src = iframeSrc;
  }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  width: 420px;
  height: 345px;
  border-radius: 10px;
}

.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  visibility: hidden;
  transform: scaleX(1.1) scaleY(1.1);
  transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}

.modal-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
}

iframe {
  width: 420px;
  height: 345px;
  border: 0px;
  border-radius: 10px;
  box-shadow: 0 0 20px 0px black;
}

.close-button:hover {
  background-color: darkgray;
}

.show-modal {
  opacity: 1;
  visibility: visible;
  transform: scaleX(1.0) scaleY(1.0);
  transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}

div {
  display: inline-block;
  position: relative;
}

img {
  max-width: 100%;
}

.thumb {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 96px;
  height: 96px;
}

.round-button {
  box-sizing: border-box;
  display: block;
  width: 80px;
  height: 80px;
  padding-top: 14px;
  padding-left: 8px;
  line-height: 20px;
  border: 6px solid #fff;
  border-radius: 50%;
  color: #f5f5f5;
  text-align: center;
  text-decoration: none;
  background-color: #3fa6d9;
  font-size: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.round-button:hover {
  background-color: #2b7dff;
  box-shadow: 0px 0px 1px rgba(255, 255, 10, 1);
  text-shadow: 0px 0px 1px rgba(255, 255, 1, 1);
}</code>```

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

```

Is there a way to make it work on mobile without using library like Bootstrap?

I just need to be able to close the window with a modal when on mobile phone.

Please help.

答:
Simple X could solve your issue. I used symbol from font-awesome in given example.

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.getElementById("closediv");

function toggleModal() {
  modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
  if (event.target === modal) {
    toggleModal();
    var iframe = document.getElementById('demo');
    var iframeSrc = iframe.src;
    iframe.src = iframeSrc;
  }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  width: 420px;
  height: 345px;
  border-radius: 10px;
}

.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  visibility: hidden;
  transform: scaleX(1.1) scaleY(1.1);
  transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}

.modal-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
}

iframe {
  width: 420px;
  height: 345px;
  //border-style: solid;
  //border-width: thin;
  border: 0px;
  border-radius: 10px;
  box-shadow: 0 0 20px 0px black;
}

.close-button:hover {
  background-color: darkgray;
}

.show-modal {
  opacity: 1;
  visibility: visible;
  transform: scaleX(1.0) scaleY(1.0);
  transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}

div {
  display: inline-block;
  position: relative;
}

img {
  max-width: 100%;
}

.thumb {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 96px;
  height: 96px;
  cursor: pointer;
}

.round-button {
  box-sizing: border-box;
  display: block;
  width: 80px;
  height: 80px;
  padding-top: 14px;
  padding-left: 8px;
  line-height: 20px;
  border: 6px solid #fff;
  border-radius: 50%;
  color: #f5f5f5;
  text-align: center;
  text-decoration: none;
  background-color: #3fa6d9;
  font-size: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.round-button:hover {
  background-color: #2b7dff;
  box-shadow: 0px 0px 1px rgba(255, 255, 10, 1);
  text-shadow: 0px 0px 1px rgba(255, 255, 1, 1);
}

.fa {
  color: white;
  cursor: pointer;
  display: block;
}</code>```

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

```

Body:
I have assembled a modal with embedded video using Iframe.
It opens and closes on desktop but does not close on mobile.

Here is the code:

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close");

function toggleModal() {
  modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
  if (event.target === modal) {
    toggleModal();
    var iframe = document.getElementById('demo');
    var iframeSrc = iframe.src;
    iframe.src = iframeSrc;
  }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

img {
  width: 420px;
  height: 345px;
  border-radius: 10px;
}

.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  visibility: hidden;
  transform: scaleX(1.1) scaleY(1.1);
  transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}

.modal-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
}

iframe {
  width: 420px;
  height: 345px;
  border: 0px;
  border-radius: 10px;
  box-shadow: 0 0 20px 0px black;
}

.close-button:hover {
  background-color: darkgray;
}

.show-modal {
  opacity: 1;
  visibility: visible;
  transform: scaleX(1.0) scaleY(1.0);
  transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}

div {
  display: inline-block;
  position: relative;
}

img {
  max-width: 100%;
}

.thumb {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 96px;
  height: 96px;
}

.round-button {
  box-sizing: border-box;
  display: block;
  width: 80px;
  height: 80px;
  padding-top: 14px;
  padding-left: 8px;
  line-height: 20px;
  border: 6px solid #fff;
  border-radius: 50%;
  color: #f5f5f5;
  text-align: center;
  text-decoration: none;
  background-color: #3fa6d9;
  font-size: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.round-button:hover {
  background-color: #2b7dff;
  box-shadow: 0px 0px 1px rgba(255, 255, 10, 1);
  text-shadow: 0px 0px 1px rgba(255, 255, 1, 1);
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

Is there a way to make it work on mobile without using library like Bootstrap?

I just need to be able to close the window with a modal when on mobile phone.

Please help.

Body:
Simple X could solve your issue. I used symbol from font-awesome in given example.

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.getElementById("closediv");

function toggleModal() {
  modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
  if (event.target === modal) {
    toggleModal();
    var iframe = document.getElementById('demo');
    var iframeSrc = iframe.src;
    iframe.src = iframeSrc;
  }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

img {
  width: 420px;
  height: 345px;
  border-radius: 10px;
}

.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  visibility: hidden;
  transform: scaleX(1.1) scaleY(1.1);
  transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}

.modal-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
}

iframe {
  width: 420px;
  height: 345px;
  //border-style: solid;
  //border-width: thin;
  border: 0px;
  border-radius: 10px;
  box-shadow: 0 0 20px 0px black;
}

.close-button:hover {
  background-color: darkgray;
}

.show-modal {
  opacity: 1;
  visibility: visible;
  transform: scaleX(1.0) scaleY(1.0);
  transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}

div {
  display: inline-block;
  position: relative;
}

img {
  max-width: 100%;
}

.thumb {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 96px;
  height: 96px;
  cursor: pointer;
}

.round-button {
  box-sizing: border-box;
  display: block;
  width: 80px;
  height: 80px;
  padding-top: 14px;
  padding-left: 8px;
  line-height: 20px;
  border: 6px solid #fff;
  border-radius: 50%;
  color: #f5f5f5;
  text-align: center;
  text-decoration: none;
  background-color: #3fa6d9;
  font-size: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.round-button:hover {
  background-color: #2b7dff;
  box-shadow: 0px 0px 1px rgba(255, 255, 10, 1);
  text-shadow: 0px 0px 1px rgba(255, 255, 1, 1);
}

.fa {
  color: white;
  cursor: pointer;
  display: block;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<div class="trigger">
  <img src="https://i.ytimg.com/vi/2VLDkNjAUBU/maxresdefault.jpg" />
  <a class="round-button thumb"><i class="fa fa-play fa-2x"></i></a>
</div>
<div class="modal">
  <div class="modal-content" id="closediv">
    <i class="fa fa-times fa-2x " aria-hidden="true"></i>
    <iframe id="demo" src="https://www.youtube.com/embed/-3wlroM2gZ8" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen"></iframe>
  </div>
</div>


问:
How To Populate A Local Table?
I have a stored-procedure that (tries) to assign a table (derived from a query) into a variable called @relation. Here's my current futile attempt:

```<code>ALTER PROCEDURE [dbo].[getAllBookings]
@mode INT
AS
BEGIN
SET NOCOUNT ON;
--==========
DECLARE @relation AS TABLE(
        id INT PRIMARY KEY, code VARCHAR(10), [description] VARCHAR(255),
        environment VARCHAR(10), systems VARCHAR(50), [start] SMALLDATETIME,
        [end] SMALLDATETIME, [user] VARCHAR(50), approved BIT, rejected BIT
    );
SELECT * INTO [@relation] FROM
SELECT
 B_ID AS 'id',
 B_Change_ID AS 'code',
 B_Description AS 'description',
 E_Name AS 'environment',
 S_System_Name AS 'systems',
 dbo.fromDateTime(B_Start_Date) AS 'start',
 dbo.fromDateTime(B_End_Date) AS 'end',
 U_Name AS 'user',
 dbo.isAppr(B_Reviewed, B_Confirmed) AS 'approved',
 dbo.isRej(B_Reviewed, B_Confirmed) AS 'rejected'
FROM ((((dbo.Bookings INNER JOIN dbo.Users ON B_User_ID = U_ID)
INNER JOIN dbo.Environment ON B_Environment_ID = E_ID)
INNER JOIN dbo.BookingApps ON B_ID = BA_bookingID)
INNER JOIN dbo.EnvironmentSystems ON BA_bookingSystemID = ES_ID)
INNER JOIN dbo.System_List ON ES_SystemID = S_ID;

--==========
IF (@mode = 0)
    DELETE FROM @relation WHERE (approved = 0);
SELECT * FROM @relation;
END
</code>```

What am I doing wrong here?

答:
I haven't tried building data and running it, but I had to make the following mods to get it to compile. Perhaps this will help get you started.</p>

```<code>CREATE PROCEDURE [dbo].[getAllBookings] @mode INT
AS
    BEGIN
        SET NOCOUNT ON;

        --==========
        DECLARE @relation AS TABLE
          (
               [id]            INT PRIMARY KEY
               , [code]        VARCHAR(10)
               , [description] VARCHAR(255)
               , [environment] VARCHAR(10)
               , [systems]     VARCHAR(50)
               , [start]       SMALLDATETIME
               , [end]         SMALLDATETIME
               , [user]        VARCHAR(50)
               , [approved]    BIT
               , [rejected]    BIT
          );

        INSERT INTO @relation
                    ([id]
                     , [code]
                     , [description]
                     , [environment]
                     , [systems]
                     , [start]
                     , [end]
                     , [user]
                     , [approved]
                     , [rejected])
            SELECT [B_ID]                                    AS 'id'
                   , [B_Change_ID]                           AS 'code'
                   , [B_Description]                         AS 'description'
                   , [E_Name]                                AS 'environment'
                   , [S_System_Name]                         AS 'systems'
                   , dbo.fromDateTime([B_Start_Date])        AS 'start'
                   , dbo.fromDateTime([B_End_Date])          AS 'end'
                   , [U_Name]                                AS 'user'
                   , dbo.isAppr([B_Reviewed], [B_Confirmed]) AS 'approved'
                   , dbo.isRej([B_Reviewed], [B_Confirmed])  AS 'rejected'
            FROM   dbo.[Bookings]
                   INNER JOIN dbo.[Users]
                           ON [B_User_ID] = [U_ID]
                   INNER JOIN dbo.[Environment]
                           ON [B_Environment_ID] = [E_ID]
                   INNER JOIN dbo.[BookingApps]
                           ON [B_ID] = [BA_bookingID]
                   INNER JOIN dbo.[EnvironmentSystems]
                           ON [BA_bookingSystemID] = [ES_ID]
                   INNER JOIN dbo.[System_List]
                           ON [ES_SystemID] = [S_ID];

        --==========
        IF ( @mode = 0 )
            DELETE FROM @relation
            WHERE  ( [approved] = 0 );

        SELECT *
        FROM   @relation;
    END
</code>```

Title: How To Populate A Local Table?

Body:
I have a stored-procedure that (tries) to assign a table (derived from a query) into a variable called @relation. Here's my current futile attempt:

ALTER PROCEDURE [dbo].[getAllBookings]
@mode INT
AS
BEGIN
SET NOCOUNT ON;
--==========
DECLARE @relation AS TABLE(
        id INT PRIMARY KEY, code VARCHAR(10), [description] VARCHAR(255),
        environment VARCHAR(10), systems VARCHAR(50), [start] SMALLDATETIME,
        [end] SMALLDATETIME, [user] VARCHAR(50), approved BIT, rejected BIT
    );
SELECT * INTO [@relation] FROM
SELECT
 B_ID AS 'id',
 B_Change_ID AS 'code',
 B_Description AS 'description',
 E_Name AS 'environment',
 S_System_Name AS 'systems',
 dbo.fromDateTime(B_Start_Date) AS 'start',
 dbo.fromDateTime(B_End_Date) AS 'end',
 U_Name AS 'user',
 dbo.isAppr(B_Reviewed, B_Confirmed) AS 'approved',
 dbo.isRej(B_Reviewed, B_Confirmed) AS 'rejected'
FROM ((((dbo.Bookings INNER JOIN dbo.Users ON B_User_ID = U_ID)
INNER JOIN dbo.Environment ON B_Environment_ID = E_ID)
INNER JOIN dbo.BookingApps ON B_ID = BA_bookingID)
INNER JOIN dbo.EnvironmentSystems ON BA_bookingSystemID = ES_ID)
INNER JOIN dbo.System_List ON ES_SystemID = S_ID;

--==========
IF (@mode = 0)
    DELETE FROM @relation WHERE (approved = 0);
SELECT * FROM @relation;
END

What am I doing wrong here?

Body:
I haven't tried building data and running it, but I had to make the following mods to get it to compile. Perhaps this will help get you started.

CREATE PROCEDURE [dbo].[getAllBookings] @mode INT
AS
    BEGIN
        SET NOCOUNT ON;

        --==========
        DECLARE @relation AS TABLE
          (
               [id]            INT PRIMARY KEY
               , [code]        VARCHAR(10)
               , [description] VARCHAR(255)
               , [environment] VARCHAR(10)
               , [systems]     VARCHAR(50)
               , [start]       SMALLDATETIME
               , [end]         SMALLDATETIME
               , [user]        VARCHAR(50)
               , [approved]    BIT
               , [rejected]    BIT
          );

        INSERT INTO @relation
                    ([id]
                     , [code]
                     , [description]
                     , [environment]
                     , [systems]
                     , [start]
                     , [end]
                     , [user]
                     , [approved]
                     , [rejected])
            SELECT [B_ID]                                    AS 'id'
                   , [B_Change_ID]                           AS 'code'
                   , [B_Description]                         AS 'description'
                   , [E_Name]                                AS 'environment'
                   , [S_System_Name]                         AS 'systems'
                   , dbo.fromDateTime([B_Start_Date])        AS 'start'
                   , dbo.fromDateTime([B_End_Date])          AS 'end'
                   , [U_Name]                                AS 'user'
                   , dbo.isAppr([B_Reviewed], [B_Confirmed]) AS 'approved'
                   , dbo.isRej([B_Reviewed], [B_Confirmed])  AS 'rejected'
            FROM   dbo.[Bookings]
                   INNER JOIN dbo.[Users]
                           ON [B_User_ID] = [U_ID]
                   INNER JOIN dbo.[Environment]
                           ON [B_Environment_ID] = [E_ID]
                   INNER JOIN dbo.[BookingApps]
                           ON [B_ID] = [BA_bookingID]
                   INNER JOIN dbo.[EnvironmentSystems]
                           ON [BA_bookingSystemID] = [ES_ID]
                   INNER JOIN dbo.[System_List]
                           ON [ES_SystemID] = [S_ID];

        --==========
        IF ( @mode = 0 )
            DELETE FROM @relation
            WHERE  ( [approved] = 0 );

        SELECT *
        FROM   @relation;
    END


问:
how to properly initialize shared resource in kotlintest 2.x (interceptSpec)
I'm trying to do a standard beforeAll/afterAll type setup in the unit tests, but am having some problems.  It seems like the interceptSpec functionality is what I want and the documentation explicitly mentions this is good for e.g. cleaning up database resources, but I can't find a good example. Code below:

```<code>class MyTest : StringSpec() {
    lateinit var foo: String

    override fun interceptSpec(context: Spec, spec: () -> Unit) {
        foo = "foo"
        println("before spec - $foo")
        spec()
        println("after spec - $foo")
    }

    init {
        "some test" {
            println("inside test - $foo")
        }
    }
}
</code>```

This results in the below output:

```<code>before spec - foo
kotlin.UninitializedPropertyAccessException: lateinit property foo has not been initialized
    ... stack trace omitted ...
after spec - foo
</code>```

答:
kotlintest 2.x creates new instance of test case for every test. You can either cancel that behaviour clearing flag:

```<code>override val oneInstancePerTest = false
</code>```

Or explicitly add your interceptors to test:

```<code>val withFoo: (TestCaseContext, () -> Unit) -> Unit = { context, spec ->
    foo = "foo"
    spec()
}

init {
    "some test" {
        println("inside test - $foo")
    }.config(interceptors = listOf(withFoo))
}
</code>```

Body:
I'm trying to do a standard beforeAll/afterAll type setup in the unit tests, but am having some problems.  It seems like the interceptSpec functionality is what I want and the documentation explicitly mentions this is good for e.g. cleaning up database resources, but I can't find a good example. Code below:

class MyTest : StringSpec() {
    lateinit var foo: String

    override fun interceptSpec(context: Spec, spec: () -> Unit) {
        foo = "foo"
        println("before spec - $foo")
        spec()
        println("after spec - $foo")
    }

    init {
        "some test" {
            println("inside test - $foo")
        }
    }
}

This results in the below output:

before spec - foo
kotlin.UninitializedPropertyAccessException: lateinit property foo has not been initialized
    ... stack trace omitted ...
after spec - foo

Body:
kotlintest 2.x creates new instance of test case for every test. You can either cancel that behaviour clearing flag:

override val oneInstancePerTest = false

Or explicitly add your interceptors to test:

val withFoo: (TestCaseContext, () -> Unit) -> Unit = { context, spec ->
    foo = "foo"
    spec()
}

init {
    "some test" {
        println("inside test - $foo")
    }.config(interceptors = listOf(withFoo))
}


问:
Where is my Google Apps Script
I'm getting "Summary of failures for Google Apps Script" emails and I don't have any Apps Scripts in my Drive.  Where can I find any scripts that might be running (or trying to run) that are not in my Drive?</p>

答: The "Summary of failures for Google Apps Script" includes a link to the file holding the related script. Read it carefully.</p>

Title: Where is my Google Apps Script


问:
Does ActiveX control need thread synchronization?
I'm currently developing a simple ActiveX control. This control exposes a small set of properties and methods. It is not known now if the ActiveX methods will be called from different threads.
In order to be ready to face this scenario I decided to implement a thread synchronization inside each methods exposed by the control.
Do I need to implement this synchronization or it is already implemented by the Microsoft ActiveX framework?
Am I doing something redundant?</p>

答:
How this works depends on what threading model your control uses, but assuming your ActiveX control uses the "APARTMENT" threading model (which it nearly always should) you can assume that all methods on your ActiveX control will be called on the same thread.  If other threads access them ActiveX will automatically marshall the call to the correct thread so that you receive it on that thread.

By the same token, you must never make calls on an ActiveX object or COM interface that you use from a thread other than the one you obtained it on.  If you need to make calls from multiple threads there are ways of doing that, but that's outside of the scope of this question.

Summary: You don't have to worry about your methods being called from different threads, so you shouldn't need to worry about synchronization.


问:
Error: ENOENT: no such file or directory, scandir
I scaffold an app using jhipster which is microservice gateway using cassandra db and using maven to build which was building fine after scaffold.i ran gulp command to for the live reload of ui.

i made a change slighlty in navbar and home page of it.
which was also working file & made some changes in the json files of home & navbar & do some minor changes as adding the search box and other.

it failed to reload. I stop the gulp & maven & restarted them.
maven is building but again not loading the site in localhost

when i ran gulp it is showing me this error.

```<code> gulp
fs.js:952
  return binding.readdir(pathModule._makeLong(path), options.encoding);
                 ^

Error: ENOENT: no such file or directory, scandir '/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/vendor'
    at Error (native)
    at Object.fs.readdirSync (fs.js:952:18)
    at Object.getInstalledBinaries (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/extensions.js:121:13)
    at foundBinariesList (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/errors.js:20:15)
    at foundBinaries (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/errors.js:15:5)
    at Object.module.exports.missingBinary (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/errors.js:45:5)
    at module.exports (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/binding.js:15:30)
    at Object.<anonymous> (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/index.js:14:35)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
</code>```

Could anyone tell me solution for this

答:
The vendor directory is created during npm install. Try deleting your
node_modules and running npm install.

Body:
I scaffold an app using jhipster which is microservice gateway using cassandra db and using maven to build which was building fine after scaffold.i ran gulp command to for the live reload of ui.

i made a change slighlty in navbar and home page of it.
which was also working file & made some changes in the json files of home & navbar & do some minor changes as adding the search box and other.

it failed to reload. I stop the gulp & maven & restarted them.
maven is building but again not loading the site in localhost

when i ran gulp it is showing me this error.

 gulp
fs.js:952
  return binding.readdir(pathModule._makeLong(path), options.encoding);
                 ^

Error: ENOENT: no such file or directory, scandir '/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/vendor'
    at Error (native)
    at Object.fs.readdirSync (fs.js:952:18)
    at Object.getInstalledBinaries (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/extensions.js:121:13)
    at foundBinariesList (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/errors.js:20:15)
    at foundBinaries (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/errors.js:15:5)
    at Object.module.exports.missingBinary (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/errors.js:45:5)
    at module.exports (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/binding.js:15:30)
    at Object.<anonymous> (/home/hartron/foodnetteam/codebase/mandi/node_modules/node-sass/lib/index.js:14:35)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)

Could anyone tell me solution for this


问:
Trying to write to a mysql database but it keeps coming up empty set
For a school project I am trying to write to a table called enrolment where the student number and the course they have selected are added after they have been tested to make sure the student name and number exists in another database. No errors are coming up, however when I check my database afterward enrolment says its an empty set. Does anyone have suggestions?

```<code><?php

require 'connect.php';

//making a variable from the user data
$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];

//linking up the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());

// select all from table student which show student name and number
$squery = "SELECT * FROM student";
$sresult = mysqli_query($link, $squery);

$found = 0;

while ($srow = mysqli_fetch_array($sresult)) {

    // testing if the student name and number match the users data
    if ($name == $srow['family'] && $number == $srow['uid']) {

        $enrol = "INSERT INTO enrolment (uid course) VALUES('$number' '$course')";
        $found = 1;
        break;
    }
}
mysqli_close($link);

?>

<html>
    <body>
        <form action="index.php" method="post">
            <br>
            <input type = "submit" value="back" name="back">
        </form>
    </body>
</html>
</code>```

index.php (form)

```<code><!DOCTYPE html>
<html>
  <body>
    <h1>Course Selection</h1><br>

    <form action="next.php" method="post">

              Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">
              <br><br>

              Student Number: <input type="text" name= "snumber" required="required" maxlength="9">
              <br><br>

        <?php
        //form
      require 'connect.php';

       echo "Select a course: <select name = \"pcourse\">\n";

      $link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());

      $query = "SELECT * FROM course";
      $result = mysqli_query($link, $query);

      while ($row = mysqli_fetch_array($result)) {
        echo "<option> $row[code] $row[name] $row[maxenroll]</option><br>";
      }

      mysqli_free_result($results);

      mysqli_close ($link);

      echo " </select>\n";

      ?>

      <br><br>
      <input type = "submit" value="submit" name= "submit">

    </form>

    </body>
    </html>
</code>```

答:
My guess is that when checking the result set from student table - there is no such family and uid in it, which means - in the table. Instead of doing insert right away, try to display matching record from the database - if this is actually what you wanted to find. Then you can check what is actually stored in the database - and you can compare both.

Other thing is - why not limit select to exact that student?

Rebuild your query, something like:

$squery = "select * from student where family='".$name."' and uid='".$number."'".

Then you can check how many records were selected and display that number before doing any inserts.

Body:
For a school project I am trying to write to a table called enrolment where the student number and the course they have selected are added after they have been tested to make sure the student name and number exists in another database. No errors are coming up, however when I check my database afterward enrolment says its an empty set. Does anyone have suggestions?

<?php

require 'connect.php';

//making a variable from the user data
$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];

//linking up the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());

// select all from table student which show student name and number
$squery = "SELECT * FROM student";
$sresult = mysqli_query($link, $squery);

$found = 0;

while ($srow = mysqli_fetch_array($sresult)) {

    // testing if the student name and number match the users data
    if ($name == $srow['family'] && $number == $srow['uid']) {

        $enrol = "INSERT INTO enrolment (uid course) VALUES('$number' '$course')";
        $found = 1;
        break;
    }
}
mysqli_close($link);

?>

        <form action="index.php" method="post">

            <input type = "submit" value="back" name="back">
        </form>

index.php (form)

<!DOCTYPE html>

Course Selection

    <form action="next.php" method="post">

              Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">

              Student Number: <input type="text" name= "snumber" required="required" maxlength="9">

        <?php
        //form
      require 'connect.php';

       echo "Select a course: <select name = \"pcourse\">\n";

      $link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());

      $query = "SELECT * FROM course";
      $result = mysqli_query($link, $query);

      while ($row = mysqli_fetch_array($result)) {
        echo "<option> $row[code] $row[name] $row[maxenroll]</option>
";
      }

      mysqli_free_result($results);

      mysqli_close ($link);

      echo " </select>\n";

      ?>

      <input type = "submit" value="submit" name= "submit">

    </form>


答:
years = [n[1] for n in data] - years is now a list, each element is index [1] of an element in data

for n in data:
         years = n[1]

years is a single object and is always updated with n[1] and will finally be index [1] of the last element in data

Title: For loop in python - beginner


问:
How to immediately re-render client-side using React + NextJS after initial server-side render?
I created a website using Next.js with React and really like to declare a js variable to define component styles like this:

```<code>const foo = {
  fontSize: '12px',
};
</code>```

And in the render method I do:

```<code>render() {
  return (
    <div style={foo}>bar</div>
  );
}
</code>```

Using ESLint I can quickly find unused styles/variables (if references are gone) and keep the code clean. Hence I do not use

bar

  );
}
```

The problem

The problem with using only js variables instead of

答:
Found the solution to this. NextJS will automatically re-render client-side after doing server-side render. Adding some console output shows this:

```<code>const foo = {
  fontSize: '12px',
};
</code>```

Render method:

```<code>render() {
  if (windowWidth < 768) {
    foo.fontSize = '24px';
    console.log('24px');
  } else {
    console.log('12px');
  }

  return (
    <div style={foo}>bar</div>
  );
}
</code>```

Viewing on a small screen, this will print:

```<code>12px
24px
</code>```

However, pressing the browser's reload button, the font size doesn't change although the value of the style variable clearly changed.

The solution was to create a copy of the original object and manipulate that instead:

```<code>render() {
  let foo2;
  if (windowWidth < 768) {
    foo2 = Object.assign({}, foo, { fontSize: '24px' });
  } else {
    foo2 = Object.assign({}, foo);
  }

  return (
    <div style={foo2}>bar</div>
  );
}
</code>```

This will change the font size during runtime. However, when the page loads you will see the old 12px font size for the fraction of a second and when client-side render has finished, it will jump to the new font size of 24px. Not sure if I will go with this from a UX perspective but technically this is a working solution. Don't really like it though :-(

Body:
I created a website using Next.js with React and really like to declare a js variable to define component styles like this:

const foo = {
  fontSize: '12px',
};

And in the render method I do:

render() {
  return (

bar

  );
}

Using ESLint I can quickly find unused styles/variables (if references are gone) and keep the code clean. Hence I do not use

bar

  );
}

The problem

The problem with using only js variables instead of

Body:
Found the solution to this. NextJS will automatically re-render client-side after doing server-side render. Adding some console output shows this:

const foo = {
  fontSize: '12px',
};

Render method:

render() {
  if (windowWidth < 768) {
    foo.fontSize = '24px';
    console.log('24px');
  } else {
    console.log('12px');
  }

  return (
    <div style={foo}>bar</div>
  );
}

Viewing on a small screen, this will print:

12px
24px

However, pressing the browser's reload button, the font size doesn't change although the value of the style variable clearly changed.

The solution was to create a copy of the original object and manipulate that instead:

render() {
  let foo2;
  if (windowWidth < 768) {
    foo2 = Object.assign({}, foo, { fontSize: '24px' });
  } else {
    foo2 = Object.assign({}, foo);
  }

  return (
    <div style={foo2}>bar</div>
  );
}

This will change the font size during runtime. However, when the page loads you will see the old 12px font size for the fraction of a second and when client-side render has finished, it will jump to the new font size of 24px. Not sure if I will go with this from a UX perspective but technically this is a working solution. Don't really like it though :-(


问:
Valet and Laravel 5.5 Access denied for user 'root'@'localhost'
I just started a new project and I use Valet for all my new projects. I also use a mysql DB that is installed on my local machine. It works on all my old projects using Laravel 5.4, 5.3 and 5.2. For some reason, I get this error.

```<code>SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from `users` where `email` = john.doe@example.com limit 1)
</code>```

My .env file looks like this.

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=new_project
DB_USERNAME=root
DB_PASSWORD=
</code>```

And as I said before, this works on all my old projects.

If I run tinker and for example run a simple call to the database, the connection works. So this error is only in the browser.

```<code>$users = App\User::all();
=> Illuminate\Database\Eloquent\Collection {#752
     all: [],
   }
</code>```

Any clues?

答:
Try to clear cache:

```<code>php artisan config:cache
</code>```

Laravel can remember old database credentials

Body:
I just started a new project and I use Valet for all my new projects. I also use a mysql DB that is installed on my local machine. It works on all my old projects using Laravel 5.4, 5.3 and 5.2. For some reason, I get this error.

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from `users` where `email` = john.doe@example.com limit 1)

My .env file looks like this.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=new_project
DB_USERNAME=root
DB_PASSWORD=

And as I said before, this works on all my old projects.

If I run tinker and for example run a simple call to the database, the connection works. So this error is only in the browser.

$users = App\User::all();
=> Illuminate\Database\Eloquent\Collection {#752
     all: [],
   }

Any clues?

Body:
Try to clear cache:

php artisan config:cache

Laravel can remember old database credentials


问:
How to set lang="en" outside
I have a site that is based on the Smoolis platform.

On the site, I'm validating my code and I am mostly done.
However, W3C Validator gives me a warning that I need to set my lang="en"

https://validator.w3.org/nu/?doc=http%3A%2F%2Fmax2006.smoolis.com%2F

I'm unable to access the  tag due to the restrictions of the platform.
As such, I have tried using a  ...  around the main body text, but to no avail in removing the warning (presumably because I can still not access all of the material on page via this method.

Is there a way to set the overall page language without accessing the  tag - in a way that W3C will accept?

Or should I just ignore this issue? (seems Smoolis does try to set the language via other methods, but just not getting accepted by W3C).

Thank you!

答:
Change your opening HTML tag like below.

```<code><html>
</code>```

to

```<code><html lang="en">
</code>```

This will remove the below warning from W3C Validator.

Warning: This document appears to be written in English. Consider adding lang="en" (or variant) to the html start tag"

Title: How to set lang="en" outside <HTML>

Body:
Change your opening HTML tag like below.

<html>

to

<html lang="en">

This will remove the below warning from W3C Validator.

Warning: This document appears to be written in English. Consider adding lang="en" (or variant) to the html start tag"