问:
Inserting Data Into Mongodb using C#
```<code>using MongoDB.Bson;
using MongoDB.Driver;

protected static IMongoClient client;
protected static IMongoDatabase db;

        public async void Insert()
        {
        client = new MongoClient();
        db = client.GetDatabase("Database");

        string json = "[";

        foreach (CsvObjects.Connections e in connectionsList)
        {
            json += "{";
            json += "\"DateTime\":\"" + e.DateTime + "\",";
            json += "\"Value\":\"" + e.Value + "\",";
            json += "},";
        }

        json += "]";

        MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);

        var collection = db.GetCollection<BsonDocument>("data");
        await collection.InsertOneAsync(document);
</code>```

I made an arraylist with data I want to insert into the mongodb, I tried to make a json and insert it with the InsertOneAsync method but I got the deserialization error. There might be an easier way to do this but I have no idea how.

I tried some other stackoverflow threads about this topic but without avail.

"Cannot deserialize a 'BsonDocument' from BsonType 'Array'"

答:
await collection.InsertOneAsync(item.ToBsonDocument());

"await" is the keyword if not where it is initialize

Title: Inserting Data Into Mongodb using C#

Body:
using MongoDB.Bson;
using MongoDB.Driver;

protected static IMongoClient client;
protected static IMongoDatabase db;

        public async void Insert()
        {
        client = new MongoClient();
        db = client.GetDatabase("Database");

        string json = "[";

        foreach (CsvObjects.Connections e in connectionsList)
        {
            json += "{";
            json += "\"DateTime\":\"" + e.DateTime + "\",";
            json += "\"Value\":\"" + e.Value + "\",";
            json += "},";
        }

        json += "]";

        MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);

        var collection = db.GetCollection<BsonDocument>("data");
        await collection.InsertOneAsync(document);

I made an arraylist with data I want to insert into the mongodb, I tried to make a json and insert it with the InsertOneAsync method but I got the deserialization error. There might be an easier way to do this but I have no idea how.

I tried some other stackoverflow threads about this topic but without avail.

"Cannot deserialize a 'BsonDocument' from BsonType 'Array'"


来源: stackexchange

问:
How to debug Android/GDB/Qt problems?
I've been developing an Android app with Qt for months now.  I used to be able to debug with no problems in Qt Creator, but now the debugger fails to start.  The deploy process works -- the app can be started from the device GUI.

Sample projects build and can be debugged normally.

I'm using NDK 10e because anything later confuses Creator, which tells me that the Qt people aren't using a recent build.

I have the latest version of the SDK, developing on OS X.

The Debugger Log window ends with this:

```<code>~"Loaded symbols for /Users/tjdaniel/projects/qt/5.6.0/plugins/sensors/libqtsensors_android.so\n"
~"Reading symbols from /Users/tjdaniel/projects/build/localization/android/Debug/liblocalization.so..."
sReading /Users/tjdaniel/projects/build/localization/android/Debug/liblocalization.so......

dHANDLE GDB ERROR: The gdb process was ended forcefully
dGDB PROCESS FINISHED, status 1, exit code 11
dNOTE: ENGINE ILL ******
</code>```

And here is the output of adb logcat:

```<code>W/linker  (12790): libqtforandroid.so: unused DT entry: type 0x1d arg 0x8d9a
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
I/Qt      (12790): qt start
W/linker  (12790): libqandroidbearer.so: unused DT entry: type 0x1d arg 0x174f
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
W/linker  (12790): libqtmedia_android.so: unused DT entry: type 0x1d arg 0x51da
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
W/linker  (12790): libqtsensors_android.so: unused DT entry: type 0x1d arg 0x1076
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
I/Qt      (12790): Sensors start
W/linker  (12790): liblocalization.so: unused DT entry: type 0x1d arg 0x29f5f4
D/        (12790): (null):0 ((null)): QML debugging is enabled. Only use this in a safe environment.
I/Qt JAVA (12790): DEBUGGER: extra parameters: Bundle[{debug_ping=true, gdbserver_socket=/data/data/org.qtproject.example.localization/debug-socket, qml_debug=true, gdbserver_command=/data/data/org.qtproject.example.localization/lib/libgdbserver.so --multi +/data/data/org.qtproject.example.localization/debug-socket, qmljsdebugger=port:56956,block,services:DebugMessages,QmlDebugger,V8Debugger,QmlInspector, ping_socket=org.qtproject.example.localization.ping_pong_socket}]
I/Qt JAVA (12790): DEBUGGER: removing gdb socket /data/data/org.qtproject.example.localization/debug-socket
I/Qt JAVA (12790): DEBUGGER: starting /data/data/org.qtproject.example.localization/lib/libgdbserver.so --multi +/data/data/org.qtproject.example.localization/debug-socket
I/Qt JAVA (12790): DEBUGGER: gdbserver started
I/Qt JAVA (12790): DEBUGGER: waiting for socket at /data/data/org.qtproject.example.localization/debug-socket, attempt 0
I/Qt JAVA (12790): DEBUGGER: waiting for socket at /data/data/org.qtproject.example.localization/debug-socket, attempt 1
I/Qt JAVA (12790): DEBUGGER: socket ok
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Debug socket accepted
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/ConfigService( 1968): onDestroy
W/ActivityManager(  845): Launch timeout has expired, giving up wake lock!
</code>```

Any advice on how to debug this??  Not being able to use the debugger is killing me.  I've wiped and reinstalled everything related to Qt.. no luck.

答: I had the same issue, and as of today, the only way I found was to set the Target android SDK to API 23 (Android 6) or less in your AndroidManifest.xml</p>

ContentLicense: CC BY-SA 3.0

Title: How to debug Android/GDB/Qt problems?

Body:
I've been developing an Android app with Qt for months now.  I used to be able to debug with no problems in Qt Creator, but now the debugger fails to start.  The deploy process works -- the app can be started from the device GUI.

Sample projects build and can be debugged normally.

I'm using NDK 10e because anything later confuses Creator, which tells me that the Qt people aren't using a recent build.

I have the latest version of the SDK, developing on OS X.

The Debugger Log window ends with this:

~"Loaded symbols for /Users/tjdaniel/projects/qt/5.6.0/plugins/sensors/libqtsensors_android.so\n"
~"Reading symbols from /Users/tjdaniel/projects/build/localization/android/Debug/liblocalization.so..."
sReading /Users/tjdaniel/projects/build/localization/android/Debug/liblocalization.so......

dHANDLE GDB ERROR: The gdb process was ended forcefully
dGDB PROCESS FINISHED, status 1, exit code 11
dNOTE: ENGINE ILL ******

And here is the output of adb logcat:

W/linker  (12790): libqtforandroid.so: unused DT entry: type 0x1d arg 0x8d9a
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
I/Qt      (12790): qt start
W/linker  (12790): libqandroidbearer.so: unused DT entry: type 0x1d arg 0x174f
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
W/linker  (12790): libqtmedia_android.so: unused DT entry: type 0x1d arg 0x51da
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
W/linker  (12790): libqtsensors_android.so: unused DT entry: type 0x1d arg 0x1076
W/linker  (12790): Unsupported flags DT_FLAGS_1=0x81
I/Qt      (12790): Sensors start
W/linker  (12790): liblocalization.so: unused DT entry: type 0x1d arg 0x29f5f4
D/        (12790): (null):0 ((null)): QML debugging is enabled. Only use this in a safe environment.
I/Qt JAVA (12790): DEBUGGER: extra parameters: Bundle[{debug_ping=true, gdbserver_socket=/data/data/org.qtproject.example.localization/debug-socket, qml_debug=true, gdbserver_command=/data/data/org.qtproject.example.localization/lib/libgdbserver.so --multi +/data/data/org.qtproject.example.localization/debug-socket, qmljsdebugger=port:56956,block,services:DebugMessages,QmlDebugger,V8Debugger,QmlInspector, ping_socket=org.qtproject.example.localization.ping_pong_socket}]
I/Qt JAVA (12790): DEBUGGER: removing gdb socket /data/data/org.qtproject.example.localization/debug-socket
I/Qt JAVA (12790): DEBUGGER: starting /data/data/org.qtproject.example.localization/lib/libgdbserver.so --multi +/data/data/org.qtproject.example.localization/debug-socket
I/Qt JAVA (12790): DEBUGGER: gdbserver started
I/Qt JAVA (12790): DEBUGGER: waiting for socket at /data/data/org.qtproject.example.localization/debug-socket, attempt 0
I/Qt JAVA (12790): DEBUGGER: waiting for socket at /data/data/org.qtproject.example.localization/debug-socket, attempt 1
I/Qt JAVA (12790): DEBUGGER: socket ok
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Debug socket accepted
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/Qt JAVA (12790): DEBUGGER: Waiting for debug socket connect
I/Qt JAVA (12790): DEBUGGER: go to sleep
I/ConfigService( 1968): onDestroy
W/ActivityManager(  845): Launch timeout has expired, giving up wake lock!

Any advice on how to debug this??  Not being able to use the debugger is killing me.  I've wiped and reinstalled everything related to Qt.. no luck.


问:
Using nested objects in redux initial state and reducers
I have dashboard that have a sections which is separated by react-router.

Sections are:

Categories

Exams

Reports

Lets take a look at Exam section. we have this state as the initial state.

