问:
Python OpenCV - waitKey(0) does not respond?
I'm using opencv 2.4.7 on ubuntu 12.04. I'm programming with python and I have a problem when i run this script:

```<code>import cv2

img = cv2.imread('347620923614738322_233985812.jpg')
cv2.namedWindow("window")
cv2.imshow("window", img)
cv2.waitKey(0)
</code>```

The problem is that the script doesn't stop when I close the image. I searched information about waitKey and I found that using cv2.waitKey(0) is correct.

I don't understand, where is the problem?

答:
This problem occurs in some earlier version of opencv.
So you just need to update opencv to the latest version. Version 4.0.0.21 worked for me.
Use the command below.

update opencv to version 4.0.0.21.

Body:
I'm using opencv 2.4.7 on ubuntu 12.04. I'm programming with python and I have a problem when i run this script:

import cv2

img = cv2.imread('347620923614738322_233985812.jpg')
cv2.namedWindow("window")
cv2.imshow("window", img)
cv2.waitKey(0)

The problem is that the script doesn't stop when I close the image. I searched information about waitKey and I found that using cv2.waitKey(0) is correct.

I don't understand, where is the problem?


来源: stackexchange

问:
Can I use fs promise API without then() or await?
I am writing an express web application

I need to write the body of post request into disk, but the returned promise would have no use for me.

Is it necessary to await or attach then function to the returned promise?

```<code>import { promises as fs } from 'fs';
import express from 'express';

const app = express();

app.post('/', (req, res) => {
  fs.writeFile(`record/${req.body.name}.json`, JSON.stringify(req.body));
  res.send(`Hello World`);
});

app.listen(8080);
</code>```

答:
No, you dont have to do anything with the returned promise, just like every non-async function it will be executed even if you ignore the return value, but there are some things you have to keep in mind:

if you dont wait for the promise to resolve or reject, the following actions, such as your res.send('Hello World'); most likely will be executed before the async operation is done. It depends on your application if this is a problem or not.

You also cant handle possible exceptions that might occur within the async function if you dont have a catch block, therefore your whole application might crash when running into an unhandled exception.

ContentLicense: CC BY-SA 4.0

Body:
I am writing an express web application

I need to write the body of post request into disk, but the returned promise would have no use for me.

Is it necessary to await or attach then function to the returned promise?

import { promises as fs } from 'fs';
import express from 'express';

const app = express();

app.post('/', (req, res) => {
  fs.writeFile(`record/${req.body.name}.json`, JSON.stringify(req.body));
  res.send(`Hello World`);
});

app.listen(8080);


问:
How can I include css files using node, express, and ejs?
I'm trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561, but I still can't get my styles.css to load.

From app.js

```<code>app.use(express.static(path.join(__dirname, 'public')));
</code>```

In my .ejs, I have tried both of these lines

```<code><link rel="stylesheet" type="text/css" href="/css/style.css" />
<link rel="stylesheet" type="text/css" href="/public/css/style.css" />
</code>```

Neither loads the css. I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'.

My path looks like

```<code>.
./app.js
./public
    /css
        /style.css
</code>```

答:
For NodeJS I would get the file name from the res.url, write the header for the file by getting the extension of the file with path.extname, create a read stream for the file, and pipe the response.

```<code>const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3000;

const server = http.createServer((req, res) => {
    let filePath = path.join(
        __dirname,
        "public",
        req.url === "/" ? "index.html" : req.url
    );

    let extName = path.extname(filePath);
    let contentType = 'text/html';

    switch (extName) {
        case '.css':
            contentType = 'text/css';
            break;
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;
        case '.jpg':
            contentType = 'image/jpg';
            break;
    }

    console.log(`File path: ${filePath}`);
    console.log(`Content-Type: ${contentType}`)

    res.writeHead(200, {'Content-Type': contentType});

    const readStream = fs.createReadStream(filePath);
    readStream.pipe(res);
});

server.listen(port, (err) => {
    if (err) {
        console.log(`Error: ${err}`)
    } else {
        console.log(`Server listening at port ${port}...`);
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561, but I still can't get my styles.css to load.

From app.js

app.use(express.static(path.join(__dirname, 'public')));

In my .ejs, I have tried both of these lines

<link rel="stylesheet" type="text/css" href="/css/style.css" />
<link rel="stylesheet" type="text/css" href="/public/css/style.css" />

Neither loads the css. I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'.

My path looks like

.
./app.js
./public
    /css
        /style.css

Body:
For NodeJS I would get the file name from the res.url, write the header for the file by getting the extension of the file with path.extname, create a read stream for the file, and pipe the response.

const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3000;

const server = http.createServer((req, res) => {
    let filePath = path.join(
        __dirname,
        "public",
        req.url === "/" ? "index.html" : req.url
    );

    let extName = path.extname(filePath);
    let contentType = 'text/html';

    switch (extName) {
        case '.css':
            contentType = 'text/css';
            break;
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;
        case '.jpg':
            contentType = 'image/jpg';
            break;
    }

    console.log(`File path: ${filePath}`);
    console.log(`Content-Type: ${contentType}`)

    res.writeHead(200, {'Content-Type': contentType});

    const readStream = fs.createReadStream(filePath);
    readStream.pipe(res);
});

server.listen(port, (err) => {
    if (err) {
        console.log(`Error: ${err}`)
    } else {
        console.log(`Server listening at port ${port}...`);
    }
});


问:
Using the NHibernate QueryOver, how can you add a type-safe restrictions between dates
Considering the following QueryOver (quarter and centre are variables passed in):

```<code>QueryOver.Of<Activity>()
        .Where(Restrictions.On<Activity>(a => a.StartDate).IsBetween(quarter.StartDate).And(quarter.EndDate) ||
               Restrictions.On<Activity>(a => a.EndDate).IsBetween(quarter.StartDate).And(quarter.EndDate) ||
               Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate)))  //TODO: Refactor this to remove magic strings
        .And(a => a.Centre == centre)
        .OrderBy(a => a.Title).Asc;
</code>```

This query works perfectly, but I'd like to change the following restriction to remove the magic strings:

```<code>Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate))
</code>```

Here are the entities (snipped for brevity):

```<code>public class Quarter
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

}

public class Activity
{
    public string Title { get; set; }
    public Centre Centre { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

}

public class Centre
{
    public string Name { get; set; }
}
</code>```

So what is the type-safe way using the new QueryOver extensions that will enable me to remove these magic strings?

答:
This is what you want:

```<code>Restrictions.And(
    Restrictions.Lt(Projections.Property<Activity>(x => x.StartDate),
                    quarter.StartDate),
    Restrictions.Gt(Projections.Property<Activity>(x => x.EndDate),
                    quarter.EndDate)))
</code>```

Sidenote: property names are not magic strings.

Body:
Considering the following QueryOver (quarter and centre are variables passed in):

QueryOver.Of<Activity>()
        .Where(Restrictions.On<Activity>(a => a.StartDate).IsBetween(quarter.StartDate).And(quarter.EndDate) ||
               Restrictions.On<Activity>(a => a.EndDate).IsBetween(quarter.StartDate).And(quarter.EndDate) ||
               Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate)))  //TODO: Refactor this to remove magic strings
        .And(a => a.Centre == centre)
        .OrderBy(a => a.Title).Asc;

This query works perfectly, but I'd like to change the following restriction to remove the magic strings:

Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate))

Here are the entities (snipped for brevity):

public class Quarter
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

}

public class Activity
{
    public string Title { get; set; }
    public Centre Centre { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

}

public class Centre
{
    public string Name { get; set; }
}

So what is the type-safe way using the new QueryOver extensions that will enable me to remove these magic strings?

Body:
This is what you want:

Restrictions.And(
    Restrictions.Lt(Projections.Property<Activity>(x => x.StartDate),
                    quarter.StartDate),
    Restrictions.Gt(Projections.Property<Activity>(x => x.EndDate),
                    quarter.EndDate)))

Sidenote: property names are not magic strings.


问:
Template pointer to a member function - getter
So i'm making a sorting function and i want it to sort my elements depending on the getter i give it.
The problem is my getter is const and thats why my current code doesn't work. If i remove const it works just fine.

```<code>struct User {
    string name;
    string getX() const { return name; } //// doesnt work with this
    string getX() { return name; }       //// this works fine. but i need my getter to be const
};

template <typename ElemType, typename MemberType>
void _sort(std::vector<ElemType>& vec, MemberType(ElemType::* member)(), bool ascending = true)
{
    for (int j = 0; j < vec.size() - 1; ++j)
        for (int i = 0; i < vec.size() - j - 1; ++i)
            if (((vec[i].*member)() < (vec[i + 1].*member)()) ^ ascending)
                swap(vec[i], vec[i + 1]);
}

