问:
Gulp- Watchify does not detect changes to a submodule folder
My watchify-program does not detect changes in a sub-module.

The submodule is situated in ../js/lib/melajs/**/*.js

When I run browserify-program it does however compile the submodule.

Below are the two tasks.

```<code>programAppjs: pathsBase+"js/app.js",

gulp.task("browserify-program",function(){
    //appname global variable set in previous task
    return browserify([paths.programAppjs])
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./public/js'));
});

gulp.task("watchify-program",function(){
    var b = browserify({
        entries: [paths.programAppjs],
        cache: {},
        packageCache: {},
        plugin: [watchify]
    });

    b.on('update', bundle);
    b.on('log', function (msg) {console.log(time()+" "+ appname+" "+msg);})
    bundle();

    function bundle() {
        b.bundle().pipe(fs.createWriteStream('./public/js/bundle.js'));
    }
});
</code>```

app.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import Login from './components/auth/login';
import Logout from './components/auth/logout';
import NotFound from './components/common/NotFound';
import RequireAuth from './components/auth/require_auth'; //HOC - Higher Order Component
import AppHeader from './components/common/AppHeader';
import Dashboard from './components/Dashboard/Dashboard';
import Reports from './components/Reports';
import Settings from './components/settings/Settings';
import Customisation from './components/customisation/Customisation';
import PatientsListing from './components/PatientsListing';
import Patient from './components/patient/Patient';
import AssessmentContent from './components/patient/Assessments/AssessmentContent';
import Login_Patient from './components/auth/login_patient';
import PatientQuestionnaireListing from './components/patient/questionnaire/PatientQuestionnaireListing';

import * as actions from  './actions';
import { SET_PATHS, CHECK_CONNECTION_STATUS } from './actions/types';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

actions.getPaths(renderApp);

function renderApp(paths) {
    store.dispatch({
        type: CHECK_CONNECTION_STATUS,
        payload: true,
    });

    store.dispatch({
        type: SET_PATHS,
        payload: paths,
    });

    ReactDOM.render(
        <Provider store={store}>
            <BrowserRouter>
                <div>
                    <AppHeader />
                    <div style={{marginTop:30}}>
                    <Switch >
                        <Route exact path={`${paths.appUrl}/login`} component={Login} />
                        <Route exact path={`${paths.appUrl}/logout`} component={Logout} />

                        <Route exact path={`${paths.appUrl}/`} component={RequireAuth(Dashboard)} />
                        <Route exact path={`${paths.appUrl}/reports`} component={ RequireAuth(Reports) } />
                        <Route exact path={`${paths.appUrl}/settings`} component={ RequireAuth(Settings) } />
                        <Route exact path={`${paths.appUrl}/customisation`} component={ RequireAuth(Customisation) } />
                        <Route exact path={`${paths.appUrl}/listing`} component={ RequireAuth(PatientsListing) } />
                        <Route exact path={`${paths.appUrl}/view/:type/:start/:end`} component={ RequireAuth(PatientsListing) } />
                        <Route exact path={`${paths.appUrl}/patient/:admissionId`} component={ RequireAuth(Patient) } />
                        <Route exact path={`${paths.appUrl}/patient/:admissionId/assessment/:assessmentId`} component={ RequireAuth(AssessmentContent) } />

                        {/*QUESTIONNAIRE*/}
                        <Route exact path={`${paths.appUrl}/login_patient`} component={Login_Patient} />
                        <Route exact path={`${paths.appUrl}/patient_questionnaire_listing`} component={PatientQuestionnaireListing} />

                        <Route component={ NotFound } />

                    </Switch>
                    </div>
                </div>
            </BrowserRouter>
        </Provider>
      , document.getElementById('main_app_div')
    );
}
</code>```

PeriodForm.js

```<code>import React, {Component} from 'react';
import { reduxForm, Field, getFormValues } from 'redux-form';
import { Row, Col, Button, Table, Glyphicon } from 'react-bootstrap';
import { connect } from 'react-redux';
import * as actions from '../_actions/actions';
import { withRouter } from 'react-router-dom';
import _ from 'lodash';
import moment from 'moment';
import { getList } from '../../../../../helpers/listHelper';
import { renderDropdownList } from '../../../../../helpers/forms';
import { getListFromState } from '../_helpers/listHandler';

class PeriodForm extends Component {
.
.
.
}
</code>```

答:
I think that your code is correct. It should be related with the required files in your app.js.

Here is a working demo demo repo

If you post part of your app.js probably I can help you more.

Body:
My watchify-program does not detect changes in a sub-module.

The submodule is situated in ../js/lib/melajs/**/*.js

When I run browserify-program it does however compile the submodule.

Below are the two tasks.

programAppjs: pathsBase+"js/app.js",

gulp.task("browserify-program",function(){
    //appname global variable set in previous task
    return browserify([paths.programAppjs])
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./public/js'));
});

gulp.task("watchify-program",function(){
    var b = browserify({
        entries: [paths.programAppjs],
        cache: {},
        packageCache: {},
        plugin: [watchify]
    });

    b.on('update', bundle);
    b.on('log', function (msg) {console.log(time()+" "+ appname+" "+msg);})
    bundle();

    function bundle() {
        b.bundle().pipe(fs.createWriteStream('./public/js/bundle.js'));
    }
});

app.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import Login from './components/auth/login';
import Logout from './components/auth/logout';
import NotFound from './components/common/NotFound';
import RequireAuth from './components/auth/require_auth'; //HOC - Higher Order Component
import AppHeader from './components/common/AppHeader';
import Dashboard from './components/Dashboard/Dashboard';
import Reports from './components/Reports';
import Settings from './components/settings/Settings';
import Customisation from './components/customisation/Customisation';
import PatientsListing from './components/PatientsListing';
import Patient from './components/patient/Patient';
import AssessmentContent from './components/patient/Assessments/AssessmentContent';
import Login_Patient from './components/auth/login_patient';
import PatientQuestionnaireListing from './components/patient/questionnaire/PatientQuestionnaireListing';

import * as actions from  './actions';
import { SET_PATHS, CHECK_CONNECTION_STATUS } from './actions/types';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

actions.getPaths(renderApp);

function renderApp(paths) {
    store.dispatch({
        type: CHECK_CONNECTION_STATUS,
        payload: true,
    });

    store.dispatch({
        type: SET_PATHS,
        payload: paths,
    });

    ReactDOM.render(
        <Provider store={store}>
            <BrowserRouter>

                    <AppHeader />

                    <Switch >
                        <Route exact path={`${paths.appUrl}/login`} component={Login} />
                        <Route exact path={`${paths.appUrl}/logout`} component={Logout} />

                        <Route exact path={`${paths.appUrl}/`} component={RequireAuth(Dashboard)} />
                        <Route exact path={`${paths.appUrl}/reports`} component={ RequireAuth(Reports) } />
                        <Route exact path={`${paths.appUrl}/settings`} component={ RequireAuth(Settings) } />
                        <Route exact path={`${paths.appUrl}/customisation`} component={ RequireAuth(Customisation) } />
                        <Route exact path={`${paths.appUrl}/listing`} component={ RequireAuth(PatientsListing) } />
                        <Route exact path={`${paths.appUrl}/view/:type/:start/:end`} component={ RequireAuth(PatientsListing) } />
                        <Route exact path={`${paths.appUrl}/patient/:admissionId`} component={ RequireAuth(Patient) } />
                        <Route exact path={`${paths.appUrl}/patient/:admissionId/assessment/:assessmentId`} component={ RequireAuth(AssessmentContent) } />

                        {/*QUESTIONNAIRE*/}
                        <Route exact path={`${paths.appUrl}/login_patient`} component={Login_Patient} />
                        <Route exact path={`${paths.appUrl}/patient_questionnaire_listing`} component={PatientQuestionnaireListing} />

                        <Route component={ NotFound } />

                    </Switch>

            </BrowserRouter>
        </Provider>
      , document.getElementById('main_app_div')
    );
}

PeriodForm.js

import React, {Component} from 'react';
import { reduxForm, Field, getFormValues } from 'redux-form';
import { Row, Col, Button, Table, Glyphicon } from 'react-bootstrap';
import { connect } from 'react-redux';
import * as actions from '../_actions/actions';
import { withRouter } from 'react-router-dom';
import _ from 'lodash';
import moment from 'moment';
import { getList } from '../../../../../helpers/listHelper';
import { renderDropdownList } from '../../../../../helpers/forms';
import { getListFromState } from '../_helpers/listHandler';

class PeriodForm extends Component {
.
.
.
}


来源: stackexchange

问:
Powershell New-PSSession Access Denied - Administrator Account
I try to use powershell PSSession cmdlets, but I'm struggling with Access Denied Error.

What I try to do is using Administrator Account I run command New-PSSession (or Enter-PSSession) and unfortunately I receive Access Denied Error.

I follow all the instructions correctly I believe, cause on the other server I can run those commands with no troubles.

In addition I'd like to inform that test-wsman return me an response. I'm using Built-In Administrator Account and already checked Set-PSSessionConfiguration -Name Microsoft.PowerShell -ShowSecurityDescriptorUI
All the privileges seems to be ok. I have no more ideas, looking for help.

UPDATE

I found one interesting behaviour:

Let's assume that:

IP Address of machine is 22.222.222.222

I log via remote desktop using Administrator Credentials

I use following commands:

```<code>new-pssession // access denied