```<code>{
        ID: null,
        RandomizeQuestions: false,
        RandomizeAnswers: false,
        Pages: [
            {
                ID: 1,
                Title: 'Page one',
                Blocks: [
                    {
                        ID: 1,
                        Title: 'Block One',
                        Questions: [
                            {
                                ID: 1,
                                Title: "Quesiton title is here",
                                Answers: [
                                    {
                                        ID: 1,
                                        Title: "Answer 1"
                                    },
                                    {
                                        ID: 2,
                                        Title: "Answer 2"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
</code>```

I know that the state should be flatten and normalized when I use redux. but that is my exact problem. if i try to normalize my state it should be like this :

```<code>{
Exam: {
    ID: null,
    RandomizeQuestions: false,
    RandomizeAnswers: false
},
ExamPages: [
    {
        ExamId: 1,
        ID: 1,
        Title: 'Page One'
    }
],
ExamBlocks: [
    {
        ID: 1,
        Title: 'The New Block',
        Questions: []
    }
],
ExamQuestions: [],
ExamAnswers: []
}
</code>```

lets assume that its ok and I wont have problem with it. but when happen to the other sections ?

Categories have its own states which is big too and report too. ( there are other section that I didn't mention )

and then my combineReducer would be looks like this :

```<code>import {combineReducers} from 'redux'
import Exam from './redc.exams.jsx'
import ExamBlocks from './redc.blocks.jsx'

const rootReducer = combineReducers({
    Exam,
    ExamBlocks
})

export default rootReducer
</code>```

and of course I should have a reducer for every array in that object.

so my main question is how can I at lest have this structure:

```<code>const initialState = {
    Exams: {
        Blocks: [],
        Questions: [],
        Answers: []
    },
    Categories: {
        Menus: [],
        Users: []
    },
    Report: {
        MainReports: [],
        SideReports: []
    }
}
</code>```

remember that I want to have separate reducers for each of them.
a reducer for Blocks , reducer for Questions and so on...

UPDATE #1

I tried @Tom Fenech said in the answers but cannot combine reducers before final combineReducers.
right now my root reducers is looks like this:

```<code>import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const rootReducer = combineReducers({
        Exams,
        Categories,
        Blocks,
})

export default rootReducer
</code>```

I tried with what he says and here is my code after the changes:

```<code>import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const examRedc = combineReducers(Exams,Blocks )
const catsRedc = combineReducers(Categories)

const rootReducer = combineReducers(examRedc, catsRedc)

export default rootReducer
</code>```

i get this error :

```<code>Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.
</code>```

and when i log the state in one of the components like this

```<code>var mapDispatchToProps = function (dispatch) {
    return {
        AddBlock: function () {
            dispatch(addBlock());
        }
    }
};

const mapStateToProps = function (state) {
    console.log(state); //////HERE
    return {Blocks: state.Blocks};
}

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

I get this state which is not what I want finally.

答:
I don't think there's any need to have Blocks, Questions and Answers inside of Exams. I would suggest something like this at the top level:

```<code>{
    Exams: {
        [ID]: {
            ID: string,
            RandomizeQuestions: boolean,
            RandomizeAnswers: boolean,
            Blocks: string[] // array of block IDs
        }
    }
    Blocks: {
        [ID]: {
            ID: string,
            Title: string,
            Questions: string[] // array of question IDs
        }
    },
    Questions: // etc.
}
</code>```

Now, instead of storing the nested objects, we just store their ID to keep track of ownership.

This state would be created with:

```<code>state = combineReducers({
    examsReducer,
    blocksReducer,
    // ...more reducers
})
</code>```

If you want to split the overall state into sections, you could use something like this:

```<code>const examStuff = combineReducers({
    examsReducer,
    blocksReducer,
    // ...
});

const categoryStuff = combineReducers({
    categoriesReducer,
    menusReducer,
    // ...
});

const state = combineReducers({
    examStuff,
    categoryStuff
});
</code>```

Then state would be:

```<code>{
    examStuff: {} // the object defined at the top of question,
    categoryStuff: {},
    otherStuff: {}
}
</code>```

Body:
I have dashboard that have a sections which is separated by react-router.

Sections are:

Categories

Exams

Reports

Lets take a look at Exam section. we have this state as the initial state.

{
        ID: null,
        RandomizeQuestions: false,
        RandomizeAnswers: false,
        Pages: [
            {
                ID: 1,
                Title: 'Page one',
                Blocks: [
                    {
                        ID: 1,
                        Title: 'Block One',
                        Questions: [
                            {
                                ID: 1,
                                Title: "Quesiton title is here",
                                Answers: [
                                    {
                                        ID: 1,
                                        Title: "Answer 1"
                                    },
                                    {
                                        ID: 2,
                                        Title: "Answer 2"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }

I know that the state should be flatten and normalized when I use redux. but that is my exact problem. if i try to normalize my state it should be like this :

{
Exam: {
    ID: null,
    RandomizeQuestions: false,
    RandomizeAnswers: false
},
ExamPages: [
    {
        ExamId: 1,
        ID: 1,
        Title: 'Page One'
    }
],
ExamBlocks: [
    {
        ID: 1,
        Title: 'The New Block',
        Questions: []
    }
],
ExamQuestions: [],
ExamAnswers: []
}

lets assume that its ok and I wont have problem with it. but when happen to the other sections ?

Categories have its own states which is big too and report too. ( there are other section that I didn't mention )

and then my combineReducer would be looks like this :

import {combineReducers} from 'redux'
import Exam from './redc.exams.jsx'
import ExamBlocks from './redc.blocks.jsx'

const rootReducer = combineReducers({
    Exam,
    ExamBlocks
})

export default rootReducer

and of course I should have a reducer for every array in that object.

so my main question is how can I at lest have this structure:

const initialState = {
    Exams: {
        Blocks: [],
        Questions: [],
        Answers: []
    },
    Categories: {
        Menus: [],
        Users: []
    },
    Report: {
        MainReports: [],
        SideReports: []
    }
}

remember that I want to have separate reducers for each of them.
a reducer for Blocks , reducer for Questions and so on...

UPDATE #1

I tried @Tom Fenech said in the answers but cannot combine reducers before final combineReducers.
right now my root reducers is looks like this:

import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const rootReducer = combineReducers({
        Exams,
        Categories,
        Blocks,
})

export default rootReducer

I tried with what he says and here is my code after the changes:

import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const examRedc = combineReducers(Exams,Blocks )
const catsRedc = combineReducers(Categories)

const rootReducer = combineReducers(examRedc, catsRedc)

export default rootReducer

i get this error :

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

and when i log the state in one of the components like this

var mapDispatchToProps = function (dispatch) {
    return {
        AddBlock: function () {
            dispatch(addBlock());
        }
    }
};

const mapStateToProps = function (state) {
    console.log(state); //////HERE
    return {Blocks: state.Blocks};
}

export default connect(mapStateToProps, mapDispatchToProps)(Blocks)

I get this state which is not what I want finally.

Body:
I don't think there's any need to have Blocks, Questions and Answers inside of Exams. I would suggest something like this at the top level:

{
    Exams: {
        [ID]: {
            ID: string,
            RandomizeQuestions: boolean,
            RandomizeAnswers: boolean,
            Blocks: string[] // array of block IDs
        }
    }
    Blocks: {
        [ID]: {
            ID: string,
            Title: string,
            Questions: string[] // array of question IDs
        }
    },
    Questions: // etc.
}

Now, instead of storing the nested objects, we just store their ID to keep track of ownership.

This state would be created with:

state = combineReducers({
    examsReducer,
    blocksReducer,
    // ...more reducers
})

If you want to split the overall state into sections, you could use something like this:

const examStuff = combineReducers({
    examsReducer,
    blocksReducer,
    // ...
});

const categoryStuff = combineReducers({
    categoriesReducer,
    menusReducer,
    // ...
});

const state = combineReducers({
    examStuff,
    categoryStuff
});

Then state would be:

{
    examStuff: {} // the object defined at the top of question,
    categoryStuff: {},
    otherStuff: {}
}


问:
Catch Right-Click AS3
Is it possible to catch a right-click inside of flash (AS3)?

No JQuery/JavaScript.

I need to pause gameplay when a right-click is caught, so I don't so much want to disable the context-menu as I do just want to tell that a right-click has happened.  Is there an EventListener I can add?  Any other ideas?

UPDATE:

I need the event to be triggered as they are actually right clicking, not just after the context-menu has disappeared.

答:
Just as weltraumpirat reported, the only way to capture the Right Click event is if you are building your application to be deployed as an AIR application if you want to keep it all native to the Flash Platform Architecture; otherwise you will need to use some other language in conjunction with Flash to capture the event (i.e. JavaScript).

FYI, here is the API reference for the MouseEvent Class that contains information about the RightClick event: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/MouseEvent.html

ContentLicense: CC BY-SA 2.5

Title: Catch Right-Click AS3


问:
Pointer to variable inside a struct
I have a struct like this:

```<code>typedef struct{
    char *lexema;
    int comp_lexico;
    union{
        double v;
        double (*fnctptr)();
    } valor;
}tipoelem;

struct celda {
    tipoelem info;
    struct celda *izq, *der;
};

typedef struct celda * abb;
</code>```

Then I define a global variable abb, which has a global scope. If I get somehow the memory direction of the field info of celda, would I be able to modify it safely or It is better to define the field as a tipoelem pointer such as (tipoelem *info)?

The thing is, is it safe to edit the tipoelem info field with a tipoelem *pointerToInfo from other part of the prrogram or it is better to declare it as a pointer tipoelem *info in the struct celda?

Edited with more information:
The way I want to modify tipoelem info is the next one, and I do not know if it is safe.

```<code>abb a;
int main(){
    tipoelem *ptr = a->info;
    ptr->comp_lexico = 2;
}
</code>```

答:
To access the int inside info with a variable of type abb I would use this main:

```<code>#include <stdio.h>
void main(){
    abb variable;
    printf("comp_lexico es %d",variable->info.comp_lexico);
}
</code>```

Title: Pointer to variable inside a struct

Body:
I have a struct like this:

typedef struct{
    char *lexema;
    int comp_lexico;
    union{
        double v;
        double (*fnctptr)();
    } valor;
}tipoelem;

struct celda {
    tipoelem info;
    struct celda *izq, *der;
};

typedef struct celda * abb;

Then I define a global variable abb, which has a global scope. If I get somehow the memory direction of the field info of celda, would I be able to modify it safely or It is better to define the field as a tipoelem pointer such as (tipoelem *info)?

The thing is, is it safe to edit the tipoelem info field with a tipoelem *pointerToInfo from other part of the prrogram or it is better to declare it as a pointer tipoelem *info in the struct celda?

Edited with more information:
The way I want to modify tipoelem info is the next one, and I do not know if it is safe.

abb a;
int main(){
    tipoelem *ptr = a->info;
    ptr->comp_lexico = 2;
}

Body:
To access the int inside info with a variable of type abb I would use this main:

#include <stdio.h>
void main(){
    abb variable;
    printf("comp_lexico es %d",variable->info.comp_lexico);
}


问:
CollectionViewCell margin?
I have a UICollectionView and there are some dequeued custom cells in it. As you can see from the screenshot, there's this odd margin and I cannot figure out where this come from. The brown/orange color is the UICollectionView and the grey color is the UICollectionViewCell.

I'm using a xib file for that cell because I'd need many custom cells.

And the code that generates the UICollectionView has nothing that would cause this margin.

```<code>extension DashVC: UICollectionViewDelegate, UICollectionViewDataSource
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostImageCell", for: indexPath) as! PostImageCell
        let post = posts[indexPath.row]
        let user = users[indexPath.row]
        cell.post = post
        cell.user = user
        cell.delegate = self
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return posts.count
    }

    func setCollectionViewDelegatesAndRowHeight()
    {
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}
</code>```

UPDATE:

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,   sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let width = Int(UIScreen.main.bounds.width)
    let height = 407
    let size = CGSize(width: width, height: height)
    return size
}
</code>```