int main()
{
    vector<User> a{ User{"Z"}, User{"E"}, User{"B"}, User{"R"}, User{"A"} };

    for (auto e : a)
        cout << e.name << " ";
    cout << endl;

    _sort(a, &User::getX);

    for (auto e : a)
        cout << e.name << " ";
    cout << endl;

    return 0;
}
</code>```

What do i do to make it work with const getter

答:
Just make the parameter const as well:

```<code>template <typename ElemType, typename MemberType>
void _sort(std::vector<ElemType>& vec, MemberType(ElemType::* member)() const, bool ascending = true)
________________________________________________________________________^^^^^
</code>```

Or don't make the parameter that specific:

```<code>template <typename ElemType, typename MemberType>
void _sort(std::vector<ElemType>& vec, MemberType member, bool ascending = true)
</code>```

The former won't work if the getter isn't const, while the latter will work with anything. If you pass the latter a function that cannot be called like (vec[i].*member)(), then the compilation error will be there instead of in the signature of _sort.

Body:
So i'm making a sorting function and i want it to sort my elements depending on the getter i give it.
The problem is my getter is const and thats why my current code doesn't work. If i remove const it works just fine.

struct User {
    string name;
    string getX() const { return name; } //// doesnt work with this
    string getX() { return name; }       //// this works fine. but i need my getter to be const
};

template <typename ElemType, typename MemberType>
void _sort(std::vector<ElemType>& vec, MemberType(ElemType::* member)(), bool ascending = true)
{
    for (int j = 0; j < vec.size() - 1; ++j)
        for (int i = 0; i < vec.size() - j - 1; ++i)
            if (((vec[i].*member)() < (vec[i + 1].*member)()) ^ ascending)
                swap(vec[i], vec[i + 1]);
}

int main()
{
    vector<User> a{ User{"Z"}, User{"E"}, User{"B"}, User{"R"}, User{"A"} };

    for (auto e : a)
        cout << e.name << " ";
    cout << endl;

    _sort(a, &User::getX);

    for (auto e : a)
        cout << e.name << " ";
    cout << endl;

    return 0;
}

What do i do to make it work with const getter

Body:
Just make the parameter const as well:

template <typename ElemType, typename MemberType>
void _sort(std::vector<ElemType>& vec, MemberType(ElemType::* member)() const, bool ascending = true)
________________________________________________________________________^^^^^

Or don't make the parameter that specific:

template <typename ElemType, typename MemberType>
void _sort(std::vector<ElemType>& vec, MemberType member, bool ascending = true)

The former won't work if the getter isn't const, while the latter will work with anything. If you pass the latter a function that cannot be called like (vec[i].*member)(), then the compilation error will be there instead of in the signature of _sort.


问:
How can i get make a table model work efficiently?
So,i am making an app for making timetables. and i have  run into a problem.
I have two models . Timetable and Content.

```<code>class Timetable(models.Model):

title=models.CharField(max_length=50)
start_time=models.TimeField(default="8:0")
end_time=models.TimeField(default="4:0")
entries=models.IntegerField(default=3)
theme=models.ForeignKey(Theme,on_delete=models.CASCADE,null=True)
def __str__(self):
    return self.title

def get_absoulte_url(self):
    return reverse('timetable-detail',args=[str(self.id)])

class CellEntry(models.Model):

parent_table=models.ForeignKey(Timetable,on_delete=models.CASCADE)
content=models.CharField(max_length=30)

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

How can i make a form such that i can get the two models to behave like a table in excel? How can i set the value of multiple cellentry's parent_table attribute to be the same value in a view?

答:
here is a sample code. Guess you can get some idea from here.</p>

```<code>def content_add_view(request):

LectureFormset = modelformset_factory(Lecture, fields=('lecture_title', 'lecture_content', 'youtube_url'))

# if the request is post and the form is valid than save the form
if request.method == 'POST':
    content_add_form = ContentAddForm(request.POST or None, request.FILES or None)
    formset = LectureFormset(request.POST or None, request.FILES or None)

    if content_add_form.is_valid():
        course = content_add_form.save(commit=False)
        course.user = request.user
        course.save()

        # looping through the formset as we need multiple fields saving it in same form. here we get the data and than save it
        if formset.is_valid():
            for f in formset:
                try:
                    video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url'))
                    video.save()

                except Exception as e:
                    break
            return redirect('teacher-profile')
        else:
            print('formsset is invalid')

else:
    content_add_form = ContentAddForm()
    formset = LectureFormset(queryset=Lecture.objects.none())

context = {

    'contentForm': content_add_form,
    'formset': formset,
}

return render(request, 'apps/contentAdd.html', context)
</code>```

Body:
So,i am making an app for making timetables. and i have  run into a problem.
I have two models . Timetable and Content.

class Timetable(models.Model):

title=models.CharField(max_length=50)
start_time=models.TimeField(default="8:0")
end_time=models.TimeField(default="4:0")
entries=models.IntegerField(default=3)
theme=models.ForeignKey(Theme,on_delete=models.CASCADE,null=True)
def __str__(self):
    return self.title

def get_absoulte_url(self):
    return reverse('timetable-detail',args=[str(self.id)])

class CellEntry(models.Model):

parent_table=models.ForeignKey(Timetable,on_delete=models.CASCADE)
content=models.CharField(max_length=30)

def __str__(self):
    return self.content

How can i make a form such that i can get the two models to behave like a table in excel? How can i set the value of multiple cellentry's parent_table attribute to be the same value in a view?

Body:
here is a sample code. Guess you can get some idea from here.

def content_add_view(request):

LectureFormset = modelformset_factory(Lecture, fields=('lecture_title', 'lecture_content', 'youtube_url'))

# if the request is post and the form is valid than save the form
if request.method == 'POST':
    content_add_form = ContentAddForm(request.POST or None, request.FILES or None)
    formset = LectureFormset(request.POST or None, request.FILES or None)

    if content_add_form.is_valid():
        course = content_add_form.save(commit=False)
        course.user = request.user
        course.save()

        # looping through the formset as we need multiple fields saving it in same form. here we get the data and than save it
        if formset.is_valid():
            for f in formset:
                try:
                    video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url'))
                    video.save()

                except Exception as e:
                    break
            return redirect('teacher-profile')
        else:
            print('formsset is invalid')

else:
    content_add_form = ContentAddForm()
    formset = LectureFormset(queryset=Lecture.objects.none())

context = {

    'contentForm': content_add_form,
    'formset': formset,
}

return render(request, 'apps/contentAdd.html', context)


问:
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>```

答:
```<code>var b = browserify({
        entries: [paths.programAppjs],
        cache: {},
        packageCache: {},
        plugin: [watchify]
      })
      .transform(babelify.configure({
        presets : ["es2015","react"],
        env: {
            development: {
                plugins: [
                    ["react-transform", {
                    transforms: [{
                        transform: "livereactload/babel-transform",
                        imports: ["react"]
                    }]
                    }],
                "transform-class-properties",
                "transform-object-rest-spread"
            ]
        }
        }
    }));

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

    function bundle() {
    console.log('start gulp');
    b.bundle()
        .on('error', console.error)
        .on('log', function (msg) {console.log(time()+" "+ appname+" "+msg);})
        .pipe(fs.createWriteStream('./public/js/bundle.js'));
        console.log('finish gulp'+time());
    }
</code>```

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 {
.
.
.
}


问:
Python on Electron framework
I am trying to write a cross-platform desktop app using web technologies (HTML5, CSS, and JS). I took a look at some frameworks and decided to use the Electron framework.

I've already done the app in Python, so I want to know if is possible to write cross-platform desktop applications using Python on the Electron framework?

答:
With electron-django app I am developing I used pyinstaller to get my django app compiled, then just spawn its child process and it works, please notice pyinstaller may not recognize all modules or dist folder. there are plenty examples online on how to get a workaround for that filling the .specs file and amending the dist folder adding the files you may need.
pyinstaller usually tells you what went wrong in the terminal. hope it helps </p>

Title: Python on Electron framework


问:
Extract Email Address from Thunderbird Emails
I want to extract all the email addresses found in a Thunderbird email file. Sometimes the emails are incased in spaces, sometimes in <> and possibly other ways. I'm able to find where a @ occurs on each string, but how do I grab the characters before and after it that form the email?

Thanks.

答:
Regex was born for this kind of job. Here's a minimal console application that shows how you can use RegEx to extract all email addresses from one long block of text:

```<code>program Project25;

{$APPTYPE CONSOLE}

uses
  SysUtils, PerlRegex;

var PR: TPerlRegEx;
    TestString: string;

begin

  // Initialize a test string to include some email addresses. This would normally
  // be your eMail text.
  TestString := '<one@server.domain.xy>, another@otherserver.xyz';

  PR := TPerlRegEx.Create;
  try
    PR.RegEx := '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'; // <-- this is the actual regex used.
    PR.Options := PR.Options + [preCaseLess];
    PR.Compile;
    PR.Subject := TestString; // <-- tell the TPerlRegEx where to look for matches
    if PR.Match then
    begin
      // At this point the first matched eMail address is already in MatchedText, we should grab it
      WriteLn(PR.MatchedText); // Extract first address (one@server.domain.xy)
      // Let the regex engine look for more matches in a loop:
      while PR.MatchAgain do
        WriteLn(PR.MatchedText); // Extract subsequent addresses (another@otherserver.xyz)
    end;
  finally PR.Free;
  end;

  Readln;