new-pssession localhost // access denied

new-pssession 127.0.0.1 // access denied

new-pssession 22.222.222.222 // Session created ! It's working !

new-pssession 22.222.222.222 -Credential Get-Credential // access denied (using the same administrator credentials which I'm using for RDP)
</code>```

I can add that on the other server when I run exactly the same commands all commands are successful.

Any Ideas?

答:
There is a possible answer to this at the end, but a bit of background may help so I'm starting with that.

Intro

It is important to note that my answer is only related to loopback (localhost) sessions. It does not address problems with remote sessions.

Loopback sessions are useful as they enable a user with administrator rights to invoke user commands or scripts on the local host. An example of this is a toast message to a logged in user from a system monitoring program run under the System user. (Yes, there may be better ways of doing this but that's not what is being discussed here).

Background

I had exactly the same problem with exactly the same results as what is shown in the updates section of @Piotr's original question. I searched extensively on Google for an answer, but this yielded no working answers—even though a few people were reporting very similar issues.

Specs

As most people using Powershell remoting seem to not have this problem, it may be related to my machine's specs:

Windows 10 Home Version 1803.

Private network using WiFi connection

```<code>PS Env:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17134.858
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17134.858
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
</code>```

Possible Answer

The EnableNetworkAccess option worked for me, but I don't know why yet. It is confirmed to work for the PowerShell commands New-PSSession and Invoke-Command, and may work for others as well.

Examples

To configure PowerShell remoting, the following command is needed once—though it
will not harm anything if it is repeated. It will only work on private (not public) networks.

```<code>PS Env:\> Enable-PSRemoting -force
</code>```

The following examples don't require an entry in Trusted Hosts.

LAPTOP-XZ is the computer name == $env:COMPUTERNAME

. = dot alias for localhost

```<code>Invoke-Command -ComputerName . -ScriptBlock { dir } -EnableNetworkAccess

New-PSSession -EnableNetworkAccess
New-PSSession localhost -EnableNetworkAccess
New-PSSession 127.0.0.1 -EnableNetworkAccess
New-PSSession LAPTOP-XZ -EnableNetworkAccess
</code>```

The IPv4 Address of the computer (192.168.1.103, in my case) will only work if it is included in Trusted Hosts. The EnableNetworkAccess option isn't needed in this case.

```<code>PS Env:\> Set-Item WSMan:\localhost\Client\TrustedHosts -Value "192.168.1.103"

New-PSSession 192.168.1.103
</code>```

Note that including localhost and its other aliases in Trusted Hosts doesn't work in the above example (-EnableNetworkAccess is needed).

ContentLicense: CC BY-SA 3.0

Body:
I try to use powershell PSSession cmdlets, but I'm struggling with Access Denied Error.

What I try to do is using Administrator Account I run command New-PSSession (or Enter-PSSession) and unfortunately I receive Access Denied Error.

I follow all the instructions correctly I believe, cause on the other server I can run those commands with no troubles.

In addition I'd like to inform that test-wsman return me an response. I'm using Built-In Administrator Account and already checked Set-PSSessionConfiguration -Name Microsoft.PowerShell -ShowSecurityDescriptorUI
All the privileges seems to be ok. I have no more ideas, looking for help.

UPDATE

I found one interesting behaviour:

Let's assume that:

IP Address of machine is 22.222.222.222

I log via remote desktop using Administrator Credentials

I use following commands:

new-pssession // access denied

new-pssession localhost // access denied

new-pssession 127.0.0.1 // access denied

new-pssession 22.222.222.222 // Session created ! It's working !

new-pssession 22.222.222.222 -Credential Get-Credential // access denied (using the same administrator credentials which I'm using for RDP)

I can add that on the other server when I run exactly the same commands all commands are successful.

Any Ideas?

Body:
There is a possible answer to this at the end, but a bit of background may help so I'm starting with that.

Intro

It is important to note that my answer is only related to loopback (localhost) sessions. It does not address problems with remote sessions.

Loopback sessions are useful as they enable a user with administrator rights to invoke user commands or scripts on the local host. An example of this is a toast message to a logged in user from a system monitoring program run under the System user. (Yes, there may be better ways of doing this but that's not what is being discussed here).

Background

I had exactly the same problem with exactly the same results as what is shown in the updates section of @Piotr's original question. I searched extensively on Google for an answer, but this yielded no working answers—even though a few people were reporting very similar issues.

Specs

As most people using Powershell remoting seem to not have this problem, it may be related to my machine's specs:

Windows 10 Home Version 1803.

Private network using WiFi connection

PS Env:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17134.858
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17134.858
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Possible Answer

The EnableNetworkAccess option worked for me, but I don't know why yet. It is confirmed to work for the PowerShell commands New-PSSession and Invoke-Command, and may work for others as well.

Examples

To configure PowerShell remoting, the following command is needed once—though it
will not harm anything if it is repeated. It will only work on private (not public) networks.

PS Env:\> Enable-PSRemoting -force

The following examples don't require an entry in Trusted Hosts.

LAPTOP-XZ is the computer name == $env:COMPUTERNAME

. = dot alias for localhost

Invoke-Command -ComputerName . -ScriptBlock { dir } -EnableNetworkAccess

New-PSSession -EnableNetworkAccess
New-PSSession localhost -EnableNetworkAccess
New-PSSession 127.0.0.1 -EnableNetworkAccess
New-PSSession LAPTOP-XZ -EnableNetworkAccess

The IPv4 Address of the computer (192.168.1.103, in my case) will only work if it is included in Trusted Hosts. The EnableNetworkAccess option isn't needed in this case.

PS Env:\> Set-Item WSMan:\localhost\Client\TrustedHosts -Value "192.168.1.103"

New-PSSession 192.168.1.103

Note that including localhost and its other aliases in Trusted Hosts doesn't work in the above example (-EnableNetworkAccess is needed).

ContentLicense: CC BY-SA 4.0


问:
use parent schema value as default value of child schema in mongoose
```<code>const ParentSchema = new Schema({
    key1: {type: String, required: true},
    key2: {type: String, required: true},
    child: {type: [ChildSchema], default: ChildSchema}
})

const ChildSchema = new Schema({
    key3: {type: String, default: '**Value of Key1**'},
    key4: {type: String}
})
</code>```

Here I have two schemas one is a parent schema and another one is child schema, I want to set Key1 value as a default value of Key3. Key1 value is a dynamic value that will be entered by the user.

Thanks in advance.

答:
You can try using Mongoose population.

```<code>const ParentSchema = new Schema({
    key1: {type: String, required: true},
    key2: {type: String, required: true}
})

const ChildSchema = new Schema({
    key3: { type: Schema.Types.ObjectId, ref: 'ParentSchema' }
    key4: {type: String}
})
</code>```

Then, you can populate ChildSchema like this:

```<code>ChildSchema.
  findById(someId).
  populate('key3', 'key1').
  exec(errorHandlingCb);