答:
Your UICollectionView width is 375 and UICollectionViewCell width is 320. You are seeing the difference. To make your cells as wide as the screen you can make your controller conform to the UICollectionViewDelegateFlowLayout, and implement the following method:

```<code>- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    cellHeight = 407.0
    CGSize size = CGSizeMake(screenWidth, cellHeight);

    return size;
}
</code>```

Title: CollectionViewCell margin?

Body:
I have a UICollectionView and there are some dequeued custom cells in it. As you can see from the screenshot, there's this odd margin and I cannot figure out where this come from. The brown/orange color is the UICollectionView and the grey color is the UICollectionViewCell.

I'm using a xib file for that cell because I'd need many custom cells.

And the code that generates the UICollectionView has nothing that would cause this margin.

extension DashVC: UICollectionViewDelegate, UICollectionViewDataSource
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostImageCell", for: indexPath) as! PostImageCell
        let post = posts[indexPath.row]
        let user = users[indexPath.row]
        cell.post = post
        cell.user = user
        cell.delegate = self
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return posts.count
    }

    func setCollectionViewDelegatesAndRowHeight()
    {
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

UPDATE:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,   sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let width = Int(UIScreen.main.bounds.width)
    let height = 407
    let size = CGSize(width: width, height: height)
    return size
}

Body:
Your UICollectionView width is 375 and UICollectionViewCell width is 320. You are seeing the difference. To make your cells as wide as the screen you can make your controller conform to the UICollectionViewDelegateFlowLayout, and implement the following method:

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    cellHeight = 407.0
    CGSize size = CGSizeMake(screenWidth, cellHeight);

    return size;
}


问:
R - Top x Important Variable Each Individual Sample Data in Classification
I'm building a churn model using C5 algorithm in R. After finishing the model and successfully predicting the data, how do I know the top 3 important predictors for each of customer that will churn? So I know the reason why the model classifies -for example- cust A,B,D,F as positive and the others as negative. Is it possible?

Thanks.

答:
You can plot the trees within the model. If you use a single C5.0 tree, this gives you an easy way to provide the exact reasoning of the tree.

```<code>library(C50)
set.seed(1401)
C5tree <- C5.0(x = iris[, 1:4], y = iris$Species, trials = 1) # A single C50 tree
C5imp(C5tree)
plot(C5tree, trial = 0)
</code>```

If you use boosting (i.e. trials > 1 when you train the trees), then this approach is likely too complicated due to the number of trees.

```<code>C5boosted <- C5.0(x = iris[, 1:4], y = iris$Species, trials = 3) # Boost three trees
C5imp(C5boosted)
# Plot each of the trees
for(i in 0:2){ # trials starts counting at 0, see ?plot.C5.0
plot(C5boosted, trial = i)
}
</code>```

Instead, you can rely on the variable importance for a general report of important variables or use partial dependence plots that show the (non-linear) effect of one variable relative to all other variables. I suggest having a look at package pdp on CRAN.

Body:
You can plot the trees within the model. If you use a single C5.0 tree, this gives you an easy way to provide the exact reasoning of the tree.

library(C50)
set.seed(1401)
C5tree <- C5.0(x = iris[, 1:4], y = iris$Species, trials = 1) # A single C50 tree
C5imp(C5tree)
plot(C5tree, trial = 0)

If you use boosting (i.e. trials > 1 when you train the trees), then this approach is likely too complicated due to the number of trees.

C5boosted <- C5.0(x = iris[, 1:4], y = iris$Species, trials = 3) # Boost three trees
C5imp(C5boosted)
# Plot each of the trees
for(i in 0:2){ # trials starts counting at 0, see ?plot.C5.0
plot(C5boosted, trial = i)
}

Instead, you can rely on the variable importance for a general report of important variables or use partial dependence plots that show the (non-linear) effect of one variable relative to all other variables. I suggest having a look at package pdp on CRAN.


问:
Cannot find contract attachment for Cash when using NodeDriver
I just started using Corda. I know that in unit testing, I'm supposed to add the line

```<code>setCordappPackages("net.corda.finance")
</code>```

But when I debug using NodeDriver, I just receive the message.

```<code>net.corda.core.transactions.MissingContractAttachments: Cannot find contract attachments for [net.corda.finance.contracts.asset.Cash]
</code>```

What's missing?

答:
You set the packages the driver scans as follows:</p>

```<code>driver(
    startNodesInProcess = true,
    extraCordappPackagesToScan = listOf("net.corda.examples.attachments"),
    isDebug = true)
{
    ...
}
</code>```

Body:
I just started using Corda. I know that in unit testing, I'm supposed to add the line

setCordappPackages("net.corda.finance")

But when I debug using NodeDriver, I just receive the message.

net.corda.core.transactions.MissingContractAttachments: Cannot find contract attachments for [net.corda.finance.contracts.asset.Cash]

What's missing?

Body:
You set the packages the driver scans as follows:

driver(
    startNodesInProcess = true,
    extraCordappPackagesToScan = listOf("net.corda.examples.attachments"),
    isDebug = true)
{
    ...
}

ContentLicense: CC BY-SA 4.0


问:
HHH000179 warning in hibernate logging - 5.2.10
In cotext of "https://forum.hibernate.org/viewtopic.php?p=2404391" - I have added "org.hibernate.engine.internal.StatefulPersistenceContext" to ERROR in log4j.properties as well tried also "org.hibernate.engine.internal" to ERROR.

However HHH000179  warning is still not getting suppressed.My hibernate version is 5.2.10. I tried to check the code of StatefulPersistenceContext from this version and there is following code:

if ( !alreadyNarrow ) {
            LOG.narrowingProxy( concreteProxyClass );

Unless here the code adds check for checking if logging level WARN is enabled, how this can be suppressed even mentioning ERROR level for this class?

For tracing level there is code in the same file as:

```<code>final boolean tracing = LOG.isTraceEnabled();
    if ( tracing ) {
        LOG.trace( "Serializing persistent-context" );
    }
</code>```

and I think similar logic should have been there for WARN for suppressing 'HHH000179'

I was cusrious if this has already been addressed or any other ways to suppress this warning?

答:
Please read info provided on below think, which explain the scenario for which  HHH000179-narrowing-proxy-to-class- warning get logged.

https://marcin-chwedczuk.github.io/HHH000179-narrowing-proxy-to-class-this-operation-breaks-equality

Body:
In cotext of "https://forum.hibernate.org/viewtopic.php?p=2404391" - I have added "org.hibernate.engine.internal.StatefulPersistenceContext" to ERROR in log4j.properties as well tried also "org.hibernate.engine.internal" to ERROR.

However HHH000179  warning is still not getting suppressed.My hibernate version is 5.2.10. I tried to check the code of StatefulPersistenceContext from this version and there is following code:

if ( !alreadyNarrow ) {
            LOG.narrowingProxy( concreteProxyClass );

Unless here the code adds check for checking if logging level WARN is enabled, how this can be suppressed even mentioning ERROR level for this class?

For tracing level there is code in the same file as:

final boolean tracing = LOG.isTraceEnabled();
    if ( tracing ) {
        LOG.trace( "Serializing persistent-context" );
    }

and I think similar logic should have been there for WARN for suppressing 'HHH000179'

I was cusrious if this has already been addressed or any other ways to suppress this warning?


问:
Golang: cannot install package zvelo/ttlru
I would like to use zvelo/ttlru and have successfully go get this package from github.

Problem:

The following error occurs, when I try to go run my go program, that contains the import "github.com/zvelo/ttlru":

go_server.go:8:2: code in directory
  /home/.../work_go/src/github.com/zvelo/ttlru expects import
  "zvelo.io/ttlru"

What is wrong here? I don't see any zvelo.io/ttlru imports anywhere.

答:
As stated in the README.md and the error message, import from zvelo.io/ttlru and not github.com/zvelo/ttlru.

Make sure to use go get zvelo.io/ttlru

You will then find the source of the package in /home/.../work_go/src/zvelo.io/ttlru/.


问:
Guaranteeing mutex safety with async signals
First, I am aware that the mutexes are not considered async-safe normally. This question concerns the use of sigprocmask to make mutexes safe in a multithreaded program with async signals and signal handlers.

I have some code conceptually like the following:

```<code>struct { int a, b; } gvars;

void sigfoo_handler(int signo, siginfo_t *info, void *context) {
    if(gvars.a == 42 || gvars.b == 13) {
        /* run a chained signal handler */
    }
}

/* called from normal code */
void update_gvars(int a, int b) {
    gvars.a = a;
    gvars.b = b;
}
</code>```

gvars is a global variable which is too large to fit in a single sig_atomic_t. It is updated by normal code and read from the signal handler. The controlled code is a chained signal handler, and so it must run in signal handler context (it may use info or context). Consequently, all accesses to gvars have to be controlled via some sort of synchronization mechanism. Complicating matters, the program is multithreaded, and any thread may receive a SIGFOO.

Question: By combining sigprocmask (or pthread_sigmask) and pthread_mutex_t, is it possible to guarantee synchronization, using code like the following?

```<code>struct { int a, b; } gvars;
pthread_mutex_t gvars_mutex;

void sigfoo_handler(int signo, siginfo_t *info, void *context) {
    /* Assume SIGFOO's handler does not have NODEFER set, i.e. it is automatically blocked upon entry */
    pthread_mutex_lock(&gvars_mutex);
    int cond = gvars.a == 42 || gvars.b == 13;
    pthread_mutex_unlock(&gvars_mutex);

    if(cond) {
        /* run a chained signal handler */
    }
}

/* called from normal code */
void update_gvars(int a, int b) {
    sigset_t set, oset;
    sigemptyset(&set);
    sigaddset(&set, SIGFOO);
    pthread_sigmask(SIG_BLOCK, &set, &oset);
    pthread_mutex_lock(&gvars_mutex);
    gvars.a = a;
    gvars.b = b;
    pthread_mutex_unlock(&gvars_mutex);
    pthread_sigmask(SIG_SETMASK, &oset, NULL);
}
</code>```

The logic goes as following: within sigfoo_handler, SIGFOO is blocked so it cannot interrupt the pthread_mutex_lock. Within update_gvars, SIGFOO cannot be raised in the current thread during the pthread_sigmask-protected critical region, and so it can't interrupt the pthread_mutex_lock either. Assuming no other signals (and we can always block any other signals that could be problematic), the lock/unlocks should always proceed in a normal, uninterruptible fashion on the current thread, and the use of lock/unlock should ensure that other threads don't interfere. Am I right, or should I avoid this approach?

答:
I found this paper https://www.cs.purdue.edu/homes/rego/cs543/threads/signals.pdf that discusses running AS-unsafe code in sig handlers safely by

masking out signals in AS-unsafe blocks of normal-context code (explored as less efficient) OR

protecting AS-unsafe blocks of normal-context code with a global sig_atomic volatile flag that prevents the AS-unsafe code in the handler from being entered if set (explored as efficient)

This approach satisfies the part of the POSIX standard that says that
calling AS-unsafe functions in sig-handlers is only deemed unsafe if the sighandler interrupts an AS-unsafe function (http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03_03 :  scroll down to the 1st paragraph after the function list)

I think what you're toying with here is essentially a more fine-grained version of this idea, since you're not trying to prevent

```<code>pthread_mutex_lock(&gvars_mutex);
int cond = gvars.a == 42 || gvars.b == 13;
pthread_mutex_unlock(&gvars_mutex);
</code>```

run from a sig-handler from clashing with any AS-unsafe code but rather just with this same/similar AS-unsafe code dealing with this mutex and these variables.

Unfortunately, POSIX only seems to have a code-only concept of signal-safety: a function is either safe or unsafe, regardless of its arguments.

However, IMO, a semaphores/mutex has no good reason to operate on any data or OS handles other than those contained in the mutex/semaphore they're passed, so I think calling sem_wait(&sem)/pthread_mutex_lock(&mx); from a signal handler ought to be safe if it's guaranteed to never clash with a sem_wait/pthread_mutex_lock to the same mutex, even though the POSIX standard technically says it shouldn't be safe (counter-arguments more than welcome).

Body:
First, I am aware that the mutexes are not considered async-safe normally. This question concerns the use of sigprocmask to make mutexes safe in a multithreaded program with async signals and signal handlers.

I have some code conceptually like the following:

struct { int a, b; } gvars;

void sigfoo_handler(int signo, siginfo_t *info, void *context) {
    if(gvars.a == 42 || gvars.b == 13) {
        /* run a chained signal handler */
    }
}

/* called from normal code */
void update_gvars(int a, int b) {
    gvars.a = a;
    gvars.b = b;
}

gvars is a global variable which is too large to fit in a single sig_atomic_t. It is updated by normal code and read from the signal handler. The controlled code is a chained signal handler, and so it must run in signal handler context (it may use info or context). Consequently, all accesses to gvars have to be controlled via some sort of synchronization mechanism. Complicating matters, the program is multithreaded, and any thread may receive a SIGFOO.

Question: By combining sigprocmask (or pthread_sigmask) and pthread_mutex_t, is it possible to guarantee synchronization, using code like the following?

struct { int a, b; } gvars;
pthread_mutex_t gvars_mutex;

void sigfoo_handler(int signo, siginfo_t *info, void *context) {
    /* Assume SIGFOO's handler does not have NODEFER set, i.e. it is automatically blocked upon entry */
    pthread_mutex_lock(&gvars_mutex);
    int cond = gvars.a == 42 || gvars.b == 13;
    pthread_mutex_unlock(&gvars_mutex);

    if(cond) {
        /* run a chained signal handler */
    }
}

/* called from normal code */
void update_gvars(int a, int b) {
    sigset_t set, oset;
    sigemptyset(&set);
    sigaddset(&set, SIGFOO);
    pthread_sigmask(SIG_BLOCK, &set, &oset);
    pthread_mutex_lock(&gvars_mutex);
    gvars.a = a;
    gvars.b = b;
    pthread_mutex_unlock(&gvars_mutex);
    pthread_sigmask(SIG_SETMASK, &oset, NULL);
}

The logic goes as following: within sigfoo_handler, SIGFOO is blocked so it cannot interrupt the pthread_mutex_lock. Within update_gvars, SIGFOO cannot be raised in the current thread during the pthread_sigmask-protected critical region, and so it can't interrupt the pthread_mutex_lock either. Assuming no other signals (and we can always block any other signals that could be problematic), the lock/unlocks should always proceed in a normal, uninterruptible fashion on the current thread, and the use of lock/unlock should ensure that other threads don't interfere. Am I right, or should I avoid this approach?

Body:
I found this paper https://www.cs.purdue.edu/homes/rego/cs543/threads/signals.pdf that discusses running AS-unsafe code in sig handlers safely by

masking out signals in AS-unsafe blocks of normal-context code (explored as less efficient) OR

protecting AS-unsafe blocks of normal-context code with a global sig_atomic volatile flag that prevents the AS-unsafe code in the handler from being entered if set (explored as efficient)

This approach satisfies the part of the POSIX standard that says that
calling AS-unsafe functions in sig-handlers is only deemed unsafe if the sighandler interrupts an AS-unsafe function (http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03_03 :  scroll down to the 1st paragraph after the function list)

I think what you're toying with here is essentially a more fine-grained version of this idea, since you're not trying to prevent

pthread_mutex_lock(&gvars_mutex);
int cond = gvars.a == 42 || gvars.b == 13;
pthread_mutex_unlock(&gvars_mutex);

run from a sig-handler from clashing with any AS-unsafe code but rather just with this same/similar AS-unsafe code dealing with this mutex and these variables.

Unfortunately, POSIX only seems to have a code-only concept of signal-safety: a function is either safe or unsafe, regardless of its arguments.

However, IMO, a semaphores/mutex has no good reason to operate on any data or OS handles other than those contained in the mutex/semaphore they're passed, so I think calling sem_wait(&sem)/pthread_mutex_lock(&mx); from a signal handler ought to be safe if it's guaranteed to never clash with a sem_wait/pthread_mutex_lock to the same mutex, even though the POSIX standard technically says it shouldn't be safe (counter-arguments more than welcome).


问:
Early page fault is triggered with IF flag cleared, but how is that possible?
I'm reading the latest linux source code and I find that early page fault interrupt is triggered even if instruction cli is executed and IF flag is cleared. But how is that possible? Is it non-maskable? If so, what's the relationship with NMI?

答:
Term "maskable" is applicable only to interrupts of type IRQ (Interrupt ReQuest), which are also referred as Hardware Interrupts.

However, page fault interrupt is not an IRQ, but of Exception type. Such types of interrupts cannot be masked by definition.

About classification of interrupts see e.g. here: http://wiki.osdev.org/Interrupt.

Think about: what should CPU do, if page fault, caused by an instruction's execution, could be masked? In that case, CPU would unable to perform the instruction and to proceed futher.

Opposite: if timer IRQ is masked, CPU can proceed as normal.


问:
Navbar growing wider than bootstrap column width
I am trying to position navbar fixed to the left-hand side of the screen effectively in a sidebar with the rest of the page content rendering to the right.

Currently, I have tried to split the page into two using bootstrap columns like so:

html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

/********************************************
*                                           *
*                                           *
*               WRAPPERS                    *
*                                           *
*                                           *
********************************************/

#sidebarWrapper {
  height: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}

/********************************************
*                                           *
*                                           *
*             SIDEBAR NAV STYLE             *
*                                           *
*                                           *
********************************************/

.sidebar-nav {
  margin: 0;
  padding: 0;
  top: 0;
  list-style: none;
  position: absolute;
}

.sidebar-nav>li {
  display: inline-block;
  line-height: 20px;
  position: relative;
  width: 100%;
}

/********************************************
*                                           *
*                                           *
*                  DIV STYLE                *
*                                           *
*                                           *
********************************************/

.container-fluid {
  height: 100%;
}

.container-fluid h1 {
  padding: 0;
  margin: 0;
}

/********************************************
*                                           *
*                                           *
*              PAGE BODY STYLE              *
*                                           *
*                                           *
********************************************/

.header {
  height: 10%;
  background-color: yellow;
}

.contentBody {
  height: 80%;
  background-color: green;
}

.footer {
  height: 10%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-2">
      <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="sidebarWrapper">
        <ul class="nav sidebar-nav">
          <li>
            Dashboard
          </li>
        </ul>
      </nav>
    </div>
    <div class="col-lg-10">
      <div class="header">
        <h1>Header</h1>
      </div>
      <div class="contentBody">
        <h1>Content</h1>
      </div>
      <div class="footer">
        <h1>Footer</h1>
      </div>
    </div>
  </div>
</div></code>```

However, as you can see from the snippet my navbar seems to brute force over any bootstrap column restrictions and takes the width of the whole page.

How can I prevent it from doing so, so that it takes 100% of the width of the bootstrap column but no more and no less?

答:
Your id have 100% height inside the css, I think you should change it to width:100% instead.</p>

```<code><nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="sidebarWrapper">

#sidebarWrapper {
  width: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}
</code>```

Body:
I am trying to position navbar fixed to the left-hand side of the screen effectively in a sidebar with the rest of the page content rendering to the right.

Currently, I have tried to split the page into two using bootstrap columns like so:

html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

/********************************************
*                                           *
*                                           *
*               WRAPPERS                    *
*                                           *
*                                           *
********************************************/

#sidebarWrapper {
  height: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}

/********************************************
*                                           *
*                                           *
*             SIDEBAR NAV STYLE             *
*                                           *
*                                           *
********************************************/

.sidebar-nav {
  margin: 0;
  padding: 0;
  top: 0;
  list-style: none;
  position: absolute;
}

.sidebar-nav>li {
  display: inline-block;
  line-height: 20px;
  position: relative;
  width: 100%;
}

/********************************************
*                                           *
*                                           *
*                  DIV STYLE                *
*                                           *
*                                           *
********************************************/

.container-fluid {
  height: 100%;
}

.container-fluid h1 {
  padding: 0;
  margin: 0;
}

/********************************************
*                                           *
*                                           *
*              PAGE BODY STYLE              *
*                                           *
*                                           *
********************************************/

.header {
  height: 10%;
  background-color: yellow;
}

.contentBody {
  height: 80%;
  background-color: green;
}

.footer {
  height: 10%;
  background-color: blue;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

            Dashboard

Header

Content

Footer

However, as you can see from the snippet my navbar seems to brute force over any bootstrap column restrictions and takes the width of the whole page.

How can I prevent it from doing so, so that it takes 100% of the width of the bootstrap column but no more and no less?

Body:
Your id have 100% height inside the css, I think you should change it to width:100% instead.

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="sidebarWrapper">

#sidebarWrapper {
  width: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}


问:
Should Supplier be used to supply File Stream?
I needed to supply a Stream of a file more than once so that different operations could be executed upon it at different times, I used the following Supplier:

```<code>Supplier<Stream<String>> linesSupplier = () -> {
    try
    {
        return Files.lines(Paths.get(file.toURI()));
    }
    catch (IOException e)
    {
        log.error("Error while supplying file " + file.getName(), e);
    }
    return null;
};
</code>```

Unfortunately, it leads to a file handle leak, so I tried to use a try-with-resource as suggested.

```<code>Supplier<Stream<String>> linesSupplier = () -> {
    try(Stream<String> lines = Files.lines(Paths.get(file.toURI())))
    {
        return lines;
    }
    catch (IOException e)
    {
        log.error("Error while supplying file " + file.getName(), e);
    }
    return null;
};
</code>```

But now the first time I use linesSupplier.get(), I get a java.lang.IllegalStateException.

Is it a sign that I should try to actively avoid Supplier, whatever the circumstances?

答:
Of course not - you should use a Supplier when you need to. The problem here is that Stream class implements AutoCloseable and your try-with-resource is calling it's close method after it ends.

As such, one should either make the Supplier responsible of closing the Stream by moving the try-with-resource or one could return something else as a Stream, for example, a List<String>.

Body:
I needed to supply a Stream of a file more than once so that different operations could be executed upon it at different times, I used the following Supplier:

Supplier<Stream<String>> linesSupplier = () -> {
    try
    {
        return Files.lines(Paths.get(file.toURI()));
    }
    catch (IOException e)
    {
        log.error("Error while supplying file " + file.getName(), e);
    }
    return null;
};

Unfortunately, it leads to a file handle leak, so I tried to use a try-with-resource as suggested.

Supplier<Stream<String>> linesSupplier = () -> {
    try(Stream<String> lines = Files.lines(Paths.get(file.toURI())))
    {
        return lines;
    }
    catch (IOException e)
    {
        log.error("Error while supplying file " + file.getName(), e);
    }
    return null;
};

But now the first time I use linesSupplier.get(), I get a java.lang.IllegalStateException.

Is it a sign that I should try to actively avoid Supplier, whatever the circumstances?


问:
Laravel post request not works
I have Form in Laravel and when i submit the form to redirect another page("action = panel") with inputs's value. but problem is that when i enter in another's link it displays error. what is wrong?

This is form

this is another page when submit form

this is error when i enter in link again

this is form code:

```<code><form action="{{route('adminPanel')}}" class="form" method="POST">
    <p>Name:</p>
    <input type="text" name="name"><br>
    <p>Password:</p>
    <input type="password" name="password"><br>
    <input type="submit" name="submit" value="Enter As Admin" class="submit">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</code>```

this is routes:

```<code>Route::get('/', [

    'uses' => 'AdminController@getAdminIndex',

    'as' => 'index.admin'
]);
Route::post('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);
</code>```

this is controller:

```<code>class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
        return view('admin/admin', ['name' => $request->name]);
    }
}
</code>```

答:
this is because when you enter an address in address bar, your are actually sending a get request. but you've defined your route with post method!

to fix this you can use any:

```<code>Route::any('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);
</code>```

and in controller:

```<code>use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
       $name = $request->name ?: Auth::user()->name;
       return view('admin/admin', ['name' => $name]);
    }
}
</code>```

Title: Laravel post request not works

Body:
I have Form in Laravel and when i submit the form to redirect another page("action = panel") with inputs's value. but problem is that when i enter in another's link it displays error. what is wrong?

This is form

this is another page when submit form

this is error when i enter in link again

this is form code:

<form action="{{route('adminPanel')}}" class="form" method="POST">

Name:

    <input type="text" name="name">

Password:

    <input type="password" name="password">

    <input type="submit" name="submit" value="Enter As Admin" class="submit">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

this is routes:

Route::get('/', [

    'uses' => 'AdminController@getAdminIndex',

    'as' => 'index.admin'
]);
Route::post('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);

this is controller:

class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
        return view('admin/admin', ['name' => $request->name]);
    }
}

Body:
this is because when you enter an address in address bar, your are actually sending a get request. but you've defined your route with post method!

to fix this you can use any:

Route::any('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);

and in controller:

use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
       $name = $request->name ?: Auth::user()->name;
       return view('admin/admin', ['name' => $name]);
    }
}


问:
React - Refactor out eval function and improve code quality
I have just started playing with React today and built a simple Calculator app.
Would someone please be able to advise on steps I could take to improve my code.

Ideally, I want ideas on how to properly use state, and how to refactor out my use of the eval function.

Would appreciate any feedback on how you would have done this differently aswell :)

import React from 'react';

class Calculator extends React.Component {
  constructor(props){
      super(props);
      this.state = {
        prev: [],
        total: []
      };
  }

  inputDigit(int) {

    var newArr = this.state.total.slice();
    newArr.push(int);
    this.setState({total: newArr});

  }

  addition(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "+");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  minus(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "-");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  divide(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "/");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  multiply(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "*");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;
  }

  clearInput() {

    this.setState({total:[],prev:[]});

  }

  sum(currNum) {

    var store = this.arrToNum(currNum);
    var newArr = this.state.prev.slice();
    newArr.push(store);
    console.log(newArr.join(" "));
    var sum = eval(newArr.join(" "));

    this.setState({total:[sum]});

  }

  arrToNum(arr) {

    var test = Number(arr.join(''));

    return test;

  }

  makePretty(num) {

    var newNum = this.arrToNum(num);
    var formatNum = newNum.toLocaleString();

    return formatNum;

  }

  render() {
    return(

{this.makePretty(this.state.total)}

            <button className="square" onClick={() => this.inputDigit(7)}>7</button>
            <button className="square" onClick={() => this.inputDigit(8)}>8</button>
            <button className="square" onClick={() => this.inputDigit(9)}>9</button>
            <button className="square" onClick={() => this.addition(this.state.total)}>+</button>

            <button className="square" onClick={() => this.inputDigit(4)}>4</button>
            <button className="square" onClick={() => this.inputDigit(5)}>5</button>
            <button className="square" onClick={() => this.inputDigit(6)}>6</button>
            <button className="square" onClick={() => this.minus(this.state.total)}>-</button>

            <button className="square" onClick={() => this.inputDigit(1)}>1</button>
            <button className="square" onClick={() => this.inputDigit(2)}>2</button>
            <button className="square" onClick={() => this.inputDigit(3)}>3</button>
            <button className="square" onClick={() => this.multiply(this.state.total)}>*</button>

            <button className="square" onClick={() => this.inputDigit(0)}>0</button>
            <button className="square" onClick={() => this.inputDigit(".")}>.</button>
            <button className="square" onClick={() => this.sum(this.state.total)}>=</button>
            <button className="square" onClick={() => this.divide(this.state.total)}>/</button>

            <button className="square full" onClick={() => this.clearInput()}>CLEAR</button>

    );
  }
}

export default Calculator;```