end.
</code>```

See here for ways to get regular expressions for your older-then-XE version of Delphi:
http://www.regular-expressions.info/delphi.html

Body:
Regex was born for this kind of job. Here's a minimal console application that shows how you can use RegEx to extract all email addresses from one long block of text:

program Project25;

{$APPTYPE CONSOLE}

uses
  SysUtils, PerlRegex;

var PR: TPerlRegEx;
    TestString: string;

begin

  // Initialize a test string to include some email addresses. This would normally
  // be your eMail text.
  TestString := '<one@server.domain.xy>, another@otherserver.xyz';

  PR := TPerlRegEx.Create;
  try
    PR.RegEx := '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'; // <-- this is the actual regex used.
    PR.Options := PR.Options + [preCaseLess];
    PR.Compile;
    PR.Subject := TestString; // <-- tell the TPerlRegEx where to look for matches
    if PR.Match then
    begin
      // At this point the first matched eMail address is already in MatchedText, we should grab it
      WriteLn(PR.MatchedText); // Extract first address (one@server.domain.xy)
      // Let the regex engine look for more matches in a loop:
      while PR.MatchAgain do
        WriteLn(PR.MatchedText); // Extract subsequent addresses (another@otherserver.xyz)
    end;
  finally PR.Free;
  end;

  Readln;
end.

See here for ways to get regular expressions for your older-then-XE version of Delphi:
http://www.regular-expressions.info/delphi.html


问:
Howto OPENCV+CUDA+VideoCapture?
I have a machine with 2 Nvidia RTX GPU.
The main task is to decode an h264 video from an IP camera and encode raw frames to JPEG with GPU.

I built opencv + cuda from sources by:

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules -D WITH_CUDA=ON -D WITH_TBB=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_QT=OFF -D WITH_NVCUVID -D WITH_NVCUVID=ON -D CMAKE_C_COMPILER=/usr/bin/gcc-6 ..
make
sudo make install
</code>```

I have a simple program which captures RTSP and saves JPEGs:

```<code>#include <strings.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/cuda.hpp>

using namespace std;

int main(int argc, char** argv)
{
    if ( argc != 2 ) {
      printf("no args\n");
      return -1;
    }
    cv::Mat frame;
    cv::VideoCapture cap;
    cap.open(argv[1]);
    if (!cap.isOpened()) {
        printf("ERROR! Unable to open camera\n");
        return -1;
    }
    printf("Start grabbing\n");
    for (;;)
    {
        cap.read(frame);
        if (frame.empty()) {
            printf("ERROR! blank frame grabbed\n");
            break;
        }
        vector<int> p;
        vector<unsigned char> buf;
        p.push_back(cv::IMWRITE_JPEG_QUALITY);
        p.push_back(50);
        imencode(".jpg", frame, buf, p);
        // Do something with buf ......
        printf("READY JPEG\n");
    }
    return 0;
}
</code>```

CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 2.8)
project( test_jpeg_cpu )
find_package( OpenCV REQUIRED )
find_package( CUDA REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} ${CUDA_INCLUDE_DIRS} )
add_executable( test_jpeg_cpu test_jpeg_cpu.cpp )
target_link_libraries( test_jpeg_cpu ${OpenCV_LIBS} ${CUDA_LIBRARIES} cuda ${CMAKE_DL_LIBS} )
</code>```

But it uses only CPU. What do I have to change to make this program use GPU?

Thanks in advance.

答:
You're using the imwrite API which uses libjpeg on the back end for CPU based encoding. If you want to use the GPU, you'll need to use the cv::cudacodec::createVideoWriter API (assuming it has been built into your OpenCV installation).

There is example code for GPU-accelerated video encoding in the OpenCV source repo.

Title: Howto OPENCV+CUDA+VideoCapture?

Body:
I have a machine with 2 Nvidia RTX GPU.
The main task is to decode an h264 video from an IP camera and encode raw frames to JPEG with GPU.

I built opencv + cuda from sources by:

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules -D WITH_CUDA=ON -D WITH_TBB=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_QT=OFF -D WITH_NVCUVID -D WITH_NVCUVID=ON -D CMAKE_C_COMPILER=/usr/bin/gcc-6 ..
make
sudo make install

I have a simple program which captures RTSP and saves JPEGs:

#include <strings.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/cuda.hpp>

using namespace std;

int main(int argc, char** argv)
{
    if ( argc != 2 ) {
      printf("no args\n");
      return -1;
    }
    cv::Mat frame;
    cv::VideoCapture cap;
    cap.open(argv[1]);
    if (!cap.isOpened()) {
        printf("ERROR! Unable to open camera\n");
        return -1;
    }
    printf("Start grabbing\n");
    for (;;)
    {
        cap.read(frame);
        if (frame.empty()) {
            printf("ERROR! blank frame grabbed\n");
            break;
        }
        vector<int> p;
        vector<unsigned char> buf;
        p.push_back(cv::IMWRITE_JPEG_QUALITY);
        p.push_back(50);
        imencode(".jpg", frame, buf, p);
        // Do something with buf ......
        printf("READY JPEG\n");
    }
    return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)
project( test_jpeg_cpu )
find_package( OpenCV REQUIRED )
find_package( CUDA REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} ${CUDA_INCLUDE_DIRS} )
add_executable( test_jpeg_cpu test_jpeg_cpu.cpp )
target_link_libraries( test_jpeg_cpu ${OpenCV_LIBS} ${CUDA_LIBRARIES} cuda ${CMAKE_DL_LIBS} )

But it uses only CPU. What do I have to change to make this program use GPU?

Thanks in advance.


问:
MYSQL How to make relation with no constrain
Hello i am trying to figure it out this one.

I have 2 Tables

```<code>Sessions
id_session

Session_Requests
id_session
id_request
url
</code>```

How can i make a relation between id_session that when i delete the session
the requests will still remain with that id_session

```<code>EX:
Session id : 0923jguj45g8342

Request
id_session = 0923jguj45g8342
id_request = 1
url = https://example.com
</code>```

When i delete the session with a relation i have a constraint that i cannot delete sessions anymore, or put null instead of session that is not good.

I want to have the relation so when i delete the Requests table will remain untouched.

Is this possible ?

答:
Is this possible ?

Assuming that you have a foreign key on that column: no, this is not possible. You can't have a foreign key holding a value that does not exist in the parent table/column.

MySQL offers a kit of possible referential actions that occur automatically when the reference row is deleted: cascade to drop the child record, set null to set the child key to null, or restrict to prevent the deletion. If one of those satisfies fits your use case, you can use it.

A possible alternative would be to create an additional column in the parent table that represents the status of the session, like is_deleted with a boolean datatype, and that you can set to some specific value (eg 1) instead of deleting the record. This let you store the information without breaking the key.

Body:
Hello i am trying to figure it out this one.

I have 2 Tables

Sessions
id_session

Session_Requests
id_session
id_request
url

How can i make a relation between id_session that when i delete the session
the requests will still remain with that id_session

EX:
Session id : 0923jguj45g8342

Request
id_session = 0923jguj45g8342
id_request = 1
url = https://example.com

When i delete the session with a relation i have a constraint that i cannot delete sessions anymore, or put null instead of session that is not good.

I want to have the relation so when i delete the Requests table will remain untouched.

Is this possible ?


问:
How create value use the selected category name?
I have input label for Title, I need Title to use the selected category name.

```<code><!-- parent_id -->
<?php $parentIdError = (isset($errors) and $errors->has('category_id')) ? ' is-invalid' : ''; ?>
<div class="form-group row required">
    <label class="col-md-3 col-form-label{{ $parentIdError }}">{{ t('Category') }} <sup>*</sup></label>
    <div class="col-md-8">
        <select name="parent_id" id="parentId" class="form-control selecter{{ $parentIdError }}">
            <option value="0" data-type=""
                    @if (old('parent_id')=='' or old('parent_id')==0)
                        selected="selected"
                    @endif
            > {{ t('Select a category') }} </option>
            @foreach ($categories as $cat)
                <option value="{{ $cat->tid }}" data-type="{{ $cat->type }}"
                        @if (old('parent_id')==$cat->tid)
                            selected="selected"
                        @endif
                > {{ $cat->name }} </option>
            @endforeach
        </select>
        <input type="hidden" name="parent_type" id="parent_type" value="{{ old('parent_type') }}">
    </div>
</div>

<!-- category_id -->
<?php $categoryIdError = (isset($errors) and $errors->has('category_id')) ? ' is-invalid' : ''; ?>
<div id="subCatBloc" class="form-group row required">
    <label class="col-md-3 col-form-label{{ $categoryIdError }}">{{ t('Sub-Category') }} <sup>*</sup></label>
    <div class="col-md-8">
        <select name="category_id" id="categoryId" class="form-control selecter{{ $categoryIdError }}">
            <option value="0"
                    @if (old('category_id')=='' or old('category_id')==0)
                        selected="selected"
                    @endif
            > {{ t('Select a sub-category') }} </option>
        </select>
    </div>
</div>