</code>```

For detail implementation see here.

Body:
const ParentSchema = new Schema({
    key1: {type: String, required: true},
    key2: {type: String, required: true},
    child: {type: [ChildSchema], default: ChildSchema}
})

const ChildSchema = new Schema({
    key3: {type: String, default: '**Value of Key1**'},
    key4: {type: String}
})

Here I have two schemas one is a parent schema and another one is child schema, I want to set Key1 value as a default value of Key3. Key1 value is a dynamic value that will be entered by the user.

Thanks in advance.

Body:
You can try using Mongoose population.

const ParentSchema = new Schema({
    key1: {type: String, required: true},
    key2: {type: String, required: true}
})

const ChildSchema = new Schema({
    key3: { type: Schema.Types.ObjectId, ref: 'ParentSchema' }
    key4: {type: String}
})

Then, you can populate ChildSchema like this:

ChildSchema.
  findById(someId).
  populate('key3', 'key1').
  exec(errorHandlingCb);

For detail implementation see here.


问:
Select multiple columns from MySql to Java
I have a MySql database which contains a VARCHAR field (called nev here) and a couple INTs

What I want is select all of the integers which columns contains 'w' (w0, w1 etc) and put it into an array or an ArrayList. And also select those which has 'b' in the columns. And I want to only select those values whose has a specific 'nev' which comes from another class.

Here is my code so far:

```<code>public static Connection qry(){
        Connection qry=null;
        try {
           qry=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/feladat","admin","admin");
           String query ="SELECT * FROM pontszamok WHERE nev="+GUI.selected;
           Statement st2;
           st2 = qry.createStatement();
           ResultSet rs = st2.executeQuery(query);

            while (rs.next())
            {

            }
            st2.close();
        } catch (SQLException e) {
            System.out.println(e);
        }
        return qry;
</code>```

What should be the solution?

答:
If the column is int type, you can get them by

```<code>rs.getInt("column-name");
</code>```

Body:
I have a MySql database which contains a VARCHAR field (called nev here) and a couple INTs

What I want is select all of the integers which columns contains 'w' (w0, w1 etc) and put it into an array or an ArrayList. And also select those which has 'b' in the columns. And I want to only select those values whose has a specific 'nev' which comes from another class.

Here is my code so far:

public static Connection qry(){
        Connection qry=null;
        try {
           qry=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/feladat","admin","admin");
           String query ="SELECT * FROM pontszamok WHERE nev="+GUI.selected;
           Statement st2;
           st2 = qry.createStatement();
           ResultSet rs = st2.executeQuery(query);

            while (rs.next())
            {

            }
            st2.close();
        } catch (SQLException e) {
            System.out.println(e);
        }
        return qry;

What should be the solution?

Body:
If the column is int type, you can get them by

rs.getInt("column-name");


问:
How to make flexbox with cross axis overflow have the same height?
A flex container contains two columns, and the first column could be with any height, so I manually set the height of the container and set overflow: auto.

What I expected is the right empty div would have the same height as the left sss box. It's true they have the same height, however it's due to the shrinked height of the left sss box.(The same height as the container 100px)

.c {
  display: flex;
  width: 400px;
  height: 100px;
  overflow: auto;
  flex-wrap: nowrap;
}

.empty {
  background-color: red;
  border: 1px solid;
  flex: 1;
}

.sss {
  border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div class="sss">
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
  </div>
  <div class="empty">
  </div>
</div></code>```

I set margin-top: auto in the left box, now the height is back to normal (exactly the sum height of all sss) while the height of the empty box still remain the same.

.c {
  display: flex;
  width: 400px;
  height: 100px;
  overflow: auto;
  flex-wrap: nowrap;
}

.empty {
  background-color: red;
  border: 1px solid;
  flex: 1;
}

.sss {
  margin-bottom: auto;
  border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div class="sss">
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
  </div>
  <div class="empty">
  </div>
</div></code>```

Then I set flex-wrap: wrap and it worked, however I don't want them to be wrapped when the width is not enough.

Also, I tried to wrap these two columns in a table and the result is the same as flex-nowrap.

.c {
  display: flex;
  width: 400px;
  height: 100px;
  overflow: auto;
  flex-wrap: wrap;
}

.empty {
  background-color: red;
  border: 1px solid;
  flex: 1;
}

.sss {
  border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div class="sss">
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
  </div>
  <div class="empty">
  </div>
</div></code>```

答:
Use CSS grid instead:

.c {
  display: grid;
  grid-template-columns:auto 1fr;
  width: 400px;
  height: 100px;
  overflow: auto;
}

.empty {
  background-color: red;
  border: 1px solid;
}

.sss {
  border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div class="sss">
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
  </div>
  <div class="empty">
  </div>
</div></code>```

Body:
A flex container contains two columns, and the first column could be with any height, so I manually set the height of the container and set overflow: auto.

What I expected is the right empty div would have the same height as the left sss box. It's true they have the same height, however it's due to the shrinked height of the left sss box.(The same height as the container 100px)

.c {
  display: flex;
  width: 400px;
  height: 100px;
  overflow: auto;
  flex-wrap: nowrap;
}

.empty {
  background-color: red;
  border: 1px solid;
  flex: 1;
}

.sss {
  border: 1px solid;
}

sssss

sssss

sssss

sssss

sssss

I set margin-top: auto in the left box, now the height is back to normal (exactly the sum height of all sss) while the height of the empty box still remain the same.

.c {
  display: flex;
  width: 400px;
  height: 100px;
  overflow: auto;
  flex-wrap: nowrap;
}

.empty {
  background-color: red;
  border: 1px solid;
  flex: 1;
}

.sss {
  margin-bottom: auto;
  border: 1px solid;
}

sssss

sssss

sssss

sssss

sssss

Then I set flex-wrap: wrap and it worked, however I don't want them to be wrapped when the width is not enough.

Also, I tried to wrap these two columns in a table and the result is the same as flex-nowrap.

.c {
  display: flex;
  width: 400px;
  height: 100px;
  overflow: auto;
  flex-wrap: wrap;
}

.empty {
  background-color: red;
  border: 1px solid;
  flex: 1;
}

.sss {
  border: 1px solid;
}

sssss

sssss

sssss

sssss

sssss

Body:
Use CSS grid instead:

.c {
  display: grid;
  grid-template-columns:auto 1fr;
  width: 400px;
  height: 100px;
  overflow: auto;
}

.empty {
  background-color: red;
  border: 1px solid;
}

.sss {
  border: 1px solid;
}

<div class="c">
  <div class="sss">
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
    <p>sssss</p>
  </div>
  <div class="empty">
  </div>
</div>


问:
Is JRuby ready for production?
I just found out about JRuby, and I like the idea of running Ruby on Rails and being able to call Java libraries.

I would like to know about some experiences with running enterprise production applications in JRuby. Are stability and performance acceptable?

Thanks.

答:
Jason Seifer says yes. His presentation on Ruby VM's is on InfoQ.

A look at the different Ruby virtual machines (JRuby, MagLev, IronRuby, Rubinius, MacRuby) and how to choose what fits best within the enterprise.

http://www.infoq.com/presentations/seifer-ruby-vm-comparison

OwnerDisplayName: Walther

LastEditorDisplayName: mmyers

ContentLicense: CC BY-SA 2.5

Title: Is JRuby ready for production?

OwnerDisplayName: Jared


问:
how to send string in my append html function in jquery
I am returning data from controller, and i use a ajax call over there

```<code> $singleArray['traveller'] = json_encode($traveller); //get data from own array
    $finalDataArray[] =  $singleArray; // assigen data to global array
    return ['status'=>'true','flightResults'=> $finalDataArray] //return data to ajax call
</code>```

In my jquery part i use foreach loop and pass to append html.

In append html have a button

```<code>onclick=testfunction(\'' + item.traveller + '\')
</code>```

I pass the data which i get from foreach loop.

now i want to send data to the function in jquery, I create a function testfunction:

```<code>function testfunction(travller)
{
    console.log(travller); //want to get which array is $traveller valriable
}
</code>```

答: Try changing onclick=testfunction(\'' + item.traveller + '\') to onclick=testfunction('\' + item.traveller + '\')

Body:
I am returning data from controller, and i use a ajax call over there

 $singleArray['traveller'] = json_encode($traveller); //get data from own array
    $finalDataArray[] =  $singleArray; // assigen data to global array
    return ['status'=>'true','flightResults'=> $finalDataArray] //return data to ajax call

In my jquery part i use foreach loop and pass to append html.

In append html have a button

onclick=testfunction(\'' + item.traveller + '\')

I pass the data which i get from foreach loop.

now i want to send data to the function in jquery, I create a function testfunction:

function testfunction(travller)
{
    console.log(travller); //want to get which array is $traveller valriable
}


问:
Moving HTML to a parent using jQuery in WordPress - CLOSED
I am creating a WordPress webshop using WooCommerce and the Divi theme.

On PC all is great, but on mobile the theme places my custom mobile cart quantity counter inside the mobile menu dropdown. This makes it not visible until you open the mobile menu. (which uses JavaScript to add display:none to the parent when collapsed.)

Now I'm trying to move the cart quantity counter up in the HTML so it stays visible.

Here is the code that I'm using. But for some reason it's not taking effect.

```<code><script type="text/javascript">
    (function() {
        $('#mobile_menu li.cart_menu').appendTo('#main-header');
    })(jQuery);
</script>
</code>```

I just want the code snippet to be fired automatically.

I did some testing, and this code snippet does work, but only fires after the add to cart action has been activated:

```<code><script type="text/javascript">
    (function() {
        $('body').on('added_to_cart',
                     $('#mobile_menu li.cart_menu').appendTo('#main-header');
    });
    })(jQuery);
</script>
</code>```

What am I doing wrong here?

UPDATE:

This script works:

```<code><script type="text/javascript">
    (function($) {
        $(window).on('load', function() {
            $('#mobile_menu li.cart_menu').appendTo('#main-header');
        });
    })(jQuery);
</script>
</code>```

答:
I found the solution.

This script works:

```<code>(function($){
    $(window).on('load', function() {
        $('#mobile_menu li.cart_menu').appendTo('#main-header');
    });
})(jQuery);
</code>```

Body:
I am creating a WordPress webshop using WooCommerce and the Divi theme.

On PC all is great, but on mobile the theme places my custom mobile cart quantity counter inside the mobile menu dropdown. This makes it not visible until you open the mobile menu. (which uses JavaScript to add display:none to the parent when collapsed.)

Now I'm trying to move the cart quantity counter up in the HTML so it stays visible.

Here is the code that I'm using. But for some reason it's not taking effect.

I just want the code snippet to be fired automatically.

I did some testing, and this code snippet does work, but only fires after the add to cart action has been activated:

What am I doing wrong here?

UPDATE:

This script works:

Body:
I found the solution.

This script works:

(function($){
    $(window).on('load', function() {
        $('#mobile_menu li.cart_menu').appendTo('#main-header');
    });
})(jQuery);


问:
How to make countdown timer print result on single line in C?
I have code here which works as a countdown timer but it prints results on a new line
like this:

```<code>10
9
8
7
6
5
4
3
2
1
</code>```

here is my code:

```<code>int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}
</code>```

what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense

答:
Use "\b \b" to clear one character. Imagine you just printed "42": the 1st '\b' moves the cursor back to over the 2, then the space 'clears' that 2, and finally go back again one more space.

```<code>    printf("Time: \t");
    while(count != 0)
    {
            printf("%d", count);
            fflush(stdout);
            sleep(1);
            if (count >= 100) printf("\b \b");
            if (count >= 10) printf("\b \b");
            if (count >= 1) printf("\b \b");
            count--;
    }
    printf(" \n");
</code>```

Body:
I have code here which works as a countdown timer but it prints results on a new line
like this:

10
9
8
7
6
5
4
3
2
1

here is my code:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}

what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense

Body:
Use "\b \b" to clear one character. Imagine you just printed "42": the 1st '\b' moves the cursor back to over the 2, then the space 'clears' that 2, and finally go back again one more space.

    printf("Time: \t");
    while(count != 0)
    {
            printf("%d", count);
            fflush(stdout);
            sleep(1);
            if (count >= 100) printf("\b \b");
            if (count >= 10) printf("\b \b");
            if (count >= 1) printf("\b \b");
            count--;
    }
    printf(" \n");


问:
Download images via 1 button
I have a problem to download images via 1 button. Now my situation is pressed the preview button first then click the download link just can download the images. How can direct pressed the download link to download the images?

Below is my tried the sample coding:

  Testing

    Html to canvas, and canvas to proper image

    Codepedia.info is a programming blog. Tutorials focused on Programming ASP.Net, C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs, Web Design, Software

    html2canvas script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation.

<input id="btn-Preview-Image" type="button" value="Preview" />
Download

```

The output result like below the picture:

Hope someone can guide me how to remove the preview button and just click the download link can download the images.

Working jsfiddle: https://jsfiddle.net/ason5861_cs/7c14gLxn/1/

答:
I've changed your download function a bit so it can be reusable.

$("#btn-Convert-Html2Image").on('click', function () {
  const link = document.createElement('a');
  link.download = 'your_pic_name.png';
  link.href = getCanvas.toDataURL("image/png")
  link.click();
});
```
<p>This way, you can trigger the download just by</p>
<pre class="lang-js prettyprint-override"><code>$("#btn-Convert-Html2Image").trigger('click');
</code>```

So the preview code is

$('#btn-Preview-Image').on('click', function () {
  html2canvas(element, {
    onrendered: function (canvas) {
      $('#previewImage').append(canvas);
      getCanvas = canvas;

      $('#btn-Convert-Html2Image').trigger('click');
    }
  });
});
```

https://output.jsbin.com/gimumoq

Title: Download images via 1 button

Body:
I have a problem to download images via 1 button. Now my situation is pressed the preview button first then click the download link just can download the images. How can direct pressed the download link to download the images?

Below is my tried the sample coding:

  Testing

    Html to canvas, and canvas to proper image

    Codepedia.info is a programming blog. Tutorials focused on Programming ASP.Net, C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs, Web Design, Software

    html2canvas script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation.

<input id="btn-Preview-Image" type="button" value="Preview" />
Download

The output result like below the picture:

Hope someone can guide me how to remove the preview button and just click the download link can download the images.

Working jsfiddle: https://jsfiddle.net/ason5861_cs/7c14gLxn/1/

Body:
I've changed your download function a bit so it can be reusable.

$("#btn-Convert-Html2Image").on('click', function () {
  const link = document.createElement('a');
  link.download = 'your_pic_name.png';
  link.href = getCanvas.toDataURL("image/png")
  link.click();
});

This way, you can trigger the download just by

$("#btn-Convert-Html2Image").trigger('click');

So the preview code is

$('#btn-Preview-Image').on('click', function () {
  html2canvas(element, {
    onrendered: function (canvas) {
      $('#previewImage').append(canvas);
      getCanvas = canvas;

      $('#btn-Convert-Html2Image').trigger('click');
    }
  });
});

https://output.jsbin.com/gimumoq


问:
python flask json response embed url for clickable redirect
My flask Restful API currently provides a get response

$ curl https://endpoint/bucket/blahhh
{"response": {"items": ["item1"], "id": "blahhh", "time": 1544638988174, "user": "mafia"}}

Can I make the "items" list items to dynamically redirect to different endpoint "https://endpoint/item/item1" ON-CLICK using flask? (kind of like "href")

Note that the response here is plain JSON, there are no templates here.

If the question has been asked already, please direct me towards it..

答: one way would be to use url_for() of flask</p>


问:
Android round button with shadow
I am new to android I have a button in my app:

```<code><Button android:elevation="10dp"
        android:id="@+id/btnAddJob"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/round_btn"
        android:drawableLeft="@drawable/plus"
        android:paddingLeft="9dp"
        android:gravity="center"
        android:layout_marginLeft="300dp" />
</code>```

and the round_btn:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="oval" android:thickness="24dp" >
        <stroke android:color="@color/colorText" android:width="24dp" />
        <solid android:color="@color/colorText"/>
        <size android:width="150dp" android:height="150dp"/>
    </shape>
</item>
</code>```

The problem is I want it to have shadow so the button seems higher than other elements. Can anybody help please?

答:
just add material library :

implementation 'com.google.android.material:material:1.2.0-alpha03'

and use MaterialButton :

```<code> <com.google.android.material.button.MaterialButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        app:cornerRadius="20dp" //you can set radius easily
/>
</code>```

Title: Android round button with shadow

Body:
I am new to android I have a button in my app:

<Button android:elevation="10dp"
        android:id="@+id/btnAddJob"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/round_btn"
        android:drawableLeft="@drawable/plus"
        android:paddingLeft="9dp"
        android:gravity="center"
        android:layout_marginLeft="300dp" />

and the round_btn:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="oval" android:thickness="24dp" >
        <stroke android:color="@color/colorText" android:width="24dp" />
        <solid android:color="@color/colorText"/>
        <size android:width="150dp" android:height="150dp"/>
    </shape>
</item>

The problem is I want it to have shadow so the button seems higher than other elements. Can anybody help please?

Body:
just add material library :

implementation 'com.google.android.material:material:1.2.0-alpha03'

and use MaterialButton :

 <com.google.android.material.button.MaterialButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        app:cornerRadius="20dp" //you can set radius easily
/>


问:
Output of pow() function in C++ is not giving accurate answer
The user will give an integer input. I have to find the mod after squaring it. But when I give a big integer, pow() gives the wrong answer. How can I fix that?

#include<bits/stdc++.h>

using namespace std;

int main()
{
    //ios_base:: sync_with_stdio(false);
    //cin.tie(NULL);
    int t;
    cin >> t;
    for(int i = 0; i < t; i++)
    {
        long long n;
        cin >> n;

        long long sn = 0;
        sn = pow(n, 2);
        long long v = pow(10, 9) + 7;

        cout << sn % v << endl;
    }
}
```

答: As the comments say, pow works on floating numbers. Since you want to square integers, you're better off just multiplying them together using sn = n*n. If you use an unsigned long long you'll be able to exactly compute the square but only if this square is at most +18,446,744,073,709,551,615 (see https://en.m.wikipedia.org/wiki/C_data_types)


问:
Should I expect POSIX to include getopt.h?
According to this, the POSIX library does not include getopt.h. However, I found this in unistd.h:

```<code>#ifdef  __USE_POSIX2
/* Get definitions and prototypes for functions to process the
   arguments in ARGV (ARGC of them, minus the program name) for
   options given in OPTS.  */
# define __need_getopt
# include <getopt.h>
#endif
</code>```

Does this mean that getopt.h is implicitly included when you include unistd.h? I mean, is the code above something I should expect from all implementations of the unistd header file, or is it just something that is in my particular version? Also, is the __USE_POSIX2 macro defined in POSIX.2 and onwards, or is it just for POSIX.2?

答:
__USE_POSIX2 is an implementation detail of glibc; it corresponds to _POSIX_C_SOURCE >= 2 or _XOPEN_SOURCE being defined. These are also implied by _GNU_SOURCE, and are used implicitly unless strict ANSI mode is on. You are not supposed to define the __USE_ macros directly.

Since it corresponds to a value >= 2, it does apply to later versions. See the feature_test_macros manpage for further details.

Or, from the comments in features.h (the internal header - don't include directly - that takes care of all this):

```<code>/* These are defined by the user (or the compiler)
   to specify the desired environment:
...
   _POSIX_C_SOURCE  If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2;
            if >=199309L, add IEEE Std 1003.1b-1993;
            if >=199506L, add IEEE Std 1003.1c-1995;
            if >=200112L, all of IEEE 1003.1-2004
            if >=200809L, all of IEEE 1003.1-2008
   _XOPEN_SOURCE    Includes POSIX and XPG things.  Set to 500 if
            Single Unix conformance is wanted, to 600 for the
            sixth revision, to 700 for the seventh revision.
</code>```

Body:
According to this, the POSIX library does not include getopt.h. However, I found this in unistd.h:

#ifdef  __USE_POSIX2
/* Get definitions and prototypes for functions to process the
   arguments in ARGV (ARGC of them, minus the program name) for
   options given in OPTS.  */
# define __need_getopt
# include <getopt.h>
#endif

Does this mean that getopt.h is implicitly included when you include unistd.h? I mean, is the code above something I should expect from all implementations of the unistd header file, or is it just something that is in my particular version? Also, is the __USE_POSIX2 macro defined in POSIX.2 and onwards, or is it just for POSIX.2?

Body:
__USE_POSIX2 is an implementation detail of glibc; it corresponds to _POSIX_C_SOURCE >= 2 or _XOPEN_SOURCE being defined. These are also implied by _GNU_SOURCE, and are used implicitly unless strict ANSI mode is on. You are not supposed to define the __USE_ macros directly.

Since it corresponds to a value >= 2, it does apply to later versions. See the feature_test_macros manpage for further details.

Or, from the comments in features.h (the internal header - don't include directly - that takes care of all this):

/* These are defined by the user (or the compiler)
   to specify the desired environment:
...
   _POSIX_C_SOURCE  If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2;
            if >=199309L, add IEEE Std 1003.1b-1993;
            if >=199506L, add IEEE Std 1003.1c-1995;
            if >=200112L, all of IEEE 1003.1-2004
            if >=200809L, all of IEEE 1003.1-2008
   _XOPEN_SOURCE    Includes POSIX and XPG things.  Set to 500 if
            Single Unix conformance is wanted, to 600 for the
            sixth revision, to 700 for the seventh revision.


问:
Could not authenticate you from GoogleOauth2 because "Invalid credentials"
I params the Google subscription with the gem 'omniauth-google-oauth2' and I config the ui and provider + in the devise.rb I put this code config.omniauth :google_oauth2, ENV["GOOGLE_ID"], ENV["GOOGLE_SECRET"], scope: 'email', info_fields: 'email, first_name,last_name', image_size: 'large'

I enter the code in application.yml and I generate contacts APIs + Google + APIs but when I want to connect it like this :
the error message tells me that
Please could you tell what's wrong. Your help is appreciated.

I am a little bit lost.

答:
I recently got this same error using the omniauth-google-oauth2 gem:

Could not authenticate you from GoogleOauth2 because “Invalid credentials”

The server logs showed this:

OAuth2::Error {"code"=>403, "message"=>"Legacy People API has not been used in project 1070582368186 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/legacypeople.googleapis.com/overview?project=############# then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."

As discussed in this issue I upgraded the gem to the latest version (0.8.0) which fixed it. Here is the commit that performs the workaround.


问:
Storing multiple ndarrays to a list
During each iteration of for loop some results get stored in a ndarray which look like this,

```<code>testpredict=[[1.1],
             [2.344],
             [3.00]]
</code>```

I want to store the above results in a list variable during each iteration.
Something like...

```<code>list[i]= testpredict
</code>```

My final list should look like this:

```<code>final_list=[
            [[1.1], [2.344], [3.00]],
            [[4.03130], [4.55914], [4.46367]],
            .......
           ]
</code>```

how can I do this correctly?

答:
For each interation append the testpredict to the final_list:

```<code>import numpy as np
final_list= []
testpredict=np.array([[1.1],
             [2.344],
             [3.00]])

final_list.append(testpredict.tolist())
</code>```

Let's simulate 3 iterations with the same testpredict as a result:

```<code>final_list = []
# lets simulate 3 iteration
for iter in [1,2,3]:
    # testpredict would be your result at each iteration
    testpredict = np.array([[1.1],
                   [2.344],
                   [3.00]])
    final_list.append(testpredict.tolist())
print(final_list)
</code>```

Title: Storing multiple ndarrays to a list

Body:
During each iteration of for loop some results get stored in a ndarray which look like this,

testpredict=[[1.1],
             [2.344],
             [3.00]]

I want to store the above results in a list variable during each iteration.
Something like...

list[i]= testpredict

My final list should look like this:

final_list=[
            [[1.1], [2.344], [3.00]],
            [[4.03130], [4.55914], [4.46367]],
            .......
           ]

how can I do this correctly?

Body:
For each interation append the testpredict to the final_list:

import numpy as np
final_list= []
testpredict=np.array([[1.1],
             [2.344],
             [3.00]])

final_list.append(testpredict.tolist())

Let's simulate 3 iterations with the same testpredict as a result:

final_list = []
# lets simulate 3 iteration
for iter in [1,2,3]:
    # testpredict would be your result at each iteration
    testpredict = np.array([[1.1],
                   [2.344],
                   [3.00]])
    final_list.append(testpredict.tolist())
print(final_list)


问:
When i execute a query in php, i get: Fatal error: Uncaught Error: Call to a member function close() on bool in
I'm following a course about php and mysql and have a task about CRUD.
When i execute a query to delete the contents of a table and related tables
everything works but i get:

Fatal error: Uncaught Error: Call to a member function close() on bool
  in
  /Applications/XAMPP/xamppfiles/htdocs/LOI/hoofdstuk10/opgave/schoon.php:10
  Stack trace: #0 {main} thrown in
  /Applications/XAMPP/xamppfiles/htdocs/LOI/hoofdstuk10/opgave/schoon.php
  on line 10.

What could be wrong?
It's a very simple document so perhaps it's in the sql document.

```<code><?php

require_once 'login.php';

$query = "DELETE FROM Lid";

$result = $conn->query($query);
if (!$result) die ('DELETE failed');

$result->close();
$conn->close();
?>
</code>```

SQL

```<code>CREATE TABLE Postcodes (
    postcode CHAR(6) NOT NULL,
    straat VARCHAR(60) NOT NULL,
    woonplaats VARCHAR(60) NOT NULL,
    PRIMARY KEY (postcode));

CREATE TABLE Lid (
    lidnummer INT NOT NULL AUTO_INCREMENT,
    naam VARCHAR(30) NOT NULL,
    voornaam VARCHAR(30) NOT NULL,
    postcode CHAR(6) NOT NULL,
    huisnummer VARCHAR(10) NOT NULL,
    PRIMARY KEY (lidnummer),
    CONSTRAINT FK_postcode FOREIGN KEY (postcode)
    REFERENCES Postcodes(postcode));

CREATE TABLE email (
    lidnummer INT NOT NULL,
    emailadres VARCHAR(60),
    PRIMARY KEY (emailadres),
    CONSTRAINT FK_email FOREIGN KEY (lidnummer)
    REFERENCES Lid(lidnummer) ON DELETE CASCADE);

CREATE TABLE Telefoonnummers (
    lidnummer INT NOT NULL,
    telefoonnummer VARCHAR(60),
    PRIMARY KEY (telefoonnummer),
    CONSTRAINT FK_telefoonnummer FOREIGN KEY (lidnummer)
    REFERENCES Lid(lidnummer) ON DELETE CASCADE);

INSERT INTO Postcodes(postcode, straat, woonplaats)
    VALUES('3333AA', 'van Goghsingel', 'Amsterdam'),
            ('4444BB', 'Rembrandtlaan', 'Rotterdam'),
            ('5555CC', 'Mondriaanstraat', 'Den Haag');

INSERT INTO Lid(lidnummer, naam, voornaam, postcode, huisnummer)
    VALUES(1, 'Jansen', 'Jan', '3333AA', '10'),
            (2, 'Pietersen', 'Piet', '4444BB', '20'),
            (3, 'Klaassen', 'Klaas', '5555CC', '30');

INSERT INTO email(lidnummer, emailadres)
    VALUES((SELECT lidnummer FROM Lid WHERE postcode = '3333AA' AND huisnummer = '10'), 'jan@gmail.com'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '4444BB' AND huisnummer = '20'), 'piet@gmail.com'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '5555CC' AND huisnummer = '30'), 'klaas@gmail.com');

INSERT INTO Telefoonnummers(lidnummer, telefoonnummer)
    VALUES((SELECT lidnummer FROM Lid WHERE postcode = '3333AA' AND huisnummer = '10'), '0655554444'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '4444BB' AND huisnummer = '20'), '0632323232'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '5555CC' AND huisnummer = '30'), '0612345678');
</code>```

答:
mysqli query returns true;

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Your request returns no data, that's why you receive true.

Just delete this row:

$result->close();
```

Body:
I'm following a course about php and mysql and have a task about CRUD.
When i execute a query to delete the contents of a table and related tables
everything works but i get:

Fatal error: Uncaught Error: Call to a member function close() on bool
  in
  /Applications/XAMPP/xamppfiles/htdocs/LOI/hoofdstuk10/opgave/schoon.php:10
  Stack trace: #0 {main} thrown in
  /Applications/XAMPP/xamppfiles/htdocs/LOI/hoofdstuk10/opgave/schoon.php
  on line 10.

What could be wrong?
It's a very simple document so perhaps it's in the sql document.

<?php

require_once 'login.php';

$query = "DELETE FROM Lid";

$result = $conn->query($query);
if (!$result) die ('DELETE failed');

$result->close();
$conn->close();
?>

SQL

CREATE TABLE Postcodes (
    postcode CHAR(6) NOT NULL,
    straat VARCHAR(60) NOT NULL,
    woonplaats VARCHAR(60) NOT NULL,
    PRIMARY KEY (postcode));

CREATE TABLE Lid (
    lidnummer INT NOT NULL AUTO_INCREMENT,
    naam VARCHAR(30) NOT NULL,
    voornaam VARCHAR(30) NOT NULL,
    postcode CHAR(6) NOT NULL,
    huisnummer VARCHAR(10) NOT NULL,
    PRIMARY KEY (lidnummer),
    CONSTRAINT FK_postcode FOREIGN KEY (postcode)
    REFERENCES Postcodes(postcode));

CREATE TABLE email (
    lidnummer INT NOT NULL,
    emailadres VARCHAR(60),
    PRIMARY KEY (emailadres),
    CONSTRAINT FK_email FOREIGN KEY (lidnummer)
    REFERENCES Lid(lidnummer) ON DELETE CASCADE);

CREATE TABLE Telefoonnummers (
    lidnummer INT NOT NULL,
    telefoonnummer VARCHAR(60),
    PRIMARY KEY (telefoonnummer),
    CONSTRAINT FK_telefoonnummer FOREIGN KEY (lidnummer)
    REFERENCES Lid(lidnummer) ON DELETE CASCADE);

INSERT INTO Postcodes(postcode, straat, woonplaats)
    VALUES('3333AA', 'van Goghsingel', 'Amsterdam'),
            ('4444BB', 'Rembrandtlaan', 'Rotterdam'),
            ('5555CC', 'Mondriaanstraat', 'Den Haag');

INSERT INTO Lid(lidnummer, naam, voornaam, postcode, huisnummer)
    VALUES(1, 'Jansen', 'Jan', '3333AA', '10'),
            (2, 'Pietersen', 'Piet', '4444BB', '20'),
            (3, 'Klaassen', 'Klaas', '5555CC', '30');

INSERT INTO email(lidnummer, emailadres)
    VALUES((SELECT lidnummer FROM Lid WHERE postcode = '3333AA' AND huisnummer = '10'), 'jan@gmail.com'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '4444BB' AND huisnummer = '20'), 'piet@gmail.com'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '5555CC' AND huisnummer = '30'), 'klaas@gmail.com');

INSERT INTO Telefoonnummers(lidnummer, telefoonnummer)
    VALUES((SELECT lidnummer FROM Lid WHERE postcode = '3333AA' AND huisnummer = '10'), '0655554444'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '4444BB' AND huisnummer = '20'), '0632323232'),
            ((SELECT lidnummer FROM Lid WHERE postcode = '5555CC' AND huisnummer = '30'), '0612345678');


问:
Load Specific URL page in WebView if the Push Notification is Clicked
I am quite a newbie in Android studio and have a question about it.

So I have an android app using Webview. I also implement the FCM push notification.
When I click the notification, it directly opens the homepage. What if I want to open the specific page in the app when I click the notification?

here is the main activity

```<code>class MainActivity : Activity() {
    private val URL = "https://thelink.pl"
    lateinit var webView: WebView
    private var notificationId: Int = 0;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.requestWindowFeature(Window.FEATURE_NO_TITLE)
        webView = createView()
        setContentView(webView)

        firebaseInstanceToken() //get token
        subscibeToTopics("androidUsers")
    }
</code>```

and here is my FCM service

```<code> // [START receive_message]
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        //check if message contains a data payload
        remoteMessage
                .data.isNotEmpty().let {
            Log.d("isData", "Message data payload: " + remoteMessage.data)
                    theMessageBody = remoteMessage.data.get("body").toString()
                    theMessageTitle = remoteMessage.data.get("title").toString()
                    theMessageDetail_ = remoteMessage.data.get("messageDetail").toString()
                    sendNotification(theMessageBody, theMessageTitle, theMessageDetail_)
        }

        //check if the message contains a notification payload
        remoteMessage
                .notification?.let {
                    theMessageBody = it.body!!
                    theMessageTitle = it.title!!
                    sendNotification(theMessageBody, theMessageTitle, theMessageDetail_)
        }
    }
</code>```

any help is appreciated.. Thank you

答:
did you send specific page via FCM? then just send using intent.

in my case,

```<code>private void sendNotification(String messageBody) {
        Dlog.e("messageBody = " + messageBody);

        try {
            JSONObject jsonBody = new JSONObject(messageBody);

            int pushType = jsonBody.getJSONObject("data").getInt("pushType");
            String pushTitle = jsonBody.getString("title");
            String textBody = "";
            String contentText = "";
            PendingIntent pendingIntent = null;

                String push_title = jsonBody.getString("title");
                String boardContent = jsonBody.getJSONObject("data").getString("boardContent");
                String boardUrl = jsonBody.getJSONObject("data").getString("boardUrl");

                textBody = boardContent;
                contentText = boardContent;

                if (boardUrl.equals("")){
                    Intent intent = new Intent(this, SplashActivity.class);
                    pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                }else {
                    Intent intent = new Intent(this, PushWebViewActivity.class);
                    intent.putExtra("push_title", push_title);
                    intent.putExtra("boardUrl", boardUrl);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                }

            Bitmap icon2 = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
            bigText.bigText(textBody);

            NotificationCompat.Builder notificationBuilder;
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel("channel", "channel_nm", NotificationManager.IMPORTANCE_HIGH);
                mChannel.setVibrationPattern(new long[]{500, 500, 500, 500});
                mChannel.setLightColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
                AudioAttributes att = new AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .build();
                mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                mChannel.enableVibration(true);
                mChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), att);
                notificationManager.createNotificationChannel(mChannel);
                notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), mChannel.getId());
            } else {
                notificationBuilder = new NotificationCompat.Builder(getApplicationContext());
            }
            notificationBuilder
                    .setLargeIcon(icon2)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(pushTitle)
                    .setContentText(contentText)
                    .setStyle(bigText)
                    .setLights(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), 3000, 3000)
                    .setVibrate(new long[]{500, 500, 500, 500})
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setContentIntent(pendingIntent);

            int random_num = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
            notificationManager.notify(random_num, notificationBuilder.build());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
</code>```

I get url from FCM and send to page and webView load url

Body:
I am quite a newbie in Android studio and have a question about it.

So I have an android app using Webview. I also implement the FCM push notification.
When I click the notification, it directly opens the homepage. What if I want to open the specific page in the app when I click the notification?

here is the main activity

class MainActivity : Activity() {
    private val URL = "https://thelink.pl"
    lateinit var webView: WebView
    private var notificationId: Int = 0;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.requestWindowFeature(Window.FEATURE_NO_TITLE)
        webView = createView()
        setContentView(webView)

        firebaseInstanceToken() //get token
        subscibeToTopics("androidUsers")
    }

and here is my FCM service

 // [START receive_message]
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        //check if message contains a data payload
        remoteMessage
                .data.isNotEmpty().let {
            Log.d("isData", "Message data payload: " + remoteMessage.data)
                    theMessageBody = remoteMessage.data.get("body").toString()
                    theMessageTitle = remoteMessage.data.get("title").toString()
                    theMessageDetail_ = remoteMessage.data.get("messageDetail").toString()
                    sendNotification(theMessageBody, theMessageTitle, theMessageDetail_)
        }

        //check if the message contains a notification payload
        remoteMessage
                .notification?.let {
                    theMessageBody = it.body!!
                    theMessageTitle = it.title!!
                    sendNotification(theMessageBody, theMessageTitle, theMessageDetail_)
        }
    }

any help is appreciated.. Thank you

Body:
did you send specific page via FCM? then just send using intent.

in my case,

private void sendNotification(String messageBody) {
        Dlog.e("messageBody = " + messageBody);

        try {
            JSONObject jsonBody = new JSONObject(messageBody);

            int pushType = jsonBody.getJSONObject("data").getInt("pushType");
            String pushTitle = jsonBody.getString("title");
            String textBody = "";
            String contentText = "";
            PendingIntent pendingIntent = null;

                String push_title = jsonBody.getString("title");
                String boardContent = jsonBody.getJSONObject("data").getString("boardContent");
                String boardUrl = jsonBody.getJSONObject("data").getString("boardUrl");

                textBody = boardContent;
                contentText = boardContent;

                if (boardUrl.equals("")){
                    Intent intent = new Intent(this, SplashActivity.class);
                    pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                }else {
                    Intent intent = new Intent(this, PushWebViewActivity.class);
                    intent.putExtra("push_title", push_title);
                    intent.putExtra("boardUrl", boardUrl);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                }

            Bitmap icon2 = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
            bigText.bigText(textBody);

            NotificationCompat.Builder notificationBuilder;
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel("channel", "channel_nm", NotificationManager.IMPORTANCE_HIGH);
                mChannel.setVibrationPattern(new long[]{500, 500, 500, 500});
                mChannel.setLightColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
                AudioAttributes att = new AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .build();
                mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                mChannel.enableVibration(true);
                mChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), att);
                notificationManager.createNotificationChannel(mChannel);
                notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), mChannel.getId());
            } else {
                notificationBuilder = new NotificationCompat.Builder(getApplicationContext());
            }
            notificationBuilder
                    .setLargeIcon(icon2)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(pushTitle)
                    .setContentText(contentText)
                    .setStyle(bigText)
                    .setLights(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), 3000, 3000)
                    .setVibrate(new long[]{500, 500, 500, 500})
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setContentIntent(pendingIntent);

            int random_num = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
            notificationManager.notify(random_num, notificationBuilder.build());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

I get url from FCM and send to page and webView load url


问:
Problem with function that returns the key with most unique values in python
I am trying to implement greedy algorithm where I need to find the alphabet generator with most unique alphabets, process these alphabets and find the next best generator until I have processed all alphabets. However, when I run the function get_next_best_generator the first time it returns the right values but doesn't return anything in the next call with the following error-
0
[]
KeyError: ''
output of first call-generator_2
6
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']

why its not returning anything in the call after the first call?

Here is my code-

```<code># create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','m'], 'generator_4':['p','e','m','g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while len(alphabets_covered) < 13:

    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
</code>```

After making some changes- My function still doesn't return the key with the most unique elements.

Updated code-

```<code># create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :
            if selected_alphabet  in alphabets:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets -= set(best_generator_unique_alphabets)
</code>```

Expected output-
generator_2
8
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
generator_3
3
['x', 'w', 'b']
generator_4
2
['e','g']
generator_1
1
['r']

答:
First of all, if your script crashes, please include the full stack-trace!

Your problem occurs because your if-statement if len(unique_alphabets_list) > most_alphabets_count is never True on your second pass-through of the function.

The reason for that is, inside of this for-loop:

```<code>for selected_alphabet in generator_alphabets:
    if selected_alphabet not in alphabets_covered:
        unique_alphabets_list.append(selected_alphabet)
        alphabets_covered.append(selected_alphabet)
</code>```

There you write to alphabets_covered which after you've run the function once, will contain all of the unique letters already, so the second go-around the if-statement will never be True. If you instead change the scope of the variable by defining it inside of the function, you can still keep count on the unique values.

And finally because you can no longer use alphabets_covered as your while-statement limiter, change it to just check if generator_alphabets_dict has any values inside of it or not.

Here is the updated code:

```<code># create lists to store covered alphabets and processed generators
generator_covered = []
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict = {'generator_1': ['p', 'q', 'r'], 'generator_2': ['p', 'q', 'k', 'j', 'l', 'm', 'n', 't'],
                            'generator_3': ['x', 'm'], 'generator_4': ['p', 'e', 'm', 'g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count = 0
    best_generator_alphabets = []
    best_generator = ''
    alphabets_covered = [] # Moved into the function.

    #Loop through the dict to find the generator with most unique alphabets
    for generator, alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return most_alphabets_count, best_generator_alphabets, best_generator

# Loop until all alphabets have been covered
# the boolean value of an empty dictionary is False, so we can limit it on that.
while generator_alphabets_dict:
    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
</code>```

I haven't added any logic to your function, and looking at the output of it, then we can see generators are output in the following order:

```<code>generator_2
generator_1
generator_4
generator_3
</code>```

However, that isn't the order I would make, because generator_4 has more characters than generator_1 and thus should be more "unique" in my eyes.

With that in mind, I have simplified your code to return the order that I would see would be more "unique":

```<code>def get_ordered_unique_generator(values: dict) -> list:
    return sorted(values, key=lambda x: len(set(values[x])), reverse=True)

for k in get_ordered_unique_generator(generator_alphabets_dict):
    print(f"Key: {k}, Value: {generator_alphabets_dict[k]}")
</code>```

Output:

```<code>Key: generator_2, Value: ['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
Key: generator_4, Value: ['p', 'e', 'm', 'g']
Key: generator_1, Value: ['p', 'q', 'r']
Key: generator_3, Value: ['x', 'm']
</code>```

Body:
I am trying to implement greedy algorithm where I need to find the alphabet generator with most unique alphabets, process these alphabets and find the next best generator until I have processed all alphabets. However, when I run the function get_next_best_generator the first time it returns the right values but doesn't return anything in the next call with the following error-
0
[]
KeyError: ''
output of first call-generator_2
6
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']

why its not returning anything in the call after the first call?

Here is my code-

# create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','m'], 'generator_4':['p','e','m','g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while len(alphabets_covered) < 13:

    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)

After making some changes- My function still doesn't return the key with the most unique elements.

Updated code-

# create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :
            if selected_alphabet  in alphabets:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets -= set(best_generator_unique_alphabets)

Expected output-
generator_2
8
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
generator_3
3
['x', 'w', 'b']
generator_4
2
['e','g']
generator_1
1
['r']

Body:
First of all, if your script crashes, please include the full stack-trace!

Your problem occurs because your if-statement if len(unique_alphabets_list) > most_alphabets_count is never True on your second pass-through of the function.

The reason for that is, inside of this for-loop:

for selected_alphabet in generator_alphabets:
    if selected_alphabet not in alphabets_covered:
        unique_alphabets_list.append(selected_alphabet)
        alphabets_covered.append(selected_alphabet)

There you write to alphabets_covered which after you've run the function once, will contain all of the unique letters already, so the second go-around the if-statement will never be True. If you instead change the scope of the variable by defining it inside of the function, you can still keep count on the unique values.

And finally because you can no longer use alphabets_covered as your while-statement limiter, change it to just check if generator_alphabets_dict has any values inside of it or not.

Here is the updated code:

# create lists to store covered alphabets and processed generators
generator_covered = []
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict = {'generator_1': ['p', 'q', 'r'], 'generator_2': ['p', 'q', 'k', 'j', 'l', 'm', 'n', 't'],
                            'generator_3': ['x', 'm'], 'generator_4': ['p', 'e', 'm', 'g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count = 0
    best_generator_alphabets = []
    best_generator = ''
    alphabets_covered = [] # Moved into the function.

    #Loop through the dict to find the generator with most unique alphabets
    for generator, alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return most_alphabets_count, best_generator_alphabets, best_generator

# Loop until all alphabets have been covered
# the boolean value of an empty dictionary is False, so we can limit it on that.
while generator_alphabets_dict:
    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)

I haven't added any logic to your function, and looking at the output of it, then we can see generators are output in the following order:

generator_2
generator_1
generator_4
generator_3

However, that isn't the order I would make, because generator_4 has more characters than generator_1 and thus should be more "unique" in my eyes.

With that in mind, I have simplified your code to return the order that I would see would be more "unique":

def get_ordered_unique_generator(values: dict) -> list:
    return sorted(values, key=lambda x: len(set(values[x])), reverse=True)

for k in get_ordered_unique_generator(generator_alphabets_dict):
    print(f"Key: {k}, Value: {generator_alphabets_dict[k]}")

Output:

Key: generator_2, Value: ['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
Key: generator_4, Value: ['p', 'e', 'm', 'g']
Key: generator_1, Value: ['p', 'q', 'r']
Key: generator_3, Value: ['x', 'm']


问:
Visual studio 2005: is there a compiler option to initialize all stack-based variables to zero?
This question HAS had to be asked before, so it kills me to ask it again, but I can't find it for all of my google and searching stackoverflow.

I'm porting a bunch of linux code to windows, and a good chunk of it makes the assumption that everything is automatically initialized to zero or null.

```<code>int whatever;
char* something;
</code>```

...and then immediately doing something that may leave 'something' null, and testing against 'something'

```<code>if(something == NULL)
{
.......
}
</code>```

I would REALLY like not to have to go back throughout this code and say:

```<code>int whatever = 0;
char* something = NULL;
</code>```

Even though that is the proper way to deal with it.  It's just very time consuming.

Otherwise, I declare a variable, and it's initialized to something crazy if I don't set it myself.

答:
Interestingly, MSVC now does have the ability to do this. The Microsoft Security team wrote a blog post about it here, and there's a CppCon talk here.

Unfortunately, it doesn't seem like this option is exposed to the public. This page lists a bunch of 'hidden MSVC flags', and it includes an option called -initall, so that might be it.

Body:
This question HAS had to be asked before, so it kills me to ask it again, but I can't find it for all of my google and searching stackoverflow.

I'm porting a bunch of linux code to windows, and a good chunk of it makes the assumption that everything is automatically initialized to zero or null.

int whatever;
char* something;

...and then immediately doing something that may leave 'something' null, and testing against 'something'

if(something == NULL)
{
.......
}

I would REALLY like not to have to go back throughout this code and say:

int whatever = 0;
char* something = NULL;

Even though that is the proper way to deal with it.  It's just very time consuming.

Otherwise, I declare a variable, and it's initialized to something crazy if I don't set it myself.


问:
Cannot login to Oracle Enterprise Manager Express
I have downloaded Oracle Developer Days Database 12c virtualbox image. I can boot it and access the desktop. When I try to log in to Enterprise Manager (EM) Express using the URL http://127.0.0.1:8888/em I am asked to install Adobe Flash. I install it and get to the login screen.

If I try to login as SYSTEM I get the following error:

But when I try to log in as user SYS I get a strange error: Security token does not match. You must login again..

To me it looks like the credentials for SYS are OK, but there is something wrong with the user in the database. Is this correct and if so how can I fix it? Or is EM Express just not setup on the image?

答:
Use internet explorer to login to EM .
The other browser are not compatible with enterprise manager</p>


问:
Parse XML only returns first element
I am new to robot framework's XML library.
I tried parsing an xml to get a value in it, but it would only get the very first element.
So my XML is something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Header>
    <firstElement>
        <secondElement>
            <myValue>...</myValue>
            <mySecondValue>...</mySecondValue>
            ...
        </secondElement
    </firstElement>
  </S:Header>
  <S:Body>
  ...
  </S:Body>
</S:Envelope>
</code>```

My very short robot framework test looks like this:

```<code> ${xml}=    Parse Xml    path/to/xml
 ${first}=    get element    ${xml}    myValue
 Log  ${first}
</code>```

But when parsing the XML, it logs it like this:

```<code>INFO : ${xml} = <Element 'Envelope' at 0x00000000042B67C8>
</code>```

Of course all my attempts to get values in the parsed xml failed, I get:

```<code>FAIL : No element matching 'myValue' found.
</code>```

What did I do wrong?

答:
The problem is with the xpath you're using to find the element, have a look here: https://robotframework.org/robotframework/latest/libraries/XML.html#Finding%20elements%20with%20xpath

It should look like this:

```<code>    ${x}=    Parse Xml    ${xml}
    ${el_my_value}=    Get Element    ${x}    .//myValue
    Log  ${el_my_value}
    ${first_text}=    Get Element Text    ${el_my_value}
</code>```

Notice that .//myValue.

Also, if you want to get element text, then you need to use keyword Get Element Text.

So the whole working example and result:

```<code>*** Settings ***
Library    XML
Variables    ../../Resources/xml_test.py

*** Test Cases ***
Test XML Parsing
    ${x}=    Parse Xml    ${xml}
    ${el_my_value}=    Get Element    ${x}    .//myValue
    Log  ${el_my_value}
    ${first_text}=    Get Element Text    ${el_my_value}
</code>```

Title: Parse XML only returns first element

Body:
I am new to robot framework's XML library.
I tried parsing an xml to get a value in it, but it would only get the very first element.
So my XML is something like this:

<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Header>
    <firstElement>
        <secondElement>
            <myValue>...</myValue>
            <mySecondValue>...</mySecondValue>
            ...
        </secondElement
    </firstElement>
  </S:Header>
  <S:Body>
  ...
  </S:Body>
</S:Envelope>

My very short robot framework test looks like this:

 ${xml}=    Parse Xml    path/to/xml
 ${first}=    get element    ${xml}    myValue
 Log  ${first}

But when parsing the XML, it logs it like this:

INFO : ${xml} = <Element 'Envelope' at 0x00000000042B67C8>

Of course all my attempts to get values in the parsed xml failed, I get:

FAIL : No element matching 'myValue' found.

What did I do wrong?

Body:
The problem is with the xpath you're using to find the element, have a look here: https://robotframework.org/robotframework/latest/libraries/XML.html#Finding%20elements%20with%20xpath

It should look like this:

    ${x}=    Parse Xml    ${xml}
    ${el_my_value}=    Get Element    ${x}    .//myValue
    Log  ${el_my_value}
    ${first_text}=    Get Element Text    ${el_my_value}

Notice that .//myValue.

Also, if you want to get element text, then you need to use keyword Get Element Text.

So the whole working example and result:

*** Settings ***
Library    XML
Variables    ../../Resources/xml_test.py

*** Test Cases ***
Test XML Parsing
    ${x}=    Parse Xml    ${xml}
    ${el_my_value}=    Get Element    ${x}    .//myValue
    Log  ${el_my_value}
    ${first_text}=    Get Element Text    ${el_my_value}


问:
Creating object with type safety
I'm using ThreadLocal for getting current logged in User into my application as

```<code>private static ThreadLocal<User> userAuditor = new ThreadLocal<>();
User user = Auditor.userAuditor.get();
</code>```

Will it make any difference if I don't specify type at the right side while creating object like the one mentioned above

Or will I have to specify type while creating object like the one mentioned below:

```<code>private static ThreadLocal<User> userAuditor = new ThreadLocal<User>();
</code>```

答: Since java 7 you could omit the Diamond operator <> at the right side when using generics, this feature was added only for code readability,it is helpful when using nested collection types and it doesn't affect the code logic or performance,thus it's up to your personal preferences.

Title: Creating object with type safety

Body:
I'm using ThreadLocal for getting current logged in User into my application as

private static ThreadLocal<User> userAuditor = new ThreadLocal<>();
User user = Auditor.userAuditor.get();

Will it make any difference if I don't specify type at the right side while creating object like the one mentioned above

Or will I have to specify type while creating object like the one mentioned below:

private static ThreadLocal<User> userAuditor = new ThreadLocal<User>();


问:
Fastest way to extract a substring in C#
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

```<code><a href="/link/i/want">Fixed_String</a>
</code>```

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?

答:
The SubString() Option

As noted by Teoman Soygul, there is a SubString() Option, which I don't know if it is slower or faster as I did not test them side by side.

Now, this is not properly disected into sub methods but should give you the general idea.

I just use a ReadOnlyCollection cause it is what I'm used to when no further manipulation of the list is required. Change it to what ever output list type you like.

The someText variable is most likely going to end up a paramter of GetLinks off course.

```<code>public ReadOnlyCollection<string> GetLinks()
{
    string startingText = "href=''";
    string endText = "''>";
    string stopText = "Fixed_String";
    string someText = @"what is this text <a href=''/link/i/want''>somenormallink</a> some random text <a href=''/another link/i/want''>Fixed_String</a> some more radnom txt ";

    List<string> myLinks = new List<string>();

    string[] rawLinks = someText.Split(new string[] { "<a " }, StringSplitOptions.None);

    foreach (string rawLink in rawLinks)
    {
        if (!rawLink.StartsWith(startingText))
        {
            continue;
        }

        myLinks.Add(rawLink.Substring(startingText.Length, rawLink.IndexOf(endText, 1) - startingText.Length));

        if (rawLink.Contains(stopText))
        {
            break;
        }
    }

    return new ReadOnlyCollection<string>(myLinks);
}
</code>```

That Results in a Collection containing the links:

Body:
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

Fixed_String

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?

Body:
The SubString() Option

As noted by Teoman Soygul, there is a SubString() Option, which I don't know if it is slower or faster as I did not test them side by side.

Now, this is not properly disected into sub methods but should give you the general idea.

I just use a ReadOnlyCollection cause it is what I'm used to when no further manipulation of the list is required. Change it to what ever output list type you like.

The someText variable is most likely going to end up a paramter of GetLinks off course.

public ReadOnlyCollection<string> GetLinks()
{
    string startingText = "href=''";
    string endText = "''>";
    string stopText = "Fixed_String";
    string someText = @"what is this text <a href=''/link/i/want''>somenormallink</a> some random text <a href=''/another link/i/want''>Fixed_String</a> some more radnom txt ";

    List<string> myLinks = new List<string>();

    string[] rawLinks = someText.Split(new string[] { "<a " }, StringSplitOptions.None);

    foreach (string rawLink in rawLinks)
    {
        if (!rawLink.StartsWith(startingText))
        {
            continue;
        }

        myLinks.Add(rawLink.Substring(startingText.Length, rawLink.IndexOf(endText, 1) - startingText.Length));

        if (rawLink.Contains(stopText))
        {
            break;
        }
    }

    return new ReadOnlyCollection<string>(myLinks);
}

That Results in a Collection containing the links:


问:
How to access host port from docker container
I have a docker container running jenkins. As part of the build process, I need to access a web server that is run locally on the host machine. Is there a way the host web server (which can be configured to run on a port) can be exposed to the jenkins container?

I'm running docker natively on a Linux machine.

UPDATE:

In addition to @larsks answer below, to get the IP address of the Host IP from the host machine, I do the following:

```<code>ip addr show docker0 | grep -Po 'inet \K[\d.]+'
</code>```

答:
For me (Windows 10, Docker Engine v19.03.8) it was a mix of https://stackoverflow.com/a/43541732/7924573 and https://stackoverflow.com/a/50866007/7924573 .

change the host/ip to host.docker.internal

e.g.: LOGGER_URL = "http://host.docker.internal:8085/log"

set the network_mode to bridge (if you want to maintain the port forwarding; if not use host):

version: '3.7'
services:
server:
    build: .
    ports:
         - "5000:5000"
    network_mode: bridge

or alternatively: Use --net="bridge" if you are not using docker-compose (similar to https://stackoverflow.com/a/48806927/7924573)

As pointed out in previous answers: This should only be used in a local development environment.

For more information read: https://docs.docker.com/compose/compose-file/#network_mode and https://docs.docker.com/docker-for-windows/networking/#use-cases-and-workarounds

Body:
I have a docker container running jenkins. As part of the build process, I need to access a web server that is run locally on the host machine. Is there a way the host web server (which can be configured to run on a port) can be exposed to the jenkins container?

I'm running docker natively on a Linux machine.

UPDATE:

In addition to @larsks answer below, to get the IP address of the Host IP from the host machine, I do the following:

ip addr show docker0 | grep -Po 'inet \K[\d.]+'