答:
1-

```<code>inputDigit(int) {
  this.setState({total: [
    ...this.state.total,
    int
  ]})
}
</code>```

2-

```<code>addition(prevNum) {
 let store = this.arrToNum(prevNum);
 let string = [...this.state.prev, store, '+'].join(' ');
 this.setState({total:[] , prev: [string]});
 return prevNum;
}
</code>```

and you have to follow the same pattern for the rest of the functions

3- add this function

```<code>renderItem(value, onClick) {
   return <button className="square" onClick={onclick}>{value}</button>
}
</code>```

4- replace this:

```<code><div className="row">
            <button className="square" onClick={() => this.inputDigit(7)}>7</button>
            <button className="square" onClick={() => this.inputDigit(8)}>8</button>
            <button className="square" onClick={() => this.inputDigit(9)}>9</button>
            <button className="square" onClick={() => this.addition(this.state.total)}>+</button>
          </div>
</code>```

with this

```<code><div className="row">
  {[
     ['7',() => this.inputDigit(7)],
     ['8',() => this.inputDigit(8)],
     ['9',() => this.inputDigit(9)],
     ['+',() => this.addition(this.state.total)],
   ].map(([value, onClick]) => this.renderItem(value, onClick)})
</code>```

5- follow the same pattern with all the views