<!-- title -->
<?php $titleError = (isset($errors) and $errors->has('title')) ? ' is-invalid' : ''; ?>
<div class="form-group row required">
    <label class="col-md-3 col-form-label" for="title">{{ t('Title') }} <sup>*</sup></label>
    <div class="col-md-8">
        <input id="title" name="title" placeholder="{{ t('Job title') }}" class="form-control input-md{{ $titleError }}"
               type="text" value="{{ old('title') }}">
        <small id="" class="form-text text-muted">{{ t('A great title needs at least 60 characters.') }}</small>
    </div>
</div>
</code>```

答:
I have removed some of your laravel code and syntax, but you get the idea, it will work same

$('#categoryId').on('change', function() {
  if ($('option:selected', this).val() != '0')
    var val = $('option:selected', this).text();
  $("#title").val(val);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="subCatBloc" class="form-group row required">
  <label class="col-md-3 col-form-label">Category <sup>*</sup></label>
  <div class="col-md-8">
    <select name="category_id" id="categoryId" class="form-control">
      <option value="0">select category</option>
      <option value="1">Text 1</option>
      <option value="2">Text 2</option>
    </select>
  </div>
</div>

<div class="form-group row required">
  <label class="col-md-3 col-form-label" for="title">Title <sup>*</sup></label>
  <div class="col-md-8">
    <input id="title" name="title" placeholder="Job title" class="form-control input-md" type="text" value="">
    <small id="" class="form-text text-muted">A great title needs at least 60 characters.</small>
  </div>
</div></code>```

Body:
I have input label for Title, I need Title to use the selected category name.

<?php $parentIdError = (isset($errors) and $errors->has('category_id')) ? ' is-invalid' : ''; ?>

    {{ t('Category') }} *

        <select name="parent_id" id="parentId" class="form-control selecter{{ $parentIdError }}">
            <option value="0" data-type=""
                    @if (old('parent_id')=='' or old('parent_id')==0)
                        selected="selected"
                    @endif
            > {{ t('Select a category') }} </option>
            @foreach ($categories as $cat)
                <option value="{{ $cat->tid }}" data-type="{{ $cat->type }}"
                        @if (old('parent_id')==$cat->tid)
                            selected="selected"
                        @endif
                > {{ $cat->name }} </option>
            @endforeach
        </select>
        <input type="hidden" name="parent_type" id="parent_type" value="{{ old('parent_type') }}">

<?php $categoryIdError = (isset($errors) and $errors->has('category_id')) ? ' is-invalid' : ''; ?>

    {{ t('Sub-Category') }} *

        <select name="category_id" id="categoryId" class="form-control selecter{{ $categoryIdError }}">
            <option value="0"
                    @if (old('category_id')=='' or old('category_id')==0)
                        selected="selected"
                    @endif
            > {{ t('Select a sub-category') }} </option>
        </select>

<?php $titleError = (isset($errors) and $errors->has('title')) ? ' is-invalid' : ''; ?>

    {{ t('Title') }} *

        <input id="title" name="title" placeholder="{{ t('Job title') }}" class="form-control input-md{{ $titleError }}"
               type="text" value="{{ old('title') }}">
        {{ t('A great title needs at least 60 characters.') }}

Body:
I have removed some of your laravel code and syntax, but you get the idea, it will work same

$('#categoryId').on('change', function() {
  if ($('option:selected', this).val() != '0')
    var val = $('option:selected', this).text();
  $("#title").val(val);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="subCatBloc" class="form-group row required">
  <label class="col-md-3 col-form-label">Category <sup>*</sup></label>
  <div class="col-md-8">
    <select name="category_id" id="categoryId" class="form-control">
      <option value="0">select category</option>
      <option value="1">Text 1</option>
      <option value="2">Text 2</option>
    </select>
  </div>
</div>

<div class="form-group row required">
  <label class="col-md-3 col-form-label" for="title">Title <sup>*</sup></label>
  <div class="col-md-8">
    <input id="title" name="title" placeholder="Job title" class="form-control input-md" type="text" value="">
    <small id="" class="form-text text-muted">A great title needs at least 60 characters.</small>
  </div>
</div>


问:
How can I update R using conda?
I installed Rstudio using anaconda. I think the R was also installed alongside with it (but I read somewhere that Rstudio doesn't come with R: Tell me if I am wrong).

From terminal: which R shows :/home/simo/anaconda3/bin/R.

I tried that:

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
sudo echo "deb http://cran.wustl.edu/bin/linux/ubuntu bionic-cran35/" | sudo tee -a /etc/apt/sources.list
sudo apt update
sudo apt upgrade
</code>```

but doesn't upgrade the version of R (still R version 3.5.1 (2018-07-02) -- "Feather Spray")

At the first place I want to install: dashHtmlComponents,  a dash library.

```<code>> install.packages("dashHtmlComponents")
Warning message:
package ‘dashHtmlComponents’ is not available (for R version 3.5.1)
>
</code>```

But from the dash documentation I read that at least version 3.0.2 of R is required.

What is wrong?

答:
It depends what OS you are on how you would go about doing that. The particular methods for Windows and MacOS are laid out on this page.

As far as if you have R (which it appears you do, but nonetheless), you can run install r-essentials --yes in the terminal (Mac) or Anaconda Prompt (PC). In Linux you can follow the steps here.

Once you do either of these, you should be able to use install.packages('dashHtmlComponents'). I am using R version 3.6.2 and it installs just fine.

Title: How can I update R using conda?

Body:
I installed Rstudio using anaconda. I think the R was also installed alongside with it (but I read somewhere that Rstudio doesn't come with R: Tell me if I am wrong).

From terminal: which R shows :/home/simo/anaconda3/bin/R.

I tried that:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
sudo echo "deb http://cran.wustl.edu/bin/linux/ubuntu bionic-cran35/" | sudo tee -a /etc/apt/sources.list
sudo apt update
sudo apt upgrade

but doesn't upgrade the version of R (still R version 3.5.1 (2018-07-02) -- "Feather Spray")

At the first place I want to install: dashHtmlComponents,  a dash library.

> install.packages("dashHtmlComponents")
Warning message:
package ‘dashHtmlComponents’ is not available (for R version 3.5.1)
>

But from the dash documentation I read that at least version 3.0.2 of R is required.

What is wrong?


问:
Can't create column in SQLite Android
I have a problem like this:

/SQLiteLog: (1) table ds_sinhvien has no column named id

E/SQLiteDatabase: Error inserting name=An id=1 class=MMTT2011

android.database.sqlite.SQLiteException: table ds_sinhvien has no
  column named id (code 1 SQLITE_ERROR): , while compiling: INSERT INTO
  ds_sinhvien(name,id,class) VALUES (?,?,?)

I don't know how to fix this, this is my dbhelper:

```<code>public class StudentDbHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "dbStudent";
    private static final String TB_STUDENT = "ds_sinhvien";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_CLASS = "class";
    public StudentDbHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
// TODO Auto-generated method stub
// tạo table
        String SQL_String = String.format("CREATE TABLE %s(%sINTEGER PRIMARY KEY, %s TEXT, %s TEXT)", TB_STUDENT,KEY_ID, KEY_NAME, KEY_CLASS);
        db.execSQL(SQL_String);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + TB_STUDENT);
// Create tables again
        onCreate(db);
    }
    public void insertStudent(Student student)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String nullColumnHack = null; // Allow null value
        ContentValues values = new ContentValues();
        if (student.getId() != -1)
        {
            values.put(KEY_ID, student.getId());
            values.put(KEY_NAME, student.getName());
            values.put(KEY_CLASS, student.getClassName());
            db.insert(TB_STUDENT, null, values);
        }
        db.close();
    }
</code>```

Thanks for helping me, i've tried to fix it for a very long time.

答:
```<code>%sINTEGER
</code>```

This makes the column name idINTEGER. Add the missing space between the name and type. You can then uninstall your app to delete the old database with this incorrect column name and make onCreate() execute again.

Title: Can't create column in SQLite Android

Body:
I have a problem like this:

/SQLiteLog: (1) table ds_sinhvien has no column named id

E/SQLiteDatabase: Error inserting name=An id=1 class=MMTT2011

android.database.sqlite.SQLiteException: table ds_sinhvien has no
  column named id (code 1 SQLITE_ERROR): , while compiling: INSERT INTO
  ds_sinhvien(name,id,class) VALUES (?,?,?)

I don't know how to fix this, this is my dbhelper:

public class StudentDbHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "dbStudent";
    private static final String TB_STUDENT = "ds_sinhvien";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_CLASS = "class";
    public StudentDbHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
// TODO Auto-generated method stub
// tạo table
        String SQL_String = String.format("CREATE TABLE %s(%sINTEGER PRIMARY KEY, %s TEXT, %s TEXT)", TB_STUDENT,KEY_ID, KEY_NAME, KEY_CLASS);
        db.execSQL(SQL_String);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + TB_STUDENT);
// Create tables again
        onCreate(db);
    }
    public void insertStudent(Student student)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String nullColumnHack = null; // Allow null value
        ContentValues values = new ContentValues();
        if (student.getId() != -1)
        {
            values.put(KEY_ID, student.getId());
            values.put(KEY_NAME, student.getName());
            values.put(KEY_CLASS, student.getClassName());
            db.insert(TB_STUDENT, null, values);
        }
        db.close();
    }

Thanks for helping me, i've tried to fix it for a very long time.

Body:
%sINTEGER

This makes the column name idINTEGER. Add the missing space between the name and type. You can then uninstall your app to delete the old database with this incorrect column name and make onCreate() execute again.


问:
IOError: [Errno 28] No space left on device while installing TensorFlow
I am trying to install TensorFlow in my local directory using the following command.

```<code>export TF_BINARY_URL=http://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl
pip install --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL
</code>```

I am getting the following error:

```<code>IOError: [Errno 28] No space left on device
</code>```

Then I did df to see the following:

```<code>Filesystem             1K-blocks       Used   Available Use% Mounted on
tmpfs                      10240      10240           0 100% /tmp
tmpfs                      10240      10240           0 100% /var/tmp
</code>```

Is there a way I can install TF without the temp files being downloaded in /tmp or /var/tmp? Thanks.

答:
Solution 1:
Pip won't re-download the package in this solution but in other solutions it does

Check the available disk space using df -h:

If you just need to change tmpfs size, you can remount it on-line with new size:

```<code>$ sudo mount -o remount,size=10G /tmp
$ sudo mount -o remount,size=10G /var/tmp
</code>```

Solution 2:
You can set the environment variable 'TMPDIR' for pip

```<code>$ export TMPDIR=$HOME/new/tmp/dir
$ pip install --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL
</code>```

Solution 3:
With custom cache/temp directory

```<code>$ pip install --cache-dir=$HOME/new/tmp/dir/  --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL
</code>```

Solution 4:
With no cache directory

```<code>pip install --no-cache-dir --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL
</code>```

Body:
I am trying to install TensorFlow in my local directory using the following command.

export TF_BINARY_URL=http://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl
pip install --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL

I am getting the following error:

IOError: [Errno 28] No space left on device

Then I did df to see the following:

Filesystem             1K-blocks       Used   Available Use% Mounted on
tmpfs                      10240      10240           0 100% /tmp
tmpfs                      10240      10240           0 100% /var/tmp

Is there a way I can install TF without the temp files being downloaded in /tmp or /var/tmp? Thanks.

Body:
Solution 1:
Pip won't re-download the package in this solution but in other solutions it does

Check the available disk space using df -h:

If you just need to change tmpfs size, you can remount it on-line with new size:

$ sudo mount -o remount,size=10G /tmp
$ sudo mount -o remount,size=10G /var/tmp

Solution 2:
You can set the environment variable 'TMPDIR' for pip

$ export TMPDIR=$HOME/new/tmp/dir
$ pip install --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL

Solution 3:
With custom cache/temp directory

$ pip install --cache-dir=$HOME/new/tmp/dir/  --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL

Solution 4:
With no cache directory

pip install --no-cache-dir --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL


问:
Cell shading effect in OpenGL ES 2.0/3.0
I applied cell shading effect to the object, like:

This works well, but there are many conditional checks ("if" statements) in the fragment shader:

```<code>#version 300 es
precision lowp float;

in float v_CosViewAngle;
in float v_LightIntensity;

const lowp vec3 defaultColor = vec3(0.1, 0.7, 0.9);

void main() {
    lowp float intensity = 0.0;
    if (v_CosViewAngle > 0.33) {
        intensity = 0.33;
        if (v_LightIntensity > 0.76) {
            intensity = 1.0;
        } else if (v_LightIntensity > 0.51) {
            intensity = 0.84;
        } else if (v_LightIntensity > 0.26) {
            intensity = 0.67;
        } else if (v_LightIntensity > 0.1) {
            intensity = 0.50;
        }
    }
    outColor = vec4(defaultColor * intensity, 1.0);
}
</code>```

I guess so many checks in the fragment shader can ultimately affect performance. In addition, shader size is increasing. Especially if there will be even more cell shading levels.

Is there any other way to get this effect? Maybe some glsl-function can be used here?

Thanks in advance!

答:
Store your color bands in a Nx1 texture, do a texture lookup using v_LightIntensity as your texture coordinate. Want a different shading level count then just change the texture.

EDIT Store an NxM texture, doing a lookup using vLightIntensity and v_CosViewAngle as a 2D coordinate, and you can kill branches completely.

Body:
I applied cell shading effect to the object, like:

This works well, but there are many conditional checks ("if" statements) in the fragment shader:

#version 300 es
precision lowp float;

in float v_CosViewAngle;
in float v_LightIntensity;

const lowp vec3 defaultColor = vec3(0.1, 0.7, 0.9);

void main() {
    lowp float intensity = 0.0;
    if (v_CosViewAngle > 0.33) {
        intensity = 0.33;
        if (v_LightIntensity > 0.76) {
            intensity = 1.0;
        } else if (v_LightIntensity > 0.51) {
            intensity = 0.84;
        } else if (v_LightIntensity > 0.26) {
            intensity = 0.67;
        } else if (v_LightIntensity > 0.1) {
            intensity = 0.50;
        }
    }
    outColor = vec4(defaultColor * intensity, 1.0);
}

I guess so many checks in the fragment shader can ultimately affect performance. In addition, shader size is increasing. Especially if there will be even more cell shading levels.

Is there any other way to get this effect? Maybe some glsl-function can be used here?

Thanks in advance!


问:
Calayer subclass problem
I am creating calayer subclass for carousel view.

My subclass is

@interface Carousellayer : CALayer {

}

I get an error message in

Cannot find interface declaration for 'CALayer', superclass of 'Carousellayer' in Carousellayer.h

答:
CALayer header files are not included by default, you need to import QuartzCore:

```<code>#import <QuartzCore/QuartzCore.h>
</code>```

And also link your application with the corresponding framework.

Title: Calayer subclass problem

Body:
CALayer header files are not included by default, you need to import QuartzCore:

#import <QuartzCore/QuartzCore.h>

And also link your application with the corresponding framework.


问:
In VBA, how to extract the string before a number from the text
From ActiveWorkbook.name, I would like to extract the strings that are before (left side of ) the numbers. Since I want to use the same code in multiple workbooks, the file names would be variable, but every file name has date info in the middle  (yyyymmdd).

In case of excel file, I can use the below formula, but can I apply the same kind of method in VBA?

```<code>=LEFT(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(A1)&1234567890))-1)
</code>```

Example: MyExcelWorkbook_Management_20200602_MyName.xlsm

In above case, I want to extract "MyExcelWorkbook_Management_".

答:
You could use Regular Expressions to extract any letters / underscores before the number as well

```<code>Dim str As String

str = "MyExcelWorkbook_Management_20200602_MyName.xlsm"

With CreateObject("vbscript.regexp")
    .Pattern = "^\D*"
    .Global = True

    MsgBox .Execute(str)(0)
End With
</code>```

Gives:

MyExcelWorkbook_Management_

Body:
From ActiveWorkbook.name, I would like to extract the strings that are before (left side of ) the numbers. Since I want to use the same code in multiple workbooks, the file names would be variable, but every file name has date info in the middle  (yyyymmdd).

In case of excel file, I can use the below formula, but can I apply the same kind of method in VBA?

=LEFT(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},ASC(A1)&1234567890))-1)

Example: MyExcelWorkbook_Management_20200602_MyName.xlsm

In above case, I want to extract "MyExcelWorkbook_Management_".

Body:
You could use Regular Expressions to extract any letters / underscores before the number as well

Dim str As String

str = "MyExcelWorkbook_Management_20200602_MyName.xlsm"

With CreateObject("vbscript.regexp")
    .Pattern = "^\D*"
    .Global = True

    MsgBox .Execute(str)(0)
End With

Gives:

MyExcelWorkbook_Management_


问:
Integrate multivariate python function with one positional argument
suppose I define a function of an unpackable array (e.g. list)

```<code>def f(params):
    a,b,c = params
    return a+b**2+c**2
</code>```

is there a way to integrate over only the first parameter? I tried

```<code>import scipy.integrate.quad as quad

def integrate(b,c):
    return quad(f,0,1,args=(b,c))
</code>```

but it returns an error because the function f only takes one positional argument. I guess I have to unpack it in the integration step, but unsure how.

Thanks!

答:
If these are the only two use cases for using this function you can do something like the following:

```<code>def f(*args):
    if len(args) == 1:
        a,b,c = args[0]
    else:
        a, b,c  = args
    return a+b**2+c**2
</code>```

This assumes that if you pass one argument to the function in can be unpacked and if you pass more than one you pass a, b, c directly.

In a more generic setting, you can define different behavior of a function depending on the input type using functools.singledispatch. In this case this would look as follows:

```<code>from functools import singledispatch

@singledispatch
def f(arg1, arg2=None, arg3=None):
    a, b, c = arg1
    return a+b**2+c**2

@f.register(int)
@f.register(float)
def _(arg1, arg2, arg3):
    return arg1+arg2**2+arg3**2