Body:
1-

inputDigit(int) {
  this.setState({total: [
    ...this.state.total,
    int
  ]})
}

2-

addition(prevNum) {
 let store = this.arrToNum(prevNum);
 let string = [...this.state.prev, store, '+'].join(' ');
 this.setState({total:[] , prev: [string]});
 return prevNum;
}

and you have to follow the same pattern for the rest of the functions

3- add this function

renderItem(value, onClick) {
   return <button className="square" onClick={onclick}>{value}</button>
}

4- replace this:

<div className="row">
            <button className="square" onClick={() => this.inputDigit(7)}>7</button>
            <button className="square" onClick={() => this.inputDigit(8)}>8</button>
            <button className="square" onClick={() => this.inputDigit(9)}>9</button>
            <button className="square" onClick={() => this.addition(this.state.total)}>+</button>
          </div>

with this

<div className="row">
  {[
     ['7',() => this.inputDigit(7)],
     ['8',() => this.inputDigit(8)],
     ['9',() => this.inputDigit(9)],
     ['+',() => this.addition(this.state.total)],
   ].map(([value, onClick]) => this.renderItem(value, onClick)})

5- follow the same pattern with all the views


问:
Codacy: Possible to add patterns for markdown documentation?
In our project we are hosting the code at github and placing the documentation in the "docs" directory. We would like to add so-called Codacy "patterns" for the documentation (written in markdown), how can this be done? Is this something that can only be done manually?

Right this is what it looks like for us:

Grateful for help and with kind regards,
Tord

答:
At this moment it seems codacy doesn't support markdown files: https://support.codacy.com/hc/en-us/articles/207994735-Supported-Languages

Also, I think Codacy doesn't have Documentation patterns anymore (go to https://www.codacy.com/account/patterns and filter patterns by category: there's no 'documentation' category anymore)


问:
cannot find pthread.c in linux folder
I have downloaded kernel and the kernel resides in folder called Linux-2.6.32.28 in which I can find /Kernel/Kthread.c
I found Kthread.c but I cannot find pthread.c in Linux-2.6.32.28
I found Kthread.c in Linux-3.13/Kernel and Linux-4.7.2/Kernel

locate pthread.c finds file pthread.c in Computer/usr folder that comes when I install Ubuntu but pthread.c is not available in downloaded folders Linux-2.6.32.28, Linux-3.13, Linux-4.7.2

MORE: There are two sets of function calls. 1. System Calls 2. Library Calls.

For a computer to do any task it has to use hardware resources. So, how library calls differ from system calls?

System calls always use kernel which means hardware.
Library calls means no usage of kernel or hardware?

I know that library calls sometimes may resolve to system call.

What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources when compared with library calls and vice-versa.

Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right?

答:
Regarding your second cluster of questions: Everything a computer does is ultimately done by hardware.  But we can make some distinctions between different kinds of hardware within the computer, and different kinds of programs interacting with them in different ways.

A modern computer can be divided into three major components: central processing unit (CPU), main memory (random access memory, RAM), and "peripherals" such as disks, network transceivers, displays, graphics cards, keyboards, mice, etc.  Things that the CPU and RAM can do by themselves without involving peripherals in any way are called computation.  Any operation involving at least one peripheral is called input/output (I/O).  All programs do some of both, but some programs mostly do computation, and other programs mostly do I/O.

A modern operating system is also divided into two major components: the kernel, which is a self-contained program that is given special abilities that no other program has (such as the ability to communicate with peripherals and the ability to control the allocation of RAM), and is responsible for supervising execution of all the other programs; and the user space, which is an unbounded set of programs that have no such special abilities.

User space programs can do computation by themselves, but to do I/O they must, essentially, ask the kernel to do it for them.  A system call is a request from a user-space program to the kernel.  Many system calls are requests to perform I/O, but the kernel can also be requested to do other things, such as provide general information, set up communication channels among programs, allocate RAM, etc. A library is a component of a user space program.  It is, essentially, a collection of "functions" that someone else has written for you, that you can use as if you wrote them yourself.  There are many libraries, and most of them don't do anything out of the ordinary.  For instance, zlib is a library that (provides functions that) compress and uncompress data.

However, "the C library" is special because (on all modern operating systems, except Windows) it is responsible for interacting directly with the kernel.  Nearly all programs, and nearly all libraries, will not make system calls themselves; they will instead ask the C library to do it for them.  Because of this, it can often be confusing trying to tell whether a particular C library function does all of its work itself or whether it "wraps" one or more system calls.  The pthreads functions in particular tend to be a complicated tangle of both.  If you want to learn how operating systems are put together at their lower levels, I recommend you start with something simpler, such as how the stdio.h "buffered I/O" routines (fopen, fclose, fread, fwrite, puts, etc) ultimately call the unistd.h/fcntl.h "raw I/O" routines (open, close, read, write, etc) and how the latter set of functions are just wrappers around system calls.