</code>```

The advantage of this would be that you can extend it for different input types if that is needed.

Body:
suppose I define a function of an unpackable array (e.g. list)

def f(params):
    a,b,c = params
    return a+b**2+c**2

is there a way to integrate over only the first parameter? I tried

import scipy.integrate.quad as quad

def integrate(b,c):
    return quad(f,0,1,args=(b,c))

but it returns an error because the function f only takes one positional argument. I guess I have to unpack it in the integration step, but unsure how.

Thanks!

Body:
If these are the only two use cases for using this function you can do something like the following:

def f(*args):
    if len(args) == 1:
        a,b,c = args[0]
    else:
        a, b,c  = args
    return a+b**2+c**2

This assumes that if you pass one argument to the function in can be unpacked and if you pass more than one you pass a, b, c directly.

In a more generic setting, you can define different behavior of a function depending on the input type using functools.singledispatch. In this case this would look as follows:

from functools import singledispatch

@singledispatch
def f(arg1, arg2=None, arg3=None):
    a, b, c = arg1
    return a+b**2+c**2

@f.register(int)
@f.register(float)
def _(arg1, arg2, arg3):
    return arg1+arg2**2+arg3**2

The advantage of this would be that you can extend it for different input types if that is needed.


问:
Max limit of message in SignalR
I am trying to send notifications through SignalR. It works perfectly.

But what is the maximum size of a message we can send through SignalR?

Does it have any official limit as such?

答:
In .Net Core 3+, You can configure SignalR in ConfigureServices method in your startup class.</p>

```<code>services.AddSignalR(o =>
{
    o.EnableDetailedErrors = true;
    o.MaximumReceiveMessageSize = 10240; // bytes
});
</code>```

Title: Max limit of message in SignalR

Body:
In .Net Core 3+, You can configure SignalR in ConfigureServices method in your startup class.

services.AddSignalR(o =>
{
    o.EnableDetailedErrors = true;
    o.MaximumReceiveMessageSize = 10240; // bytes
});


问:
Cannot figure out how to structure data for ViewPager2 from one Room entity using pojo
I am new to Android and need some help.
I'm making an App which manages expenses. I have room database table 'expenses':

CostEntry.java

```<code>@Entity(tableName = "expenses")
public class CostEntry {

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String category;
    private String name;
    private int cost;
    private String date;
    private String currency;

//....
}

</code>```

My activity shows all the expenses on a certain date.
Now, I want to make viewpager2 whose page will show all categories with theirs sums - in particular currency (number of pages equals number of different currencies).

So, I made a simple pojo:

TotalCostPojo.java

```<code>public class TotalCostPojo {

    public TotalCostPojo() {
    }

    private String currency;
    private List<String> category;
    private List<Integer> categoryCosts;

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public List<String> getCategory() {
        return category;
    }

    public void setCategory(List<String> category) {
        this.category = category;
    }

    public List<Integer> getCategoryCosts() {
        return categoryCosts;
    }

    public void setCategoryCosts(List<Integer> categoryCosts) {
        this.categoryCosts = categoryCosts;
    }
}
</code>```

But, I got an error:

error: Cannot figure out how to read this field from a cursor.
      private List categoryCosts; private List category;

This is my Dao:

```<code>@Query("SELECT DISTINCT currency, category, SUM (cost) AS categoryCosts FROM expenses WHERE date = :date group by category")
    LiveData<List<TotalCostPojo>> loadTotalCategoryCosts(String date);
</code>```

I had similar problem before, but then  I resolved it with @Relation annotations. I don't know how to do it here because there isn't more than one entity.

Thanks in advance.

答:
I think in Room there is no built-in way for what you want (as you've written it's not a case for @Relation annotation, since there is no two real tables to join).
I can only suggest workaround you can try (may be it's a obvious boilerplate, and you've expected for more elegance, but still is a way):

Add class CostPojo with fields: currency(String), category(String), categoryCosts(Integer).

Change the type of returning value in your loadTotalCategoryCosts to List<CostPojo>:

```<code>LiveData<List<CostPojo>> loadTotalCategoryCosts(String date);
</code>```

To get the needed data structure for your ViewPager you have to make your own transformation function from List<CostPojo> to List<TotalCostPojo>. For this you can play with LiveData Transformations or for example to add static auxilary method convertToTotalCost to your CostPojo class (input - List<CostPojo>, output - List<TotalCostPojo>).

UPDATE
For those who interested - final solution based on this answer made by author of the question is inside separate answer

Body:
I am new to Android and need some help.
I'm making an App which manages expenses. I have room database table 'expenses':

CostEntry.java

@Entity(tableName = "expenses")
public class CostEntry {

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String category;
    private String name;
    private int cost;
    private String date;
    private String currency;

//....
}

My activity shows all the expenses on a certain date.
Now, I want to make viewpager2 whose page will show all categories with theirs sums - in particular currency (number of pages equals number of different currencies).

So, I made a simple pojo:

TotalCostPojo.java

public class TotalCostPojo {

    public TotalCostPojo() {
    }

    private String currency;
    private List<String> category;
    private List<Integer> categoryCosts;

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public List<String> getCategory() {
        return category;
    }

    public void setCategory(List<String> category) {
        this.category = category;
    }

    public List<Integer> getCategoryCosts() {
        return categoryCosts;
    }

    public void setCategoryCosts(List<Integer> categoryCosts) {
        this.categoryCosts = categoryCosts;
    }
}

But, I got an error:

error: Cannot figure out how to read this field from a cursor.
      private List categoryCosts; private List category;

This is my Dao:

@Query("SELECT DISTINCT currency, category, SUM (cost) AS categoryCosts FROM expenses WHERE date = :date group by category")
    LiveData<List<TotalCostPojo>> loadTotalCategoryCosts(String date);

I had similar problem before, but then  I resolved it with @Relation annotations. I don't know how to do it here because there isn't more than one entity.

Thanks in advance.

Body:
I think in Room there is no built-in way for what you want (as you've written it's not a case for @Relation annotation, since there is no two real tables to join).
I can only suggest workaround you can try (may be it's a obvious boilerplate, and you've expected for more elegance, but still is a way):

Add class CostPojo with fields: currency(String), category(String), categoryCosts(Integer).

Change the type of returning value in your loadTotalCategoryCosts to List<CostPojo>:

LiveData<List<CostPojo>> loadTotalCategoryCosts(String date);

To get the needed data structure for your ViewPager you have to make your own transformation function from List<CostPojo> to List<TotalCostPojo>. For this you can play with LiveData Transformations or for example to add static auxilary method convertToTotalCost to your CostPojo class (input - List<CostPojo>, output - List<TotalCostPojo>).

UPDATE
For those who interested - final solution based on this answer made by author of the question is inside separate answer


问:
Replace Contents of Request Object in Slim Middleware
I'm encrypting a header value and params of the request object. In the middleware.. I decrypt the values and would I like replace the values.

Tried the below. Doesnt seem to be working.
new \Slim\Http\Request($method, $uri, $headers, $cookies, $serverParams, $body)

```<code>For -  $response = $next($request, $response); I tried the below

$response = $next(new \Slim\Http\Request($request->getMethod(),$request->getUri(), $arr, $request->getCookieParams(), $request->getServerParams(), $request->getBody()), $response);
</code>```

Any help would be very much appreciated.

答:
Try this to replace the header value:

$value = $response->getHeaderLine('MyHeader');

// ...

$response = $response->withHeader('MyHeader', $value);
```

Body:
I'm encrypting a header value and params of the request object. In the middleware.. I decrypt the values and would I like replace the values.

Tried the below. Doesnt seem to be working.
new \Slim\Http\Request($method, $uri, $headers, $cookies, $serverParams, $body)

For -  $response = $next($request, $response); I tried the below

$response = $next(new \Slim\Http\Request($request->getMethod(),$request->getUri(), $arr, $request->getCookieParams(), $request->getServerParams(), $request->getBody()), $response);

Any help would be very much appreciated.


问:
How increase heap size in android studio?
I have a problem that on my PC android studio are laging. It's not the newest a notebok but I have 8gb RAM. I try to increase memory to android studio by editing files: android-studio\bin\studio.exe.vmoptions and android-studio\bin\studio64.exe.vmoptions but it dosen't help me (allocate heap size dosen't change - it's 445M).

My example studio64.exe.vmoptions is:

```<code>-Xms128m
-Xmx2048m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=200m
-XX:+UseCompressedOops
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djna.nosys=true
-Djna.boot.library.path=

-XX:MaxJavaStackTraceDepth=-1
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-ea
</code>```

Do you know whhy heap size dosen't change (of course after restart android studio)

答:
allocate heap size doesn't change - it's 445M

because your windows handle it

reading the source

If you are working (1) on a large project, or

(2) your system has _!_a_lot_of_RAM_!_,

you can improve performance by increasing the maximum heap size

is it your case?..

or maybe you need to do some alternative:

described in "Configure the IDE for low-memory machines" menu point (my choice by the way) at the same source?

whish you all of good in any case!

Body:
I have a problem that on my PC android studio are laging. It's not the newest a notebok but I have 8gb RAM. I try to increase memory to android studio by editing files: android-studio\bin\studio.exe.vmoptions and android-studio\bin\studio64.exe.vmoptions but it dosen't help me (allocate heap size dosen't change - it's 445M).

My example studio64.exe.vmoptions is:

-Xms128m
-Xmx2048m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=200m
-XX:+UseCompressedOops
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djna.nosys=true
-Djna.boot.library.path=

-XX:MaxJavaStackTraceDepth=-1
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-ea

Do you know whhy heap size dosen't change (of course after restart android studio)


问:
SQL: display newest entry
I'm not really much of a developer, I only started self-learning VBA for Excel this year and I only started working with SQL two days ago...

That said: I'm trying to write a query that only shows the newest entry for each INVBTICKETNO based on ITTRANDATE but I can't seem to figure it out.

```<code>SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Oder No]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,INVENTORY_BIN.INVBTICKETNO AS [Ticket No]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,INVENTORY_TRAN.ITSOURCE AS Source
 ,INVENTORY_TRAN.ITCOMMENT AS Comment
 ,MAX(INVENTORY_TRAN.ITTRANDATE) AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO No]
FROM dbo.INVENTORY_BIN INVENTORY_BIN
INNER JOIN dbo.INVENTORY_ITEM_TAB INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.WHSNAME WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.VALID_BIN VALID_BIN
  ON INVENTORY_BIN.INVBBINNO = VALID_BIN.BIN_ID
    AND INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE
LEFT OUTER JOIN dbo.CUSTOMER CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
LEFT OUTER JOIN dbo.ORDERS ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.PRODUCT_CODE PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
LEFT OUTER JOIN dbo.SALESAGENT SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
WHERE ORDERS.FOR_INVT_FLG = 'R'
GROUP BY INVENTORY_BIN.INVBITEMNO
        ,INVENTORY_BIN.INVBBINNO
        ,INVENTORY_BIN.INVBQTYONHAND
        ,INVENTORY_BIN.DATE_OF_INVENTORY
        ,INVENTORY_BIN.EXTENDED_CST
        ,INVENTORY_ITEM_TAB.DESCR
        ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT
        ,WHSNAME.WHSNNAME
        ,VALID_BIN.BIN_TYPE
        ,INVENTORY_TRAN.ITSOURCE
        ,CUSTOMER.CSNAME
        ,ORDERS.ORDER_NO
        ,ORDERS.CUST_PO_NO
        ,ORDERS.QTY_ORDERED
        ,PRODUCT_CODE.DESCR
        ,SALESAGENT.SANAME
        ,ORDERS.FOR_INVT_FLG
        ,INVENTORY_BIN.INVBTICKETNO
        ,INVENTORY_TRAN.ITCOMMENT
ORDER BY [Date of Inventory]
</code>```

答:
I rebuilt the query from scratch and it seems to work, though I don't have nearly all the columns added back in yet.</p>

```<code>SELECT
  MAX(INVENTORY_TRAN.ITTRANDATE) AS expr1
 ,INVENTORY_BIN.INVBTICKETNO
 ,ORDERS.ORDER_NO
 ,ORDERS.FOR_INVT_FLG
FROM dbo.INVENTORY_TRAN
INNER JOIN dbo.INVENTORY_BIN
  ON INVENTORY_TRAN.ITTICKETNO = INVENTORY_BIN.INVBTICKETNO
INNER JOIN dbo.ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
WHERE ORDERS.FOR_INVT_FLG = 'r'
GROUP BY INVENTORY_BIN.INVBTICKETNO
        ,ORDERS.ORDER_NO
        ,ORDERS.FOR_INVT_FLG
ORDER BY INVENTORY_BIN.INVBTICKETNO
</code>```

Title: SQL: display newest entry

Body:
I'm not really much of a developer, I only started self-learning VBA for Excel this year and I only started working with SQL two days ago...

That said: I'm trying to write a query that only shows the newest entry for each INVBTICKETNO based on ITTRANDATE but I can't seem to figure it out.

SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Oder No]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,INVENTORY_BIN.INVBTICKETNO AS [Ticket No]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,INVENTORY_TRAN.ITSOURCE AS Source
 ,INVENTORY_TRAN.ITCOMMENT AS Comment
 ,MAX(INVENTORY_TRAN.ITTRANDATE) AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO No]
FROM dbo.INVENTORY_BIN INVENTORY_BIN
INNER JOIN dbo.INVENTORY_ITEM_TAB INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.WHSNAME WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.VALID_BIN VALID_BIN
  ON INVENTORY_BIN.INVBBINNO = VALID_BIN.BIN_ID
    AND INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE
LEFT OUTER JOIN dbo.CUSTOMER CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
LEFT OUTER JOIN dbo.ORDERS ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.PRODUCT_CODE PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
LEFT OUTER JOIN dbo.SALESAGENT SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
WHERE ORDERS.FOR_INVT_FLG = 'R'
GROUP BY INVENTORY_BIN.INVBITEMNO
        ,INVENTORY_BIN.INVBBINNO
        ,INVENTORY_BIN.INVBQTYONHAND
        ,INVENTORY_BIN.DATE_OF_INVENTORY
        ,INVENTORY_BIN.EXTENDED_CST
        ,INVENTORY_ITEM_TAB.DESCR
        ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT
        ,WHSNAME.WHSNNAME
        ,VALID_BIN.BIN_TYPE
        ,INVENTORY_TRAN.ITSOURCE
        ,CUSTOMER.CSNAME
        ,ORDERS.ORDER_NO
        ,ORDERS.CUST_PO_NO
        ,ORDERS.QTY_ORDERED
        ,PRODUCT_CODE.DESCR
        ,SALESAGENT.SANAME
        ,ORDERS.FOR_INVT_FLG
        ,INVENTORY_BIN.INVBTICKETNO
        ,INVENTORY_TRAN.ITCOMMENT
ORDER BY [Date of Inventory]

Body:
I rebuilt the query from scratch and it seems to work, though I don't have nearly all the columns added back in yet.

SELECT
  MAX(INVENTORY_TRAN.ITTRANDATE) AS expr1
 ,INVENTORY_BIN.INVBTICKETNO
 ,ORDERS.ORDER_NO
 ,ORDERS.FOR_INVT_FLG
FROM dbo.INVENTORY_TRAN
INNER JOIN dbo.INVENTORY_BIN
  ON INVENTORY_TRAN.ITTICKETNO = INVENTORY_BIN.INVBTICKETNO
INNER JOIN dbo.ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
WHERE ORDERS.FOR_INVT_FLG = 'r'
GROUP BY INVENTORY_BIN.INVBTICKETNO
        ,ORDERS.ORDER_NO
        ,ORDERS.FOR_INVT_FLG
ORDER BY INVENTORY_BIN.INVBTICKETNO


问:
Set background image in thymleaf with dynamic url
I want to show a background image in thymleaf which url is coming from backend spring boot

```<code><div class="card-img-top" th:style="background-image:url(/assets/img/banner-anout.jpg)" > </div>
</code>```

This is the element
I want to fill it with a variable like

```<code><div class="card-img-top" th:style="background-image:url(${product.image})" > </div>
</code>```

I tried with several approach like below

```<code><div class="card-img-top" th:style="background: url{[[@{${product.image}]]}" > </div>
</code>```

But it does not work.Can anyone help?

答:
You can build the string you need by concatenating the literal parts with the Thymeleaf expression:</p>

```<code><div class="card-img-top"
     th:style="'background-image:url(' + ${product.image}+ ')'" >
</div>
</code>```

Body:
I want to show a background image in thymleaf which url is coming from backend spring boot

This is the element
I want to fill it with a variable like

I tried with several approach like below

But it does not work.Can anyone help?

Body:
You can build the string you need by concatenating the literal parts with the Thymeleaf expression:

<div class="card-img-top"
     th:style="'background-image:url(' + ${product.image}+ ')'" >
</div>


问:
Local git repo creation
I have code base checked out from svn. (code_base). I want to create a local git repo from this code base and then use git branches to play with it. So, I am expecting a structure like follows:

currently available code = c:/code_base

git repo on same machine = c:/repo_head  (Based on c:/code_base)

git clients from newly repo = c:/repo_client1 c:/repo_client2

I am trying to create a bare repo (repo_head) and then trying to add code_base but it does not seem to work. I am getting lot of errors.
What is the best way to go about it?

答:
I've had surprising success initing and running a git repo right IN a svn working directory. So, I check out from SVN to a directory, cd into it, do git init, and very first thing put the string ".svn" into .gitignore.

The way I'm working, git's master branch is in sync with SVN (via manual ups and cis). My teammates are developing on the main SVN trunk, and I'm frequently pulling down their work to the SVN working directory and committing that to my local git master.

I have a git development branch for the feature I'm working on for a future release. I can check that out into the working directory, develop locally, merge newly-pulled SVN stuff from my git master branch, etc. If I have any hotfix changes that need to be made on the current version, I can check back out to git master, make those changes, commit them on git, commit them on SVN, and everything stays clean.