(Assigning the task of wrapping system calls to the runtime library for the C programming language is a historical accident and we probably wouldn't do it that way again if we were going to start over from scratch.)

Title: cannot find pthread.c in linux folder


问:
Mahapps Metro Custom IconPack
I am working on a project that utilizes the Mahapps Metro Library, everything is going smoothly except for one issue. This application requires extensive use of Icons and I need to create some additional Icons.

I have searched high and low for some information on how to define Icons using the MahApps.Metro.IconPacks library. I have found all sorts of information on how to use them but nothing on how to define custom Icons.

I downloaded the MahApps.Metro.IconPacks library hoping to find an example of how to accomplish this and found that there are several "Auto Generated" files for the different Icon Packs. Obviously there is a tool hiding somewhere but I have no idea where/what it is.

Can someone point me in the right direction on how to go about defining a new Icon Pack? I assume that the Icons are drawn as SVG files and the paths are used as the Icons, is this correct? If so is there a particular convention that needs to be used when drawing the Icons? I have both Inkscape and Corel Draw and noticed that Inkscape has a .xaml export that exports a bunch of Canvas and Paths but not sure if this is the right starting point.

答:
To define your custom IconPack, you can just create a resource file, in which you will place the xaml of every icon you are going to create. As you had the chance to see program like Inkscape, Expression Design, or Adobe Illustrator give you the xaml code of what you have create. You just need to copy that in the resource file, and give it a key, so when you will use this resource file in your app you can get the specific icon.

The icon is only the Path part of the code. The Canvas is just a container

Title: Mahapps Metro Custom IconPack


问:
difference beetwen path.join(__dirname , 'views') and path.join(__dirname + 'views') in node.js
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

```<code>path.join(__dirname + 'views');

path.join(__dirname, 'views');
</code>```

this is my script

```<code>app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work
</code>```

答:
The default function uses commas as separator, not plus sign, that's why it works with comma and not with plus.

See documentation for path.join() in node.js

Body:
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

path.join(__dirname + 'views');

path.join(__dirname, 'views');

this is my script

app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work


问:
Histogram equalization for normalized image without histeq function in MATLAB
i'm trying to make histogram equalization code for normalized image without builtin function in MATLAB like 'histeq'

I have normalized gray image that has values between [0,1]

```<code>    input_img = mat2gray(img);
</code>```

and I have found an example code wihout histeq function

```<code>    for i=1:size(GIm,1)
        for j=1:size(GIm,2)
            value=GIm(i,j);
            freq(value+1)=freq(value+1)+1;
            probf(value+1)=freq(value+1)/numofpixels;
        end
    end

    sum=0;
    no_bins=255;

    %The cumulative distribution probability is calculated.

    for i=1:size(probf)
       sum=sum+freq(i);
       cum(i)=sum;
       probc(i)=cum(i)/numofpixels;
       output(i)=round(probc(i)*no_bins);
    end

    for i=1:size(GIm,1)
        for j=1:size(GIm,2)
                HIm(i,j)=output(GIm(i,j)+1);
        end
    end

    figure,imshow(HIm);
    title('Histogram equalization');
</code>```

but this code is applied to an image that has a grayscale of [0,255]

how should I apply this code to my grayscale normalized image?

my image size 450x450

答:
Use the code you have to compute a 256-bin histogram by scaling your image to fit it:

```<code>input_img_255 = round(input_img * 255);
</code>```

and then use input_img_255 with the code you have. round should be good enough to use the rounded double values as indices as in your code. If you want to be more exact you can use:

```<code>input_img_255 = uint8(round(input_img * 255));
</code>```

so that the values are integers.

Body:
i'm trying to make histogram equalization code for normalized image without builtin function in MATLAB like 'histeq'

I have normalized gray image that has values between [0,1]

    input_img = mat2gray(img);

and I have found an example code wihout histeq function

    for i=1:size(GIm,1)
        for j=1:size(GIm,2)
            value=GIm(i,j);
            freq(value+1)=freq(value+1)+1;
            probf(value+1)=freq(value+1)/numofpixels;
        end
    end

    sum=0;
    no_bins=255;

    %The cumulative distribution probability is calculated.

    for i=1:size(probf)
       sum=sum+freq(i);
       cum(i)=sum;
       probc(i)=cum(i)/numofpixels;
       output(i)=round(probc(i)*no_bins);
    end

    for i=1:size(GIm,1)
        for j=1:size(GIm,2)
                HIm(i,j)=output(GIm(i,j)+1);
        end
    end

    figure,imshow(HIm);
    title('Histogram equalization');

but this code is applied to an image that has a grayscale of [0,255]

how should I apply this code to my grayscale normalized image?

my image size 450x450

Body:
Use the code you have to compute a 256-bin histogram by scaling your image to fit it:

input_img_255 = round(input_img * 255);

and then use input_img_255 with the code you have. round should be good enough to use the rounded double values as indices as in your code. If you want to be more exact you can use:

input_img_255 = uint8(round(input_img * 255));

so that the values are integers.


问:
Escaping literal s and ' while using sed
I'm using sed in Gitbash for Windows to run through a body of XML texts marking up certain strings.

One of the strings concerned is:

```<code>S. Margaret's
</code>```

which needs to be enclosed in an element like so:

```<code><orgName id="16">S.Margaret's</orgName>
</code>```

And so my script reads:

```<code>sed -e 's/S. Margaret's/<orgName id="16">S. Margaret's<\/orgName>/g'
</code>```

Where I have escaped the forward slash in the  tag that I need to insert.

This throws an error "orgName: No such file or directory"

I suppose the issue is to do with the 's/ after Margaret, which is interpreted as the beginning of a new command, but how do I escape it? I've tried various combinations of backslashes but without success.

答:
Complimenting AlexP's answer to use escaped single quotes, I think you can also do double-quoting of the search/replace part, since you don't have any shell variables that needs expansion within it. This way you don't have to worry about the escaping the single quote or white space present. Also since the replacement text involves the / character, recommend changing sed default separator from / to | or any non-meta character of your choice.

```<code>sed -e "s|S. Margaret's|<orgName id=\"16\">S. Margaret's</orgName>|g" file
</code>```

Body:
I'm using sed in Gitbash for Windows to run through a body of XML texts marking up certain strings.

One of the strings concerned is:

S. Margaret's

which needs to be enclosed in an element like so:

<orgName id="16">S.Margaret's</orgName>

And so my script reads:

sed -e 's/S. Margaret's/<orgName id="16">S. Margaret's<\/orgName>/g'

Where I have escaped the forward slash in the  tag that I need to insert.

This throws an error "orgName: No such file or directory"

I suppose the issue is to do with the 's/ after Margaret, which is interpreted as the beginning of a new command, but how do I escape it? I've tried various combinations of backslashes but without success.

Body:
Complimenting AlexP's answer to use escaped single quotes, I think you can also do double-quoting of the search/replace part, since you don't have any shell variables that needs expansion within it. This way you don't have to worry about the escaping the single quote or white space present. Also since the replacement text involves the / character, recommend changing sed default separator from / to | or any non-meta character of your choice.

sed -e "s|S. Margaret's|<orgName id=\"16\">S. Margaret's</orgName>|g" file


问:
Laravel5 Eloquent: How to get a few articles from special condition?
First, I'm sorry my poor english.

I want to got highest views with 5 articles.
I tried it, but I'm having problem with Eloquent query.

laravel source

```<code><?php
    $up = "SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x)";
    $builder = new \App\Article;
    $query = $builder->selectRaw("articles.*, $up");
?>
    @forelse($query->latest() as $article)
        <img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
    @empty
        <p class="text-center text-danger">
        empty...
        </p>
    @endforelse
</code>```

DB query result

```<code>MariaDB [test]> SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x);
+------+
| id   |
+------+
| 4018 |
| 4045 |
| 3800 |
| 4011 |
| 4005 |
+------+
5 rows in set (0.00 sec)
</code>```

I've seen the other posts on this topic, but i didn't get the solution.

Thanks for your help.

答:
5 articles ordered by views you just need to write in your controller:

```<code>$articles = Article::orderBy('views', DESC)->take(5)->get();
return view('article', ['articles' => $articles
]);
</code>```

in your article.blade.php:

```<code>@forelse($articles() as $article)
    <img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@forelse
    <p class="text-center text-danger">
    empty...
    </p>
@endforelese
</code>```

Body:
First, I'm sorry my poor english.

I want to got highest views with 5 articles.
I tried it, but I'm having problem with Eloquent query.

laravel source

<?php
    $up = "SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x)";
    $builder = new \App\Article;
    $query = $builder->selectRaw("articles.*, $up");
?>
    @forelse($query->latest() as $article)
        thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
    @empty

        empty...

    @endforelse

DB query result

MariaDB [test]> SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x);
+------+
| id   |
+------+
| 4018 |
| 4045 |
| 3800 |
| 4011 |
| 4005 |
+------+
5 rows in set (0.00 sec)

I've seen the other posts on this topic, but i didn't get the solution.

Thanks for your help.

Body:
5 articles ordered by views you just need to write in your controller:

$articles = Article::orderBy('views', DESC)->take(5)->get();
return view('article', ['articles' => $articles
]);

in your article.blade.php:

@forelse($articles() as $article)
    <img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@forelse
    <p class="text-center text-danger">
    empty...
    </p>
@endforelese


问:
Is there an easier way to send ENTER key in GNU Screen?
Currently I am using a script to spawn a daemon:

```<code>screen -r user -X stuff "spawn daemon"
screen -r user -X eval "stuff \015"
</code>```

Is there an easier way to send the enter key ("\015"), or in fact a better way of doing this? (I have to use screen.)

I assume that because I'm not attaching the screen, I won't be able to get the outcome/output of the "spawn daemon" command. Is that correct?

答: As for the second question, you can enable logging, and read from the log file.</p>

Body:
Currently I am using a script to spawn a daemon:

screen -r user -X stuff "spawn daemon"
screen -r user -X eval "stuff \015"

Is there an easier way to send the enter key ("\015"), or in fact a better way of doing this? (I have to use screen.)

I assume that because I'm not attaching the screen, I won't be able to get the outcome/output of the "spawn daemon" command. Is that correct?


问:
posting multiple parameters in jsonobjectrequest volley
I need to post multiple parameters in postbody in Jsonobject postbody here.I searched all over stack but cudnt find out.please help me

```<code>public void startArchive(String sessionId) {
    JSONObject postBody = null;
    try {
        postBody = new JSONObject("{\"sessionId\": \"" + sessionId + "\"}");
    } catch (JSONException e){
        Log.e(LOG_TAG, "Parsing json body failed");
        e.getStackTrace();
    }

    this.reqQueue.add(new JsonObjectRequest(Request.Method.POST, OpenTokConfig.ARCHIVE_START_ENDPOINT,
            postBody,
            new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i(LOG_TAG, "archive started");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            delegate.onWebServiceCoordinatorError(error);
        }
    }));
}
</code>```

my parameters

```<code>{
"sessionId" : "session_id",
"hasAudio" : true,
"hasVideo" : true,
"name" : "archive_name"
"outputMode" : "composed",
</code>```

}

I need to include this as well

```<code>  Content-Type:application/json
</code>```

postman gives this response

答:
Hope you are looking for this thing.!
You can send  JSON Object Request try below method .

```<code>HashMap<String, String> parrams = new HashMap<String, String>();
parrams.put("sessionId", "session_id");
parrams.put("hasAudio", "true");
parrams.put("hasVideo", "true");
parrams.put("name", "archive_name");
parrams.put("outputMode", "composed");

JsonObjectRequest requestCall = new JsonObjectRequest(Request.Method.POST, OpenTokConfig.ARCHIVE_START_ENDPOINT,
       new JSONObject(parrams) ,
        new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Log.i(LOG_TAG, "archive started");
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        delegate.onWebServiceCoordinatorError(error);
    }
}));

Volley.newRequestQueue(context).add(requestCall);
</code>```

Body:
I need to post multiple parameters in postbody in Jsonobject postbody here.I searched all over stack but cudnt find out.please help me

public void startArchive(String sessionId) {
    JSONObject postBody = null;
    try {
        postBody = new JSONObject("{\"sessionId\": \"" + sessionId + "\"}");
    } catch (JSONException e){
        Log.e(LOG_TAG, "Parsing json body failed");
        e.getStackTrace();
    }

    this.reqQueue.add(new JsonObjectRequest(Request.Method.POST, OpenTokConfig.ARCHIVE_START_ENDPOINT,
            postBody,
            new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i(LOG_TAG, "archive started");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            delegate.onWebServiceCoordinatorError(error);
        }
    }));
}

my parameters

{
"sessionId" : "session_id",
"hasAudio" : true,
"hasVideo" : true,
"name" : "archive_name"
"outputMode" : "composed",

}

I need to include this as well

  Content-Type:application/json

postman gives this response

Body:
Hope you are looking for this thing.!
You can send  JSON Object Request try below method .

HashMap<String, String> parrams = new HashMap<String, String>();
parrams.put("sessionId", "session_id");
parrams.put("hasAudio", "true");
parrams.put("hasVideo", "true");
parrams.put("name", "archive_name");
parrams.put("outputMode", "composed");

JsonObjectRequest requestCall = new JsonObjectRequest(Request.Method.POST, OpenTokConfig.ARCHIVE_START_ENDPOINT,
       new JSONObject(parrams) ,
        new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Log.i(LOG_TAG, "archive started");
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        delegate.onWebServiceCoordinatorError(error);
    }
}));

Volley.newRequestQueue(context).add(requestCall);


问:
Is there a global: false for .load(url) functions?
I have a loader which is called on all ajaxStart and ajaxStop functions.

```<code>$(document).on({
    ajaxStart: function () { $body.addClass("loading"); },
    ajaxStop: function () { $body.removeClass("loading"); }
});
</code>```

The loader displays for $.ajax functions, which is correct.
But the loader also displays for

```<code>$("#div").load('www.mydummyurl.com')
</code>```

Is there a way i can unbind the ajaxStart event for .load()?
or a

```<code>$("#div").load('www.mydummyurl.com', global:false)
</code>```

I am lost! Please help.

答:
Instead of using .load shorthand, use .ajax:

```<code>$.ajax({
  url: "www.mydummyurl.com",
  global: false,
});
</code>```

It will allow you to pass extra parameters - like global in this case.

Ref: https://api.jquery.com/Ajax_Events/ (Global Events section)

Body:
I have a loader which is called on all ajaxStart and ajaxStop functions.

$(document).on({
    ajaxStart: function () { $body.addClass("loading"); },
    ajaxStop: function () { $body.removeClass("loading"); }
});

The loader displays for $.ajax functions, which is correct.
But the loader also displays for

$("#div").load('www.mydummyurl.com')

Is there a way i can unbind the ajaxStart event for .load()?
or a

$("#div").load('www.mydummyurl.com', global:false)

I am lost! Please help.

Body:
Instead of using .load shorthand, use .ajax:

$.ajax({
  url: "www.mydummyurl.com",
  global: false,
});

It will allow you to pass extra parameters - like global in this case.

Ref: https://api.jquery.com/Ajax_Events/ (Global Events section)


问:
Disable automatic (preview) window (buffer) with a function signature
Every time I click dot, the function signature appears in a separate buffer.

```<code>import sys

sys.argv   # in this moment I have a separate buffer opened with sys.argv signature
</code>```

Then this buffer exists until manually closed.

I'd like to have it only when I press ctrl-K. Or at least it disappears when I exit insert mode...

答:
Realize that this buffer is called preview window. Thus the :pc or simply <C-w-C-z> works to close it

```<code>CTRL-W CTRL-Z                   *CTRL-W_CTRL-Z* *:pc* *:pclose*
:pc[lose][!]    Close any "Preview" window currently open.  When the 'hidden'
        option is set, or when the buffer was changed and the [!] is
        used, the buffer becomes hidden (unless there is another
        window editing it).  The command fails if any "Preview" buffer
        cannot be closed.  See also |:close|.
</code>```

Body:
Every time I click dot, the function signature appears in a separate buffer.

import sys

sys.argv   # in this moment I have a separate buffer opened with sys.argv signature

Then this buffer exists until manually closed.

I'd like to have it only when I press ctrl-K. Or at least it disappears when I exit insert mode...

Body:
Realize that this buffer is called preview window. Thus the :pc or simply <C-w-C-z> works to close it

CTRL-W CTRL-Z                   *CTRL-W_CTRL-Z* *:pc* *:pclose*
:pc[lose][!]    Close any "Preview" window currently open.  When the 'hidden'
        option is set, or when the buffer was changed and the [!] is
        used, the buffer becomes hidden (unless there is another
        window editing it).  The command fails if any "Preview" buffer
        cannot be closed.  See also |:close|.


答:
First you have to your services sttuf in the controller to clean up the views and to respect the MVC pattern.

So in the controller you can use Eloquent to do that :

```<code>$articles = App\Article::orderBy('view_count', 'desc')
               ->take(5)
               ->get();

return view('SomeView')->withArticles($articles);
</code>```

And in SomeView.blade.php :

```<code>@forelse($articles as $article)
    <img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@empty
    <p class="text-center text-danger">
    empty...
    </p>
@endforelse
</code>```

Title: Laravel5 Eloquent: How to get a few articles from special condition?

Body:
First you have to your services sttuf in the controller to clean up the views and to respect the MVC pattern.

So in the controller you can use Eloquent to do that :

$articles = App\Article::orderBy('view_count', 'desc')
               ->take(5)
               ->get();

return view('SomeView')->withArticles($articles);

And in SomeView.blade.php :

@forelse($articles as $article)
    <img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@empty
    <p class="text-center text-danger">
    empty...
    </p>
@endforelse


问:
Removing array from multidimensional array based off array values
I am currently attempting to create a add to cart and remove from cart function for my website. Currently, I am storing the user's information in a session variable name shopping cart. print_r that session variable as the following format was returned to me:

```<code>Array
(
    [0] => Array
        (
            [productID] => 3
            [productTitle] => Life Without Limits
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/lifewithoutlimits
            [productPrice] => 38.00
        )

    [1] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)
</code>```

I was able to get the add to cart function working, but I'm currently stuck at the remove from cart function. When a user clicks on the remove button, that particular productID will be sent via ajax to my php file, and from there I would like to remove the product array from the shopping cart array. For example, if I want to remove a product with productID = 3, the shopping cart array should only return:

```<code>Array
(
    [0] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)
</code>```

How do I go about achieving this? Thank you for your help in advance!

答:
If you are using (PHP 5 >= 5.5.0) you can use the below simple method to get the key and unset the item from the shopping cart array.</p>

```<code>$key = array_search(4, array_column($arr, 'productID'));
if(!empty($key)){
    unset($arr[$key]);
}
</code>```

Body:
I am currently attempting to create a add to cart and remove from cart function for my website. Currently, I am storing the user's information in a session variable name shopping cart. print_r that session variable as the following format was returned to me:

Array
(
    [0] => Array
        (
            [productID] => 3
            [productTitle] => Life Without Limits
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/lifewithoutlimits
            [productPrice] => 38.00
        )

    [1] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)

I was able to get the add to cart function working, but I'm currently stuck at the remove from cart function. When a user clicks on the remove button, that particular productID will be sent via ajax to my php file, and from there I would like to remove the product array from the shopping cart array. For example, if I want to remove a product with productID = 3, the shopping cart array should only return:

Array
(
    [0] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)

How do I go about achieving this? Thank you for your help in advance!

Body:
If you are using (PHP 5 >= 5.5.0) you can use the below simple method to get the key and unset the item from the shopping cart array.

$key = array_search(4, array_column($arr, 'productID'));
if(!empty($key)){
    unset($arr[$key]);
}


问:
Limit on how much data can be returned by Json Post?
I have read that you should not use get json for retrieving sensitive data and you should instead use json post.

I am wondering though what is the limit you can send back. I know with http post there is a limited(I forgot how much).

Does the same limit apply to json post?

答:
There is no limit to the data you can route as part of a GET or a POST.  However, I would suggest that whomever said not to use GET for sensitive data is misleading you.  In particular,

You can certainly encrypt the data (i.e., HTTPS GET) so that it cannot be viewed by others.

You can also specify cache control headers to prevent it from being cached.

Both should eliminate any concerns about sensitivity.  Furthermore, this is not a JSON-specific thing.  REST-based access to Web services can transmit the data in a number of formats (JSON and XML just happen to be the most popular).