Title: Local git repo creation


问:
How to define custom combine predicate?
I defined my own predicate:

```<code>public interface StringPredicate extends Predicate<String> {
</code>```

It works, but if I write:

```<code>myPred.and( strEl -> strEl != null);
</code>```

the result is a Predicate<String> not a StringPredicate. How can I define a combine operation as well?

答:
You can define your own and method in your StringPredicate interface:

```<code>public interface StringPredicate extends Predicate<String> {
    default StringPredicate and(StringPredicate other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
}
</code>```

Now, the following will work:

```<code>StringPredicate myPred = s -> s.length() > 0;
StringPredicate combined = myPred.and(strEl -> strEl.length () < 5);
</code>```

Title: How to define custom combine predicate?

Body:
I defined my own predicate:

public interface StringPredicate extends Predicate<String> {

It works, but if I write:

myPred.and( strEl -> strEl != null);

the result is a Predicate<String> not a StringPredicate. How can I define a combine operation as well?

Body:
You can define your own and method in your StringPredicate interface:

public interface StringPredicate extends Predicate<String> {
    default StringPredicate and(StringPredicate other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
}

Now, the following will work:

StringPredicate myPred = s -> s.length() > 0;
StringPredicate combined = myPred.and(strEl -> strEl.length () < 5);


问:
Process supervisor taking care of their I/O
I am trying to write a programs that is processing data. And for example I want to run 5 of them and they can run in parallel.I have already written shell like program with lexer and parser but I don't know how to manage these processes. Can anyone give me any tips because I'm stuck and have no idea what to do next?</p>

答:
I think you're looking for fork(), wait() and pipe()

You can find tons of examples if you google with those keywords. Hope it helps.


问:
Qt Quick QML Flickable disable flicking and enable only scrolling
I have two Flickable inside a column and I want to scroll vertically first Flickable when user scrolls second Flickable.

```<code>Rectangle {
id: root
anchors.fill: parent

Flickable {
  id: first
  anchors.left: parent.left
  width: parent.width/2
  height: parent.height

  // Rest of the Contents
  // I have also some TextFields and ComboBoxs here
}

Flickable {
  id: second
  anchors.left: first.right
  width: parent.width/2
  height: parent.height

  onFlickEnded: {
    first.contentY = second.contentY;
  }

  // Rest of the Contents
  // I have also some TextFields and ComboBoxs here
}

}
</code>```

I am able to do this by using onFlickEnded event, is this correct way?
How can I disable flicking effect when user clicks and drag and just have scrolling effect using mouse wheel?

Should I use ScrollView instead, but I am not able to scroll it as I did with Flickable.

答:
setting "interactive" to false should disable flicking.

Instead of "onFlickEnded" you can use "onContentYChanged".

Body:
I have two Flickable inside a column and I want to scroll vertically first Flickable when user scrolls second Flickable.

Rectangle {
id: root
anchors.fill: parent

Flickable {
  id: first
  anchors.left: parent.left
  width: parent.width/2
  height: parent.height

  // Rest of the Contents
  // I have also some TextFields and ComboBoxs here
}

Flickable {
  id: second
  anchors.left: first.right
  width: parent.width/2
  height: parent.height

  onFlickEnded: {
    first.contentY = second.contentY;
  }

  // Rest of the Contents
  // I have also some TextFields and ComboBoxs here
}

}

I am able to do this by using onFlickEnded event, is this correct way?
How can I disable flicking effect when user clicks and drag and just have scrolling effect using mouse wheel?

Should I use ScrollView instead, but I am not able to scroll it as I did with Flickable.


问:
How-to parse XML key:value pair
I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

```<code>$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';
</code>```

I was hoping that the following would work, but it appears not.

```<code>$test = new SimpleXMLElement($xml);
echo "Mask: " . $xml->response->mask; // Mask: 9999
</code>```

答: if my memory server me right simplexml is extension. Are you sure you installed it? BTW, simplexml was added in PHP 5.0, so make sure you are not running lower version

Title: How-to parse XML key:value pair

Body:
I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';

I was hoping that the following would work, but it appears not.

$test = new SimpleXMLElement($xml);
echo "Mask: " . $xml->response->mask; // Mask: 9999


问:
How to enable persistence in helm prometheus-operator
I am using the prometheus-operator helm chart. I want the data in prometheus server to persist. But open restart of the prometheus StatefulSet, the data disappears. When inspecting the yaml definitions of the associated StatefulSet and Pod objects, there is no PersistVolumeClaim.

I tried the following change to values.yaml, per the docs in https://github.com/helm/charts/tree/master/stable/prometheus:

```<code>prometheus:
  server:
    persistentVolume:
      enabled: true
</code>```

but this has no effect on the end result (even after reinstalling the chart and reinstalling the StatefulSet).

I expect the StatefulSet backing the prometheus server to have persistent volume claims, so that data is persisted upon restart.

答:
With latest Helm Chart this worked for me:
(I'm using AWS)</p>

```<code>prometheus:
  prometheusSpec:
    storageSpec:
      volumeClaimTemplate:
        spec:
          storageClassName: gp2
          accessModes: ["ReadWriteOnce"]
          resources:
            requests:
              storage: 10Gi
</code>```

Body:
I am using the prometheus-operator helm chart. I want the data in prometheus server to persist. But open restart of the prometheus StatefulSet, the data disappears. When inspecting the yaml definitions of the associated StatefulSet and Pod objects, there is no PersistVolumeClaim.

I tried the following change to values.yaml, per the docs in https://github.com/helm/charts/tree/master/stable/prometheus:

prometheus:
  server:
    persistentVolume:
      enabled: true

but this has no effect on the end result (even after reinstalling the chart and reinstalling the StatefulSet).

I expect the StatefulSet backing the prometheus server to have persistent volume claims, so that data is persisted upon restart.

Body:
With latest Helm Chart this worked for me:
(I'm using AWS)

prometheus:
  prometheusSpec:
    storageSpec:
      volumeClaimTemplate:
        spec:
          storageClassName: gp2
          accessModes: ["ReadWriteOnce"]
          resources:
            requests:
              storage: 10Gi


问:
How to space between rows?
I have an expanded widget for my ClipRRect, which I think I need, but I also need to spacebetween my row, but I can't manage it. If I wrap it in an expanded widget it changes the size of my image in ClipRRect, which I don't want to do. This is my code:</p>

```<code> @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(6),
      child: GestureDetector(
        onTap: function,

        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[

              Expanded(
                flex: 1,
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Stack(
                      children: <Widget>[
                        assetImage,
                      ],
                    ),
                ),
              ),

              Row(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text('$myText -', style: myTextStyle),
                      SizedBox(width: 5.0,),
                      Text('$locationText', style: myTextStyle),
                    ],
                  ),

                    Card(
                      elevation: 1,
                      color: Colors.white,
                      shape: cardBorder,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text('$myText - $endmyText mins', style: myTextStyle,),
                      ),
                    ),
                ],
              ),

            ],
          ),
        ),
      ),
    );

  }
</code>```

答:
Assuming your question says you want to divide widgets with equal spaces, for it replaces Row with Wrap widget

```<code>       Wrap(
            direction: Axis.horizontal,
            spacing: 30, // add space in between widget
            children: <Widget>[
              Wrap(
                spacing: 30, // add space in between widget
                direction: Axis.horizontal,
</code>```

Title: How to space between rows?

Body:
I have an expanded widget for my ClipRRect, which I think I need, but I also need to spacebetween my row, but I can't manage it. If I wrap it in an expanded widget it changes the size of my image in ClipRRect, which I don't want to do. This is my code:

 @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(6),
      child: GestureDetector(
        onTap: function,

        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[

              Expanded(
                flex: 1,
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Stack(
                      children: <Widget>[
                        assetImage,
                      ],
                    ),
                ),
              ),

              Row(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text('$myText -', style: myTextStyle),
                      SizedBox(width: 5.0,),
                      Text('$locationText', style: myTextStyle),
                    ],
                  ),

                    Card(
                      elevation: 1,
                      color: Colors.white,
                      shape: cardBorder,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text('$myText - $endmyText mins', style: myTextStyle,),
                      ),
                    ),
                ],
              ),

            ],
          ),
        ),
      ),
    );

  }

Body:
Assuming your question says you want to divide widgets with equal spaces, for it replaces Row with Wrap widget

       Wrap(
            direction: Axis.horizontal,
            spacing: 30, // add space in between widget
            children: <Widget>[
              Wrap(
                spacing: 30, // add space in between widget
                direction: Axis.horizontal,


问:
Adding NaN's in python variable?
If I have a variable with missings, how do I assign them as NaNs in python?

I've tried the following but it's returning an empty dataframe:

```<code>data_2017_18.income=np.nan
</code>```

Much appreciated.

答: You can use float("nan") to get a "not a number" (NaN) value.

Title: Adding NaN's in python variable?

Body:
If I have a variable with missings, how do I assign them as NaNs in python?

I've tried the following but it's returning an empty dataframe:

data_2017_18.income=np.nan

Much appreciated.