问:
remainders for fractions in python
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

```<code>print(1%2)
=1

print(2%4)
=2
</code>```

答:
These aren't fractions, these are simple remainder computations (technically, "modulo" operations, but the distinction is irrelevant for positive operands). 1 % 2 is saying "after removing all complete 2s from 1, what is left?" 2 % 4 is saying "after removing all complete 4s from 2, what is left?" Since in both cases there were no complete 2s or 4s to remove, "what's left?" is the whole amount.

If you want actual fractions, the fractions module will give you the results you expect:

```<code>from fractions import Fraction

print(Fraction(1, 2) == Fraction(2, 4))
</code>```

will print True, because as a fractional quantity, rather than a remainder computation, they're equivalent.

Similarly, performing true division will (sometimes) work, e.g.:

```<code>print(1 / 2 == 2 / 4)
</code>```

also prints True. That's less reliable in the general case though, since floating point math is "broken".

Title: remainders for fractions in python

Body:
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

print(1%2)
=1

print(2%4)
=2

Body:
These aren't fractions, these are simple remainder computations (technically, "modulo" operations, but the distinction is irrelevant for positive operands). 1 % 2 is saying "after removing all complete 2s from 1, what is left?" 2 % 4 is saying "after removing all complete 4s from 2, what is left?" Since in both cases there were no complete 2s or 4s to remove, "what's left?" is the whole amount.

If you want actual fractions, the fractions module will give you the results you expect:

from fractions import Fraction

print(Fraction(1, 2) == Fraction(2, 4))

will print True, because as a fractional quantity, rather than a remainder computation, they're equivalent.

Similarly, performing true division will (sometimes) work, e.g.:

print(1 / 2 == 2 / 4)

also prints True. That's less reliable in the general case though, since floating point math is "broken".


来源: stackexchange

问:
How to cancel (return from) a Kotlin coroutine from within the scope immediately?
In the following code I want to stop the execution of this scope when an exception was caught.

```<code>GlobalScope.launch() {
   try {
       someFunctionThatThrows()
   } catch (exception: Exception) {
       // log
       cancel() // this is not stopping the coroutine and moreWork() is still executed
   }
   moreWork()
}
</code>```

cancel() does not cancel the coroutine immediately but instead sets the flag isActive to false, which requires subsequent checking.

答:
There is special syntax return@launch, return@async etc. depending on which scope you have launched

```<code>GlobalScope.launch() {
   try {
       someFunctionThatThrows()
   } catch (exception: Exception) {
       // log
       return@launch
   }
   moreWork()
}
</code>```

return@async can also have an actual return value that is passed into it's Deferred<T> val.

val deferredValue = GlobalScope.async() { return@aysnc "hello world" }

ContentLicense: CC BY-SA 4.0

Body:
In the following code I want to stop the execution of this scope when an exception was caught.

GlobalScope.launch() {
   try {
       someFunctionThatThrows()
   } catch (exception: Exception) {
       // log
       cancel() // this is not stopping the coroutine and moreWork() is still executed
   }
   moreWork()
}

cancel() does not cancel the coroutine immediately but instead sets the flag isActive to false, which requires subsequent checking.

Body:
There is special syntax return@launch, return@async etc. depending on which scope you have launched

GlobalScope.launch() {
   try {
       someFunctionThatThrows()
   } catch (exception: Exception) {
       // log
       return@launch
   }
   moreWork()
}

return@async can also have an actual return value that is passed into it's Deferred<T> val.

val deferredValue = GlobalScope.async() { return@aysnc "hello world" }


问:
Why does modal render below table?
Currently, my modal renders below my table after I press submit on the form. I thought it was a CSS issue earlier but now I'm fairly certain it's an issue with the javascript logic. I feel it may have something to do with the re-rendering of the table? Here are the relevant files and screenshots for context.

Table:

```<code>import React, { Component } from 'react';
import Table from "react-bootstrap/Table";
import SampleQ from '../components/question.js';
import css from '../scss/style.scss';
import Layout from '../components/layout';
import NavigationBar from "../components/Navbar/index";

export default class extends Component {
    constructor(props) {
        super(props);

        this.state = {
            showBackground: false
        };

        this.showBackground = () => {
            this.setState({ showBackground: true });
        };

        this.hideBackground = () => {
            this.setState({ showBackground: false });
        }
    }

    static getInitialProps({query: {categories, questions, answers}}) {
        return {postCs: categories, allQs: questions, allAs: answers}
    }

    createTable = () => {
        let table = [];

        let cats = [];

        for (let i = 0; i < this.props.postCs.length; i++){
            cats.push(<th key = {i}>{this.props.postCs[i].title}</th>);
        }

        table.push(<thead> <tr> {cats} </tr> </thead>);

        let index = 0;
        // Outer loop to create parent
        for (let i = 1; i < 6; i++) {
            let children = [];

            //Inner loop to create children
            for (let j = 1; j < 7; j++) {
                children.push(
                    <td>
                        <div>
                            <SampleQ
                                amount={i}
                                question={this.props.allQs[(index)].title}
                                answer={this.props.allAs[(index)].title}
                                showBackdrop={this.showBackground}
                                hideBackdrop={this.hideBackground}
                            />
                        </div>
                    </td>);
                index++;
            }
            //Create the parent and add the children
            table.push(<tr>{children}</tr>)
        }

        return table
    };

    render() {
        let data = this.createTable();

        return (
            <div>
                <Layout showBackground={this.state.showBackground} title="lllll" />
                <Table striped bordered hover variant = "dark" className={css.table} hide={true}>
                    {data}
                </Table>
            </div>
        )
    }
}
</code>```

Question:

```<code>import React, { Component } from 'react';

import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
import UserInput from './userInput.js';
import Feedback from "./feedback/feedback";
import Backdrop from "./backdrop";
import styles from '../scss/backdrop.scss';
import Layout from '../components/layout';

class SampleQ extends Component {
    static getInitialProps({query: {amount, question, answer}}) {
        return {specAmt: amount, specQ: question, specA: answer}
    }

    constructor(props) {
        super(props);

        this.state = {
            showQuestion: false, // tracks visibility of first modal (the question modal)
            showFeedback: false, // tracks visibility of second modal (the feedback modal)
        };

        this.handleShow = () => {
            // show question and the backdrop when the user clicks a cell on the table
            this.setState({ showQuestion: true });
            this.props.showBackdrop();
        };

        this.handleHide = () => {
            this.setState({ showQuestion: false });
            this.props.hideBackdrop();
        };

        this.submitForm = event => {
            event.preventDefault();

            this.props.hideBackdrop(); // take down stars backdrop

            this.setState({
                showQuestion: false, // close question modal
                showFeedback: true, // should open Feedback modal
            });
        };

        this.closeFeedback = () => {
            // close Feedback modal and close backdrop so that it goes back to the table
            this.setState( { showFeedback: false });
            this.props.hideBackdrop();
        };
    }

    render() {
        return (
            <>
                <Button variant="outline-danger" size = "lg" onClick={this.handleShow}>
                    $ {this.props.amount}00
                </Button>

                <Modal
                    show={this.state.showQuestion}
                    onHide={this.handleHide}
                    dialogClassName="modal-90w"
                    aria-labelledby="example-custom-modal-styling-title"
                    backdrop={false}
                >
                    <Modal.Header closeButton>
                        <Modal.Title id="example-custom-modal-styling-title">
                            Question
                        </Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <p>
                            {this.props.question}
                        </p>
                        <div>
                            <UserInput
                                answer={this.props.specA}
                                handleClick={this.submitForm}
                            />
                        </div>
                    </Modal.Body>
                </Modal>
                <Feedback
                    showModal={this.state.showFeedback}
                    handleHide={this.closeFeedback}
                />
            </>
        );
    }
}

export default SampleQ;
</code>```

Feedback Modal (the one that renders below table)

```<code>import React, { Component } from 'react';

import Modal from 'react-bootstrap/Modal';
import { AiFillCheckCircle } from 'react-icons/ai';
import { IconContext } from 'react-icons';
import styles from '../../scss/modalStyle.scss';
import Button from 'react-bootstrap/Button';

class Feedback extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Modal
                show={this.props.showModal}
                onHide={this.props.handleHide}
                dialogClassName="modal-90w"
                aria-labelledby="example-custom-modal-styling-title"
                className={styles.modal}
            >
                <IconContext.Provider
                    value={{
                        color: '#fff',
                        size: '70px',
                        className: styles.modalConfirmIconBox,
                    }}
                >
                    <AiFillCheckCircle />
                </IconContext.Provider>

                <Modal.Body className={styles.modalBody}>
                    <h4 className={styles.h4}>Congratulations!</h4>
                    <p className={styles.p}>That was the correct answer.</p>
                    <Button
                        className={styles.button}
                        variant="success"
                        block
                        size="lg"
                        onClick={this.props.handleHide}
                    >
                        OK
                    </Button>
                </Modal.Body>
            </Modal>
        );
    }
}

export default Feedback;
</code>```

答: I fixed my issue. The problem was setting "position: relative" in scss file and I'm guessing the other adjustments to the modal's position put it under the table. </p>

Title: Why does modal render below table?

Body:
Currently, my modal renders below my table after I press submit on the form. I thought it was a CSS issue earlier but now I'm fairly certain it's an issue with the javascript logic. I feel it may have something to do with the re-rendering of the table? Here are the relevant files and screenshots for context.

Table:

import React, { Component } from 'react';
import Table from "react-bootstrap/Table";
import SampleQ from '../components/question.js';
import css from '../scss/style.scss';
import Layout from '../components/layout';
import NavigationBar from "../components/Navbar/index";

export default class extends Component {
    constructor(props) {
        super(props);

        this.state = {
            showBackground: false
        };

        this.showBackground = () => {
            this.setState({ showBackground: true });
        };

        this.hideBackground = () => {
            this.setState({ showBackground: false });
        }
    }

    static getInitialProps({query: {categories, questions, answers}}) {
        return {postCs: categories, allQs: questions, allAs: answers}
    }

    createTable = () => {
        let table = [];

        let cats = [];

        for (let i = 0; i < this.props.postCs.length; i++){
            cats.push({this.props.postCs[i].title}	);
        }

        table.push(

 {cats}

);

        let index = 0;
        // Outer loop to create parent
        for (let i = 1; i < 6; i++) {
            let children = [];

            //Inner loop to create children
            for (let j = 1; j < 7; j++) {
                children.push(

                            <SampleQ
                                amount={i}
                                question={this.props.allQs[(index)].title}
                                answer={this.props.allAs[(index)].title}
                                showBackdrop={this.showBackground}
                                hideBackdrop={this.hideBackground}
                            />

                    	);
                index++;
            }
            //Create the parent and add the children
            table.push(
{children}
)
        }

        return table
    };

    render() {
        let data = this.createTable();

        return (

                <Layout showBackground={this.state.showBackground} title="lllll" />

                    {data}

        )
    }
}

Question:

import React, { Component } from 'react';

import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
import UserInput from './userInput.js';
import Feedback from "./feedback/feedback";
import Backdrop from "./backdrop";
import styles from '../scss/backdrop.scss';
import Layout from '../components/layout';

class SampleQ extends Component {
    static getInitialProps({query: {amount, question, answer}}) {
        return {specAmt: amount, specQ: question, specA: answer}
    }

    constructor(props) {
        super(props);

        this.state = {
            showQuestion: false, // tracks visibility of first modal (the question modal)
            showFeedback: false, // tracks visibility of second modal (the feedback modal)
        };

        this.handleShow = () => {
            // show question and the backdrop when the user clicks a cell on the table
            this.setState({ showQuestion: true });
            this.props.showBackdrop();
        };

        this.handleHide = () => {
            this.setState({ showQuestion: false });
            this.props.hideBackdrop();
        };

        this.submitForm = event => {
            event.preventDefault();

            this.props.hideBackdrop(); // take down stars backdrop

            this.setState({
                showQuestion: false, // close question modal
                showFeedback: true, // should open Feedback modal
            });
        };

        this.closeFeedback = () => {
            // close Feedback modal and close backdrop so that it goes back to the table
            this.setState( { showFeedback: false });
            this.props.hideBackdrop();
        };
    }

    render() {
        return (
            <>
                <Button variant="outline-danger" size = "lg" onClick={this.handleShow}>
                    $ {this.props.amount}00
                </Button>

                <Modal
                    show={this.state.showQuestion}
                    onHide={this.handleHide}
                    dialogClassName="modal-90w"
                    aria-labelledby="example-custom-modal-styling-title"
                    backdrop={false}
                >
                    <Modal.Header closeButton>
                        <Modal.Title id="example-custom-modal-styling-title">
                            Question
                        </Modal.Title>
                    </Modal.Header>
                    <Modal.Body>

                            {this.props.question}

                            <UserInput
                                answer={this.props.specA}
                                handleClick={this.submitForm}
                            />

                    </Modal.Body>
                </Modal>
                <Feedback
                    showModal={this.state.showFeedback}
                    handleHide={this.closeFeedback}
                />
            </>
        );
    }
}

export default SampleQ;

Feedback Modal (the one that renders below table)

import React, { Component } from 'react';

import Modal from 'react-bootstrap/Modal';
import { AiFillCheckCircle } from 'react-icons/ai';
import { IconContext } from 'react-icons';
import styles from '../../scss/modalStyle.scss';
import Button from 'react-bootstrap/Button';

class Feedback extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Modal
                show={this.props.showModal}
                onHide={this.props.handleHide}
                dialogClassName="modal-90w"
                aria-labelledby="example-custom-modal-styling-title"
                className={styles.modal}
            >
                <IconContext.Provider
                    value={{
                        color: '#fff',
                        size: '70px',
                        className: styles.modalConfirmIconBox,
                    }}
                >
                    <AiFillCheckCircle />
                </IconContext.Provider>

                <Modal.Body className={styles.modalBody}>

Congratulations!

That was the correct answer.

                    <Button
                        className={styles.button}
                        variant="success"
                        block
                        size="lg"
                        onClick={this.props.handleHide}
                    >
                        OK
                    </Button>
                </Modal.Body>
            </Modal>
        );
    }
}

export default Feedback;


问:
java - performing file operations on remote locations
hi
i want to perform operations on files like rename, copy and etc.
these are not local files. they are located on remote computers.

I have 2 options:
1. run some kind of a telnet client (a framework that i already have in my system) from the java code. connect to the remote computer and perform a cmd operation.
2. perform a regular java.io operation on the remote path.

the problem with 1 is that its not cross platform (only theoretical problem for me), and that i generally dont want to use this telnet framework.
the problem with 2 is that large operations on remote files is slower, compared to same operation being performed on the machine itself with telnet.

am i right?
any other options?
any additional inputs?

thanks.

答: If you can deploy your application to the remote computer, you can simply write your own little client and server for these file operations.</p>

ContentLicense: CC BY-SA 3.0


问:
hotkey/button to compile as necessary but NOT run (between F5, and Ctrl+Shift+B)
In Visual Studio C++ :-

F5 = compile as necessary + run

Ctrl+Shift+B = build all open (loaded) projects , but not run

Example

If I have projects :-

A1,A2,A3 and A4 : static library

B : depend on A1,A2,A3 and A4  (set as StartUp project)

C : depend on A1,A2,A3 and A4

Hotkey will do:-

F5 = will build all A & B, then run B

Ctrl+Shift+B = build all A & B & C, but not run

Question

What is the hotkey/button for : compile as necessary (A&B only), but not run ?

... or how to set Ctrl+Shift+B to do as mentioned?

Sorry, it is probably something very obvious.  I have searched it for a few years.

答: From the Build option in the top panel go to Configuration Manager (Build > Configuration Manager), check build checkboxes for project A & B only and uncheck unwanted projects (here it is C for your case). That might help your issue.</p>


问:
cant make local database because Error: FIle/etc/my.cnf doesnt exist
i want to make local database on workbench and when i configure local management it was said

```<code>Check if /etc/my.cnf can be accessed
Operation failed: File /etc/my.cnf doesn't exist
</code>```

so i've used this option on my terminal

```<code>sudo cp my-huge.cnf /etc/my.cn
</code>```

and it was said

```<code>cp: cannot stat 'my-huge.cnf': No such file or directory
</code>```

when i check my support-files, it was not any single of my.cnf files, so i just confused why my mysql dont have any my.cnf files.

答:
mysql doesn't include .cnf files because the default configuration is reasonably sane.

When my-huge.cnf existed it was written in the year ~2000 and its huge definition didn't change ever. (~4 cpus and ~1G ram - ha, there was even a huge-4G.cnf file for when "huge" wasn't enough)

If something is requiring /etc/my.cnf to exist, create it as an empty file (e.g. touch /etc/my.cnf).

Body:
i want to make local database on workbench and when i configure local management it was said

Check if /etc/my.cnf can be accessed
Operation failed: File /etc/my.cnf doesn't exist

so i've used this option on my terminal

sudo cp my-huge.cnf /etc/my.cn

and it was said

cp: cannot stat 'my-huge.cnf': No such file or directory

when i check my support-files, it was not any single of my.cnf files, so i just confused why my mysql dont have any my.cnf files.


问:
Could not find com.android.support:appcompat-v7:23.4.0
here is my code:
help me please</p>

```<code>dependencies {

    compile fileTree(dir: 'libs', include: ['.jar'])`enter code here`
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.4.0'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
// Migrate Your Project To AndroidX After Completing Your Dependencies Look Like This </p>

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.package.name"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code>```

Body:
here is my code:
help me please

dependencies {

    compile fileTree(dir: 'libs', include: ['.jar'])`enter code here`
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.4.0'
    testCompile 'junit:junit:4.12'
}

Body:
// Migrate Your Project To AndroidX After Completing Your Dependencies Look Like This

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.package.name"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}


问:
How Does GetStringType Cause a Deadlock in Dll Main?
I'm looking at an application which hangs on Server 2016 but runs find on Server 2008 R2. I have traced it to a hang caused by deadlock when a particular DLL loads. Analysing the DLL (I don't have the source code) I can see that it violates the guideline here

Call GetStringTypeA, GetStringTypeEx, or GetStringTypeW (either
directly or indirectly). This can cause a deadlock or a crash

Specifically it calls GetStringTypeW from DllMain.

I'm trying to understand how this function can cause deadlocks in DllMain.

答:
Your DllMain function runs inside the loader lock, one of the few
  times the OS lets you run code while one of its internal locks is
  held. This means that you must be extra careful not to violate a lock
  hierarchy in your DllMain; otherwise, you are asking for a deadlock. (Refer to "Another reason not to do anything scary in your DllMain: Inadvertent deadlock")

DllMain is called while the loader-lock is held, so if GetStringType acquires the loader lock, deadlock appears.

Significant restrictions are imposed on the functions that can be
  called within DllMain. As such, DllMain is designed to perform minimal
  initialization tasks, by using a small subset of the Microsoft®
  Windows® API. You cannot call any function in DllMain that directly or
  indirectly tries to acquire the loader lock. Otherwise, you will
  introduce the possibility that your application deadlocks or crashes.

We can't see source code of GetStringType function. It is suggested to follow Dynamic-Link Library Best Practices.


问:
Is it possible to use external IFC exporter in DA4R?
I need to use IFC for Revit library SourceForge link.
Can i override the version that is built in?
 I mean using Document.Export(path,IFCExportOptions).

How can i use it in DA4R app ?

答:
That's an interesting question, can I know why do you want to override the built in version? is there any limitation? Maybe that is also a good request for us to improve or fix in Revit. And Revit Design Automation engine currently supports Revit 2018.3, 2019.2 and 2020.2, are they all not working for you?

Revit Design Automation includes the support for IFC last April at https://forge.autodesk.com/en/docs/design-automation/v3/change_history/revit_release_notes/, I am not an IFC expert but I don't think there is a way for developer to specify the version in DA4R. But to override the current behavior to export IFC, in theory, you can achieve that within your Revit plugin on DA4R, but you need to customize all the export to IFC functionality within your Revit AppBundle(make sure no namespace conflict with current Ifc export library), you may also need to package all the dependent DLLs within the package to make it work, then upload as AppBundle, define an activity then post a workitem.

Please also notice that the limitation of Revit AppBundle size is 100M by default at https://forge.autodesk.com/en/docs/design-automation/v3/developers_guide/quotas/, you may need to override the size by checking https://forge.autodesk.com/en/docs/design-automation/v3/reference/http/servicelimits-owner-PUT/


问:
Get variables datatypes in kernel mode drivers windows
I want to know if there is any method in kernel mode drivers which gives the datatype of a variable. Like if I declare:

```<code>INT i = 0;
</code>```

And ask about datatype of "i", it will return INT. I also want the same thing for structures.

答: That's impossible. The kernel is effectively assembly. If you get a PVOID, that's either a 32 or 64 bits address, and you don't even know the size of the object that it points to.

Body:
I want to know if there is any method in kernel mode drivers which gives the datatype of a variable. Like if I declare:

INT i = 0;

And ask about datatype of "i", it will return INT. I also want the same thing for structures.


问:
How to make "Paste from Word" in FCKeditor by default?
I need this while copying text from MS word to FCKeditor. The pop up "Paste from Word" should not show up.

Instead I need to internally call the "Paste from Word" function so that the user does not see this pop up.

Basically I need the functionality which is offered by "Paste from Word" but not the popup. And this should be done every time someone  paste text into FCKeditor.

Can we do this?

Help please. This is urgent and I have already spent hours trying to figure out this. :(

EDIT:

Let me rephrase my question now. I think it will be better I can have FCKConfig.ForcePasteAsPlainText = true; as said by Bariz.

But I could not see this anywhere in the fckeditor configuration file.

Any ideas? The version of fckeditor is 2.6.5

答:
Do not know how to set "Paste from Word" by default but maybe You could try pasting as plain text? "Paste from Word" cleans the input but often leaves rubbish in text. You can force pasting as plain text by adding this line to fckconfig.js:</p>

```<code>FCKConfig.ForcePasteAsPlainText = true;
</code>```

Body:
Do not know how to set "Paste from Word" by default but maybe You could try pasting as plain text? "Paste from Word" cleans the input but often leaves rubbish in text. You can force pasting as plain text by adding this line to fckconfig.js:

FCKConfig.ForcePasteAsPlainText = true;


问:
How to store structs (not instance) that implement a common trait?

Background

I have a trait MyTrait:

trait MyTrait {
    fn name() -> String;

    fn foo();
}
```

<p><code>name</code> defines its name, and <code>foo</code> is its associated function, which does some work for me.</p>

<h1>Target</h1>

<p>I have many structs that implements this trait, and I want to define a function</p>

<pre class="lang-rust prettyprint-override"><code>fn do_work(name: &String);
</code>```

which finds the struct TheStruct where TheStruct::name() is name, and call TheStruct::foo().

Problem

To achieve my goal, I need a HashMap or use match, but the target value should be a struct (not instance) implements MyTrait, but this seems impossible.

Workaround

Change name() and foo() to struct methods, i.e. name(&self) and foo(&self), then use HashMap or just match to get the things right. But I think since name() and foo() does not need an instance by design, why should I need to instantiate it?

答:
If you're mapping a name to an action, it would make the most sense to use a HashMap<String, fn()> most likely. For example:

```<code>use std::collections::{HashMap, hash_map::Entry};

trait MyTrait {
    fn name() -> String;

    fn foo();
}

struct Example;
impl MyTrait for Example {
    fn name() -> String {
        "Example".to_string()
    }
    fn foo() {
        println!("Do Example");
    }
}

#[derive(Default)]
struct Worker {
    handlers: HashMap<String, fn()>,
}
impl Worker {
    fn new() -> Self {
        Default::default()
    }
    fn register_handler<T: MyTrait>(&mut self) {
        let name = T::name();
        match self.handlers.entry(name) {
            Entry::Occupied(_) => panic!("handler already registered"),
            entry => {entry.or_insert(T::foo);},
        }
    }
    fn do_work(&self, name: &str) {
        let handler = self.handlers.get(name).expect("unknown handler");
        handler();
    }
}

fn main() {
    let mut worker = Worker::new();
    worker.register_handler::<Example>();

    worker.do_work("Example");
}
</code>```

(Playground Link)

Body:
Background

I have a trait MyTrait:

trait MyTrait {
    fn name() -> String;

    fn foo();
}

name defines its name, and foo is its associated function, which does some work for me.

Target

I have many structs that implements this trait, and I want to define a function

fn do_work(name: &String);

which finds the struct TheStruct where TheStruct::name() is name, and call TheStruct::foo().

Problem

To achieve my goal, I need a HashMap or use match, but the target value should be a struct (not instance) implements MyTrait, but this seems impossible.

Workaround

Change name() and foo() to struct methods, i.e. name(&self) and foo(&self), then use HashMap or just match to get the things right. But I think since name() and foo() does not need an instance by design, why should I need to instantiate it?

Body:
If you're mapping a name to an action, it would make the most sense to use a HashMap<String, fn()> most likely. For example:

use std::collections::{HashMap, hash_map::Entry};

trait MyTrait {
    fn name() -> String;

    fn foo();
}

struct Example;
impl MyTrait for Example {
    fn name() -> String {
        "Example".to_string()
    }
    fn foo() {
        println!("Do Example");
    }
}

#[derive(Default)]
struct Worker {
    handlers: HashMap<String, fn()>,
}
impl Worker {
    fn new() -> Self {
        Default::default()
    }
    fn register_handler<T: MyTrait>(&mut self) {
        let name = T::name();
        match self.handlers.entry(name) {
            Entry::Occupied(_) => panic!("handler already registered"),
            entry => {entry.or_insert(T::foo);},
        }
    }
    fn do_work(&self, name: &str) {
        let handler = self.handlers.get(name).expect("unknown handler");
        handler();
    }
}

fn main() {
    let mut worker = Worker::new();
    worker.register_handler::<Example>();

    worker.do_work("Example");
}

(Playground Link)


问:
How can I query a NCLOB column as a table in SAP HANA?
I like to do a select query with a where condition on a column of type NCLOB let's call it information column. It has following format:

{
   "firstName" : "name1",
   "lastName" : "lastName1"
}

I want to do some thing like this

Select * from myTable where information.firsName = "targetName"

But I am not sure how to do it.

Any hints please?

答:
Looks like you want a structured database instead of a JSON clob... :)

Why don't you have a look at the JSON functions in HANA?

With JSON_TABLE you can construct a table structure "over" the JSON-data in the clob-column and then query that table structure.


问:
Using NetBeans and Command Line Arguments
I am new to java and I know this isn't for homework but I need help. I've typed a program in java and I need to have the values passed in the command line arguments and that is where I am getting stuck I quite understand how to do that. Here is the question that I needed to answer.

(Write an application that uses an enhanced for a statement to sum the double values passed by the command-line arguments. [Hint: Use the static method parseDouble of class Double to convert a String to a double value .])

here is my code

```<code>public class Enhanced {

   public static void main(String[] args) {

   Double total = 0.0;
   for (String number : args) {

   total += Double.parseDouble(number);
   }
   //print total
   System.out.printf("Total of array elements: %f%n", total);
   }
}
</code>```

答:
Here's how to specify command-line arguments when running your app under NetBeans:

Under your Projects tab, right-click on your project and choose Properties

In the Project Properties dialog, under Categories, select Run;

Enter your command-line arguments in the Arguments field;

Click OK;

The arguments you entered will be used every time you run the project after that.

Body:
I am new to java and I know this isn't for homework but I need help. I've typed a program in java and I need to have the values passed in the command line arguments and that is where I am getting stuck I quite understand how to do that. Here is the question that I needed to answer.

(Write an application that uses an enhanced for a statement to sum the double values passed by the command-line arguments. [Hint: Use the static method parseDouble of class Double to convert a String to a double value .])

here is my code

public class Enhanced {

   public static void main(String[] args) {

   Double total = 0.0;
   for (String number : args) {

   total += Double.parseDouble(number);
   }
   //print total
   System.out.printf("Total of array elements: %f%n", total);
   }
}


问:
Arrange data in bracket based on specific order in Python
I have an array and after programming, I get the position and the value of non-zero data, which looks like (x, y, z) = (row, column, value)

```<code>[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]
</code>```

This result in order in 'the smallest number of row to the highest'.

Is there any method that I can make the result order in 'the smallest number of column to the highest' and also 'the smallest number of value to the highest'?

Thanks for any help!!

This is the code I used:

```<code>import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
print(list(zip(*res)))
</code>```

答:
You can use the key argument in the builtin sorted() function to change the key to the ith index:

```<code>array = [(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]

ascending_column_order = sorted(array, key=lambda x: x[1])
</code>```

Body:
I have an array and after programming, I get the position and the value of non-zero data, which looks like (x, y, z) = (row, column, value)

[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]

This result in order in 'the smallest number of row to the highest'.

Is there any method that I can make the result order in 'the smallest number of column to the highest' and also 'the smallest number of value to the highest'?

Thanks for any help!!

This is the code I used:

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
print(list(zip(*res)))

Body:
You can use the key argument in the builtin sorted() function to change the key to the ith index:

array = [(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]

ascending_column_order = sorted(array, key=lambda x: x[1])


问:
Why do tuples not get changed whereas lists do?
Why does only the first tuple change in example II whereas both lists get changed in example I? Please consider these two programs and their respective output (I and II).

I.

```<code>L1 = [1,2,3,4]
L2 = L1
L2.append(5)
print("L1: ", L1)
print("L2: ", L2)
</code>```

Output:

```<code>L1: [1,2,3,4,5]
L2: [1,2,3,4,5]
</code>```

II.

```<code>L1=(1,2,3,4)
L2=L1
L2 += (5,)
print("L1: ", L1)
print("L2: ", L2)
</code>```

Output:

```<code>L1: (1,2,3,4)
L2: (1,2,3,4,5)
</code>```

OwnerDisplayName: anon

Body:
Why does only the first tuple change in example II whereas both lists get changed in example I? Please consider these two programs and their respective output (I and II).

I.

L1 = [1,2,3,4]
L2 = L1
L2.append(5)
print("L1: ", L1)
print("L2: ", L2)

Output:

L1: [1,2,3,4,5]
L2: [1,2,3,4,5]

II.

L1=(1,2,3,4)
L2=L1
L2 += (5,)
print("L1: ", L1)
print("L2: ", L2)

Output:

L1: (1,2,3,4)
L2: (1,2,3,4,5)

Body:
In List when you use this '=' assignment operator, it does not creates new reference, it refers same object.

In Tuple when you use this '=' assignment operator, it creates new reference.

Refer below code, check the output of ID.

L1 = [1,2,3,4]
L2 = L1
L2.append(5)
print("L1: ", L1)
print("L2: ", L2)
print("ID of L1: ", id(L1))
print("ID of L2: ", id(L2))
# Output =
# L1:  [1, 2, 3, 4, 5]
# L2:  [1, 2, 3, 4, 5]
# ID of L1:  2598160167616
# ID of L2:  2598160167616
# -------------------------------------------
L1=(1,2,3,4)
L2=L1
L2 += (5,)
print("L1: ", L1)
print("L2: ", L2)
print("ID of L1: ", id(L1))
print("ID of L2: ", id(L2))
# Output =
# L1:  (1, 2, 3, 4)
# L2:  (1, 2, 3, 4, 5)
# ID of L1:  2598161745696
# ID of L2:  2598161718864
# -------------------------------------------


问:
Getting at C binary data from OCaml
(Ignoring endianness for the sake of argument - this is just a test case/proof of concept - and I would never use strcpy in real code either!)

Consider the following trivial C code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* variables of type message_t will be stored contiguously in memory */
typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));
  m->message_id = 1;
  strcpy(m->message_text,"the rain in spain falls mainly on the plain");

  /* write the memory to disk */
  FILE* fp = fopen("data.dat", "wb");
  fwrite((void*)m, sizeof(int) + strlen(m->message_text) + 1, 1, fp);
  fclose(fp);

  exit(EXIT_SUCCESS);
}
</code>```

The file it writes can easily be read back in from disk:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));

  FILE* fp = fopen("data.dat", "rb");
  fread((void*)m, sizeof(message_t), 1, fp);
  fclose(fp);

  /* block of memory has structure "overlaid" onto it */
  printf("message_id=%d, message_text='%s'\n", m->message_id, m->message_text);

  exit(EXIT_SUCCESS);
}
</code>```

E.g.

```<code>$ ./write
$ ./read
message_id=1, message_text='the rain in spain falls mainly on the plain'
</code>```

My question is, in OCaml, if all I have is:

```<code>type message_t = {message_id:int; message_text:string}
</code>```

How would I get at that data? Marshal can't do it, nor can input_binary_int. I can call out to helper functions in C like "what is sizeof(int)" then get n bytes and call a C function to "convert these bytes into an int" for example but in this case I can't add any new C code, the "unpacking" has to be done in OCaml, based on what I know it "should" be. Is it just a matter of iterating over the string either in blocks of sizeofs or looking for '\0' or is there a clever way? Thanks!

答:
You are relying on using the same C compiler on the same platform to avoid having to think about what the format of the written and read back data is. Unfortunately you don't have that luxury if you are trying to interoperate between C and OCaml. You have to count the bytes in the structure, figure out if the integer is little- or big-endian, and code accordingly on the OCaml side.

You'll have to manually unmarshall each type separately, in effect parsing the binary file. For instance, to read a little-endian 32-bit integer you'd have to use:

```<code>let input_le_int32 inch =
  let res = ref 0l in
  for i = 0 to 3 do
    let byte = input_byte inch in
    res := Int32.logor !res (Int32.shift_left (Int32.of_int byte) (8*i))
  done;
  !res
</code>```

and to read a NUL-terminated string:

```<code>let input_c_string inch =
  let res = Buffer.create 256 in
  try while true do
    let byte = input_byte inch in
    if byte = 0 then raise Exit else
    Buffer.add_char res (char_of_int byte)
  done; assert false with Exit ->
  Buffer.contents res
</code>```

If everything is right you can read back your structure with:

```<code>let input_message inch =
  let message_id   = input_le_int32 inch in
  let message_text = input_c_string inch in
  { message_id; message_text; }
</code>```

Note: it is imperative (!) to sequence the reads to avoid reading fields out-of-order. Do not use parallel let assignments.

Title: Getting at C binary data from OCaml

Body:
(Ignoring endianness for the sake of argument - this is just a test case/proof of concept - and I would never use strcpy in real code either!)

Consider the following trivial C code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* variables of type message_t will be stored contiguously in memory */
typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));
  m->message_id = 1;
  strcpy(m->message_text,"the rain in spain falls mainly on the plain");

  /* write the memory to disk */
  FILE* fp = fopen("data.dat", "wb");
  fwrite((void*)m, sizeof(int) + strlen(m->message_text) + 1, 1, fp);
  fclose(fp);

  exit(EXIT_SUCCESS);
}

The file it writes can easily be read back in from disk:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));

  FILE* fp = fopen("data.dat", "rb");
  fread((void*)m, sizeof(message_t), 1, fp);
  fclose(fp);

  /* block of memory has structure "overlaid" onto it */
  printf("message_id=%d, message_text='%s'\n", m->message_id, m->message_text);

  exit(EXIT_SUCCESS);
}

E.g.

$ ./write
$ ./read
message_id=1, message_text='the rain in spain falls mainly on the plain'

My question is, in OCaml, if all I have is:

type message_t = {message_id:int; message_text:string}

How would I get at that data? Marshal can't do it, nor can input_binary_int. I can call out to helper functions in C like "what is sizeof(int)" then get n bytes and call a C function to "convert these bytes into an int" for example but in this case I can't add any new C code, the "unpacking" has to be done in OCaml, based on what I know it "should" be. Is it just a matter of iterating over the string either in blocks of sizeofs or looking for '\0' or is there a clever way? Thanks!

Body:
You are relying on using the same C compiler on the same platform to avoid having to think about what the format of the written and read back data is. Unfortunately you don't have that luxury if you are trying to interoperate between C and OCaml. You have to count the bytes in the structure, figure out if the integer is little- or big-endian, and code accordingly on the OCaml side.

You'll have to manually unmarshall each type separately, in effect parsing the binary file. For instance, to read a little-endian 32-bit integer you'd have to use:

let input_le_int32 inch =
  let res = ref 0l in
  for i = 0 to 3 do
    let byte = input_byte inch in
    res := Int32.logor !res (Int32.shift_left (Int32.of_int byte) (8*i))
  done;
  !res

and to read a NUL-terminated string:

let input_c_string inch =
  let res = Buffer.create 256 in
  try while true do
    let byte = input_byte inch in
    if byte = 0 then raise Exit else
    Buffer.add_char res (char_of_int byte)
  done; assert false with Exit ->
  Buffer.contents res

If everything is right you can read back your structure with:

let input_message inch =
  let message_id   = input_le_int32 inch in
  let message_text = input_c_string inch in
  { message_id; message_text; }

Note: it is imperative (!) to sequence the reads to avoid reading fields out-of-order. Do not use parallel let assignments.


问:
How to make multiple queries in one promise
I'm using React to send data over to my PotgreSQL database using NodeJS. Data is getting inserted fine on the first INSERT as well as the second INSERT but my only problem is that on the .then after the second INSERT it doesn't give me the response?

```<code>const addData = (request, response) => {
const uuid = uuidv4();

db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      console.log('INSERT ' + JSON.stringify(res.rows[0]));
    }).then(() => {
       for (let i = 0; i < request.body.files.length; i++) {
        db.pool.query('INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index])
        }}).then(res => {
      console.log('INSERT INTO songs ' + JSON.stringify(res));
    }).catch(error => console.log(error));

}
</code>```

What am I doing wrong to not get the response for the second INSERT?

答:
Tl;DR

This should get your code to work:

const addData = (request, response) => {
  const uuid = uuidv4();
  db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *', [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      console.log('INSERT ' + JSON.stringify(res.rows[0]));
    }).then(() => {
      const dbQueryPromises = [];
      for (let i = 0; i < request.body.files.length; i++) {
        dbQueryPromises.push(db.pool.query(
          'INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *',
          [uuidv4(),
          request.body.files[i].name,
          request.body.files[i].link,
          request.body.files[i].index]));
      }
      return Promise.all(dbQueryPromises);
    }).then(res => {
      console.log('Array of INSERT result for second insert: ', res);
    }).catch(error => console.log(error));
}
```
<h3>Longer explantion:</h3>
<p>You did not get a response on the second <code>insert</code> is because you did not return any <code>Promise</code> back to the output. The first <code>then</code> works because what <code>db.pool.query</code> does is returning a <code>Promise.resolve(res)</code> of your function call. However, your second insert does not return any thing.</p>
<p>Take a look at this part of your code:</p>
<pre class="lang-js prettyprint-override"><code>() => {
      for (let i = 0; i < request.body.files.length; i++) {
        db.pool.query('INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index])
      }
    }
</code>```

-> This is an arrow function, and in javascript if you do not return anything, if you just gave out null.

Aside from that, you are actually creating multiple promises at once, I would suggest for you to use `Promise.all) if you want wait for all the promise to work.

Body:
I'm using React to send data over to my PotgreSQL database using NodeJS. Data is getting inserted fine on the first INSERT as well as the second INSERT but my only problem is that on the .then after the second INSERT it doesn't give me the response?

const addData = (request, response) => {
const uuid = uuidv4();

db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      console.log('INSERT ' + JSON.stringify(res.rows[0]));
    }).then(() => {
       for (let i = 0; i < request.body.files.length; i++) {
        db.pool.query('INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index])
        }}).then(res => {
      console.log('INSERT INTO songs ' + JSON.stringify(res));
    }).catch(error => console.log(error));

}

What am I doing wrong to not get the response for the second INSERT?

Body:
Tl;DR

This should get your code to work:

const addData = (request, response) => {
  const uuid = uuidv4();
  db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *', [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      console.log('INSERT ' + JSON.stringify(res.rows[0]));
    }).then(() => {
      const dbQueryPromises = [];
      for (let i = 0; i < request.body.files.length; i++) {
        dbQueryPromises.push(db.pool.query(
          'INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *',
          [uuidv4(),
          request.body.files[i].name,
          request.body.files[i].link,
          request.body.files[i].index]));
      }
      return Promise.all(dbQueryPromises);
    }).then(res => {
      console.log('Array of INSERT result for second insert: ', res);
    }).catch(error => console.log(error));
}

Longer explantion:

You did not get a response on the second insert is because you did not return any Promise back to the output. The first then works because what db.pool.query does is returning a Promise.resolve(res) of your function call. However, your second insert does not return any thing.

Take a look at this part of your code:

() => {
      for (let i = 0; i < request.body.files.length; i++) {
        db.pool.query('INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index])
      }
    }

-> This is an arrow function, and in javascript if you do not return anything, if you just gave out null.

Aside from that, you are actually creating multiple promises at once, I would suggest for you to use `Promise.all) if you want wait for all the promise to work.


问:
Codeigniter & Ajax - Console.log data returns CI's landing page in HTML
I want to console.log the result of my query using ajax, but it outputs the CI Landing page in the HTML Code.

JS:

```<code> function getRouters(data)
  {
    $.ajax({
      type: 'POST',
      url: "http://localhost/ldcm/Main_controller/getRouters",
      data: data,
      success: function (data) {
        console.log(data);
      }
    });
  }

$('#generateRes').click(function () {
   var data = userDetailsObj.data.homesize.id + userDetailsObj.data.floors.id + userDetailsObj.data.internetPlan.id + userDetailsObj.data.devices.id;
   console.log(data);
   if(data) {
      getRouters(data);
   } else{

   }
});
</code>```

Controller:

```<code>public function getRouters(){
                $data = $_POST['data'];
                $this->load->model('Query_Model');
                $data = $this->Query_Model->getRouters($data);

                echo json_encode($data);
        }
</code>```

Model:

```<code>public function getRouters($data)
        {
            $this->db->select('*');
            $this->db->where('id', $data);
            $q = $this->db->get('selection');
            $response = $q->result_array();
            return $response;
        }
</code>```

Is it supposed to print that way? Or did i miss a configuration part in config?

答:
Try this code.

function getRouters(data)
  {
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: "http://localhost/ldcm/Main_controller/getRouters",
      data: data,
      success: function (data) {
        console.log(data);
      }
    });
  }

Body:
I want to console.log the result of my query using ajax, but it outputs the CI Landing page in the HTML Code.

JS:

 function getRouters(data)
  {
    $.ajax({
      type: 'POST',
      url: "http://localhost/ldcm/Main_controller/getRouters",
      data: data,
      success: function (data) {
        console.log(data);
      }
    });
  }

$('#generateRes').click(function () {
   var data = userDetailsObj.data.homesize.id + userDetailsObj.data.floors.id + userDetailsObj.data.internetPlan.id + userDetailsObj.data.devices.id;
   console.log(data);
   if(data) {
      getRouters(data);
   } else{

   }
});

Controller:

public function getRouters(){
                $data = $_POST['data'];
                $this->load->model('Query_Model');
                $data = $this->Query_Model->getRouters($data);

                echo json_encode($data);
        }

Model:

public function getRouters($data)
        {
            $this->db->select('*');
            $this->db->where('id', $data);
            $q = $this->db->get('selection');
            $response = $q->result_array();
            return $response;
        }

Is it supposed to print that way? Or did i miss a configuration part in config?


问:
Error: Can't set headers after they are sent to the client
I'm fairly new to Node.js and I am having some issues.

I am using Node.js 4.10 and Express 2.4.3.

When I try to access http://127.0.0.1:8888/auth/facebook, i'll be redirected to http://127.0.0.1:8888/auth/facebook_callback.

I then received the following error:

```<code>Error: Can't render headers after they are sent to the client.
    at ServerResponse.<anonymous> (http.js:573:11)
    at ServerResponse._renderHeaders (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:64:25)
    at ServerResponse.writeHead (http.js:813:20)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:28:15
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:113:13
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/strategyExecutor.js:45:39)
    at [object Object].pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:32:3)
    at [object Object].halt (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:29:8)
    at [object Object].redirect (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:16:8)
    at [object Object].<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:77:15)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:195:11)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
    at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
    at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
    at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
    at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
    at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
    at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9
    at Array.<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session/memory.js:57:7)
    at EventEmitter._tickCallback (node.js:126:26)
</code>```

The following is my code:

```<code>var fbId= "XXX";
var fbSecret= "XXXXXX";
var fbCallbackAddress= "http://127.0.0.1:8888/auth/facebook_callback"

var cookieSecret = "node";     // enter a random hash for security

var express= require('express');
var auth = require('connect-auth')
var app = express.createServer();

app.configure(function(){
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.session({secret: cookieSecret}));
    app.use(auth([
        auth.Facebook({
            appId : fbId,
            appSecret: fbSecret,
            callback: fbCallbackAddress,
            scope: 'offline_access,email,user_about_me,user_activities,manage_pages,publish_stream',
            failedUri: '/noauth'
        })
    ]));
    app.use(app.router);
});

app.get('/auth/facebook', function(req, res) {
  req.authenticate("facebook", function(error, authenticated) {
    if (authenticated) {
      res.redirect("/great");
      console.log("ok cool.");
      console.log(res['req']['session']);
    }
  });
});

app.get('/noauth', function(req, res) {
  console.log('Authentication Failed');
  res.send('Authentication Failed');
});

app.get('/great', function( req, res) {
  res.send('Supercoolstuff');
});

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

May I know what is wrong with my code?

答: In my case, In a loop, I put res.render() so might have been tried to call multiple times.

Body:
I'm fairly new to Node.js and I am having some issues.

I am using Node.js 4.10 and Express 2.4.3.

When I try to access http://127.0.0.1:8888/auth/facebook, i'll be redirected to http://127.0.0.1:8888/auth/facebook_callback.

I then received the following error:

Error: Can't render headers after they are sent to the client.
    at ServerResponse.<anonymous> (http.js:573:11)
    at ServerResponse._renderHeaders (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:64:25)
    at ServerResponse.writeHead (http.js:813:20)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:28:15
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:113:13
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/strategyExecutor.js:45:39)
    at [object Object].pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:32:3)
    at [object Object].halt (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:29:8)
    at [object Object].redirect (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:16:8)
    at [object Object].<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:77:15)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:195:11)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
    at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
    at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
    at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
    at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
    at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
    at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: Can't set headers after they are sent.
    at ServerResponse.<anonymous> (http.js:527:11)
    at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
    at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
    at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9
    at Array.<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session/memory.js:57:7)
    at EventEmitter._tickCallback (node.js:126:26)

The following is my code:

var fbId= "XXX";
var fbSecret= "XXXXXX";
var fbCallbackAddress= "http://127.0.0.1:8888/auth/facebook_callback"

var cookieSecret = "node";     // enter a random hash for security

var express= require('express');
var auth = require('connect-auth')
var app = express.createServer();

app.configure(function(){
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.session({secret: cookieSecret}));
    app.use(auth([
        auth.Facebook({
            appId : fbId,
            appSecret: fbSecret,
            callback: fbCallbackAddress,
            scope: 'offline_access,email,user_about_me,user_activities,manage_pages,publish_stream',
            failedUri: '/noauth'
        })
    ]));
    app.use(app.router);
});

app.get('/auth/facebook', function(req, res) {
  req.authenticate("facebook", function(error, authenticated) {
    if (authenticated) {
      res.redirect("/great");
      console.log("ok cool.");
      console.log(res['req']['session']);
    }
  });
});

app.get('/noauth', function(req, res) {
  console.log('Authentication Failed');
  res.send('Authentication Failed');
});

app.get('/great', function( req, res) {
  res.send('Supercoolstuff');
});

app.listen(8888);

May I know what is wrong with my code?


问:
Loading indicator around stacklayout
I am trying to create a loading indicator/spinning animation around a StackLayout, as you can see in the image below, the indicator color must change according to the direction, the indicator is going around the lane, wherever the indicator goes the line seems to fade. Its like a spinning animation around the layout.

I have tried to create a custom stack layout and add some border animation but with no success.

答:
You could use custom renderer to set the gradient border of frame instead of stacklayout.

MyFrame.cs

```<code>public class MyFrame:Frame
{
}
</code>```

MyFrameRenderer.cs

```<code> [assembly: ExportRenderer(typeof(MyFrame), typeof(MyFrameRenderer))]
namespace GradientBorder.Droid
{
 public class MyFrameRenderer : VisualElementRenderer<Frame>
   {
    public MyFrameRenderer(Context context) : base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
    {
        base.OnElementChanged(e);

        SetBackgroundResource(Resource.Drawable.Gradient);
    }
  }
}
</code>```

Gradient.xml in Android Resource Drawable

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
  <gradient

      android:angle="360"
      android:centerColor="#edecbb"
      android:endColor="#e6e217"
      android:gradientRadius="360"
      android:startColor="#edeb72"
      android:type="sweep" />
  <corners android:radius="10dp" />
  <!--<stroke
      android:width="2dp"
      android:color="#ff207d94" />-->
</shape>
</item>
<item
   android:bottom="5dp"
  android:left="5dp"
  android:right="5dp"
  android:top="5dp">
<shape android:shape="rectangle" >
  <solid android:color="#fff" />
</shape>
</item>

</layer-list>
</code>```

MainPage.xml

```<code>  <StackLayout Padding="50" BackgroundColor="Gray">
    <local:MyFrame>
        <StackLayout>
            <Button />
            <Label Text="Hello" />
        </StackLayout>
    </local:MyFrame>
</StackLayout>
</code>```

Title: Loading indicator around stacklayout

Body:
You could use custom renderer to set the gradient border of frame instead of stacklayout.

MyFrame.cs

public class MyFrame:Frame
{
}

MyFrameRenderer.cs

 [assembly: ExportRenderer(typeof(MyFrame), typeof(MyFrameRenderer))]
namespace GradientBorder.Droid
{
 public class MyFrameRenderer : VisualElementRenderer<Frame>
   {
    public MyFrameRenderer(Context context) : base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
    {
        base.OnElementChanged(e);

        SetBackgroundResource(Resource.Drawable.Gradient);
    }
  }
}

Gradient.xml in Android Resource Drawable

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
  <gradient

      android:angle="360"
      android:centerColor="#edecbb"
      android:endColor="#e6e217"
      android:gradientRadius="360"
      android:startColor="#edeb72"
      android:type="sweep" />
  <corners android:radius="10dp" />
  <!--<stroke
      android:width="2dp"
      android:color="#ff207d94" />-->
</shape>
</item>
<item
   android:bottom="5dp"
  android:left="5dp"
  android:right="5dp"
  android:top="5dp">
<shape android:shape="rectangle" >
  <solid android:color="#fff" />
</shape>
</item>

</layer-list>

MainPage.xml

  <StackLayout Padding="50" BackgroundColor="Gray">
    <local:MyFrame>
        <StackLayout>
            <Button />
            <Label Text="Hello" />
        </StackLayout>
    </local:MyFrame>
</StackLayout>


问:
Sum multiple fields with select new and where raises error 'Model' does not have definition of 'Sum'
First timer to C# and want to see if i can change a query. Basically, I want an aggregated values of the two currency columns in one go. There are Car dealer, with each dealer having a list of cars in their possession. So I want to get list of car dealers along with a total cost of all the cars under them. For now what I am doing is I loop over each dealer, get the cars then loop the cars over summing each cars price, which sounds inefficient to me.

```<code>public object DealerObj(Dealer d)
{
    var cars = d.DealerCars.Select(cc => new { cc.Cost }).ToList();

    var totalCost decimal = 0;
    foreach (var car in cars){
        totalCost += car.Cost;
    }

    return new {
        d.DealerName,
        totalCost = totalCost
    }
}
</code>```

While I am getting the correct results, the query appears slower. Is there a way to do a Sum() on the results and avoid the loop, something like below

```<code>   var cars = d.DealerCars.Select(cc => new { total = cc.Sum(s=>s.Cost) });
</code>```

答:
Based on this:

There are Car dealer, with each dealer having a list of cars in their
  possession. So I want to get list of car dealers along with a total
  cost of all the cars under them.

The function that you posted and Enigmativity has correctly updated to get the sum would be used to iterate over a dealer at a time.

If you have a collection of Dealers outside of this method call, in this case a List<Dealer> as an example:

```<code>List<Dealer> dealers = loadDealers();
var sumObjects = dealers.Select(d => DealerObj(d)).ToList();
</code>```

and with Enigmativity's change to get the Sum for the cars under the dealer, you would be good to go. Though I would recommend defining a suitable model (DTO or ViewModel) for this kind of summary rather than trying to pass anonymous types around and/or object references, and giving the method a more descriptive name.

If instead you want to run an operation across a dealers collection directly:

```<code>List<Dealer> dealers = loadDealers(); // Load these from data source.
var sumObjects = dealers
    .SelectMany(d => d.DealerCars)
    .GroupBy(c => c.Dealer.DealerName)
    .Select(g => new
    {
        DealerName = g.Key,
        TotalCost = g.Sum(c => c.Cost)
    }).ToList();
</code>```

This assumes all dealers are uniquely named. If not, you would want to group by c.Dealer and then select g.Key.Name along with anything to differentiate the multiple dealers /w the same name.

If you're dealing with a list of dealer objects that are loaded as a whole into memory then I would probably stick with the method approach, as it's a bit cleaner to read and interpret what is going on.

Where the 2nd approach would come into play is if you are dealing with something that uses IQueryable such as Entity Framework to retrieve your data. The first approach would need to load all dealers AND their related details into memory entirely to work without a potentially significant performance hit if related details for each dealer needed to be lazy loaded after the fact. (Extra round trips to the DB) Using the 2nd approach against an IQueryable (DbSet / EF Linq expression) means that it can be translated down to SQL provided you follow some key rules, resulting in a single, far more efficient query to the database.

For instance: Given an EF context:

```<code>using(var context = new AppContext())
{
    var sumObjects = context.Dealers
        .SelectMany(d => d.DealerCars)
        .GroupBy(c => c.Dealer.DealerName)
        .Select(g => new
        {
            DealerName = g.Key,
            TotalCost = g.Sum(c => c.Cost)
        }).ToList();
}
</code>```

Alternatively for that to work efficiently with something like a repository method, that repository would need to return IQueryable<Dealer> rather than IEnumerable<Dealer>. EF will only compose these down to an efficient query if using IQueryable. If you use IEnumerable the query will be executed before these criteria are considered and you would potentially be facing lazy load hits.

If your methods are using IEnumerable<Dealer> or List<Dealer> or arrays etc. and no idea or need for IQueryable then sticking with the method per Dealer will probably be the easiest to follow.

Body:
First timer to C# and want to see if i can change a query. Basically, I want an aggregated values of the two currency columns in one go. There are Car dealer, with each dealer having a list of cars in their possession. So I want to get list of car dealers along with a total cost of all the cars under them. For now what I am doing is I loop over each dealer, get the cars then loop the cars over summing each cars price, which sounds inefficient to me.

public object DealerObj(Dealer d)
{
    var cars = d.DealerCars.Select(cc => new { cc.Cost }).ToList();

    var totalCost decimal = 0;
    foreach (var car in cars){
        totalCost += car.Cost;
    }

    return new {
        d.DealerName,
        totalCost = totalCost
    }
}

While I am getting the correct results, the query appears slower. Is there a way to do a Sum() on the results and avoid the loop, something like below

   var cars = d.DealerCars.Select(cc => new { total = cc.Sum(s=>s.Cost) });

Body:
Based on this:

There are Car dealer, with each dealer having a list of cars in their
  possession. So I want to get list of car dealers along with a total
  cost of all the cars under them.

The function that you posted and Enigmativity has correctly updated to get the sum would be used to iterate over a dealer at a time.

If you have a collection of Dealers outside of this method call, in this case a List<Dealer> as an example:

List<Dealer> dealers = loadDealers();
var sumObjects = dealers.Select(d => DealerObj(d)).ToList();

and with Enigmativity's change to get the Sum for the cars under the dealer, you would be good to go. Though I would recommend defining a suitable model (DTO or ViewModel) for this kind of summary rather than trying to pass anonymous types around and/or object references, and giving the method a more descriptive name.

If instead you want to run an operation across a dealers collection directly:

List<Dealer> dealers = loadDealers(); // Load these from data source.
var sumObjects = dealers
    .SelectMany(d => d.DealerCars)
    .GroupBy(c => c.Dealer.DealerName)
    .Select(g => new
    {
        DealerName = g.Key,
        TotalCost = g.Sum(c => c.Cost)
    }).ToList();

This assumes all dealers are uniquely named. If not, you would want to group by c.Dealer and then select g.Key.Name along with anything to differentiate the multiple dealers /w the same name.

If you're dealing with a list of dealer objects that are loaded as a whole into memory then I would probably stick with the method approach, as it's a bit cleaner to read and interpret what is going on.

Where the 2nd approach would come into play is if you are dealing with something that uses IQueryable such as Entity Framework to retrieve your data. The first approach would need to load all dealers AND their related details into memory entirely to work without a potentially significant performance hit if related details for each dealer needed to be lazy loaded after the fact. (Extra round trips to the DB) Using the 2nd approach against an IQueryable (DbSet / EF Linq expression) means that it can be translated down to SQL provided you follow some key rules, resulting in a single, far more efficient query to the database.

For instance: Given an EF context:

using(var context = new AppContext())
{
    var sumObjects = context.Dealers
        .SelectMany(d => d.DealerCars)
        .GroupBy(c => c.Dealer.DealerName)
        .Select(g => new
        {
            DealerName = g.Key,
            TotalCost = g.Sum(c => c.Cost)
        }).ToList();
}

Alternatively for that to work efficiently with something like a repository method, that repository would need to return IQueryable<Dealer> rather than IEnumerable<Dealer>. EF will only compose these down to an efficient query if using IQueryable. If you use IEnumerable the query will be executed before these criteria are considered and you would potentially be facing lazy load hits.

If your methods are using IEnumerable<Dealer> or List<Dealer> or arrays etc. and no idea or need for IQueryable then sticking with the method per Dealer will probably be the easiest to follow.


问:
Accessing value from key with JavaScript
I'm new to JavaScript. This is giving me undefined.

What am I doing wrong? How do I log the values inside the objects?

let spaceship = {
  passengers: null
};

(spaceship.passengers = [{ name: "Mike" }, { ability: "teleportation" }]),
  [{ name: "David" }, { ability: "cook" }];

let firstPassenger = spaceship.passengers[0];
console.log(firstPassenger.ability);```

答:
You defined object in a wrong way.
You should define object like this to get the desired result</p>

```<code>let spaceship = {
    passengers: null
  };

        spaceship.passengers = [
            {
               name: "Mike" , ability: "teleportation"
            },
            {
               name: "David" , ability: "cook"
            }
          ];
     let firstPassenger = spaceship.passengers[0];
          console.log(firstPassenger.ability);
</code>```

Body:
You defined object in a wrong way.
You should define object like this to get the desired result

let spaceship = {
    passengers: null
  };

        spaceship.passengers = [
            {
               name: "Mike" , ability: "teleportation"
            },
            {
               name: "David" , ability: "cook"
            }
          ];
     let firstPassenger = spaceship.passengers[0];
          console.log(firstPassenger.ability);


问:
Java 8 stream grouping by on property ignoring case sensitive
I have the following classes:

LivingPlace:

```<code>public class LivingPlace {
    public LivingPlace(String province) {
        this.province = province;
    }

    private String province;

    public String getProvince() {
        return province;
    }
}
</code>```

User:

```<code>public class User {
    private LivingPlace viv;
    private int age;

    public User(LivingPlace viv, int age) {
        this.viv = viv;
        this.age = age;
    }

    public LivingPlace getLivingPlace() {
        return viv;
    }

    public int getAge() {
        return age;
    }
}
</code>```

And then on my Main class I have a list of Users.
I want to get the amount of users below the age of 18, grouped by province (knowing that the name of provinces of each user can have any combination of upcase or lowercase letters).
I thought something like:

```<code>    Map<String, Integer> rta = users.stream()
            .filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
            .collect(Collectors.toMap(us -> us.getLivingPlace().getProvince(), Collectors.counting()));
</code>```

However this won't compile.

Any ideas?

I get several errors:

```<code>* method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> us) -> {}, Collector<Object,?,Long>)
* The method getLivingPlace() is undefined for the type T
* method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> us) -> {}, Collector<Object,?,Long>)
</code>```

答:
For grouping operations you should use Collectors.groupingBy because Collectors.toMap will take Function as arguments

```<code>Map<String, Long> rta = users.stream().filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
        .collect(Collectors.groupingBy(us -> us.getLivingPlace().getProvince(), Collectors.counting()));
</code>```

As @Holger suggested you can also use Collectors.toMap with merge function when you expect a large number of groups with small counts

```<code>Map<String, Integer> rta = users.stream()
.filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
.collect(Collectors.toMap(us -> us.getLivingPlace().getProvince(),
    a -> 1L, Integer::sum));
</code>```

And if you want to perform grouping operation by ignoring cases, you can either convert province to lower case or upper case

```<code>Map<String, Long> rta = users.stream().filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
    .collect(Collectors.groupingBy(us -> us.getLivingPlace().getProvince().toLowerCase(), Collectors.counting()));
</code>```

or you can use TreeMap with CASE_INSENSITIVE_ORDER comparator

```<code>Map<String, Long> result = users.stream()
      .filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
      .collect(Collectors.groupingBy(us -> us.getLivingPlace().getProvince(),
            () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER), Collectors.counting()));
</code>```

Body:
I have the following classes:

LivingPlace:

public class LivingPlace {
    public LivingPlace(String province) {
        this.province = province;
    }

    private String province;

    public String getProvince() {
        return province;
    }
}

User:

public class User {
    private LivingPlace viv;
    private int age;

    public User(LivingPlace viv, int age) {
        this.viv = viv;
        this.age = age;
    }

    public LivingPlace getLivingPlace() {
        return viv;
    }

    public int getAge() {
        return age;
    }
}

And then on my Main class I have a list of Users.
I want to get the amount of users below the age of 18, grouped by province (knowing that the name of provinces of each user can have any combination of upcase or lowercase letters).
I thought something like:

    Map<String, Integer> rta = users.stream()
            .filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
            .collect(Collectors.toMap(us -> us.getLivingPlace().getProvince(), Collectors.counting()));

However this won't compile.

Any ideas?

I get several errors:

* method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> us) -> {}, Collector<Object,?,Long>)
* The method getLivingPlace() is undefined for the type T
* method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> us) -> {}, Collector<Object,?,Long>)

Body:
For grouping operations you should use Collectors.groupingBy because Collectors.toMap will take Function as arguments

Map<String, Long> rta = users.stream().filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
        .collect(Collectors.groupingBy(us -> us.getLivingPlace().getProvince(), Collectors.counting()));

As @Holger suggested you can also use Collectors.toMap with merge function when you expect a large number of groups with small counts

Map<String, Integer> rta = users.stream()
.filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
.collect(Collectors.toMap(us -> us.getLivingPlace().getProvince(),
    a -> 1L, Integer::sum));

And if you want to perform grouping operation by ignoring cases, you can either convert province to lower case or upper case

Map<String, Long> rta = users.stream().filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
    .collect(Collectors.groupingBy(us -> us.getLivingPlace().getProvince().toLowerCase(), Collectors.counting()));

or you can use TreeMap with CASE_INSENSITIVE_ORDER comparator

Map<String, Long> result = users.stream()
      .filter(user -> user.getAge() < 18 && user.getLivingPlace() != null)
      .collect(Collectors.groupingBy(us -> us.getLivingPlace().getProvince(),
            () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER), Collectors.counting()));


问:
Terminal stops printing even with a running process
I have tried to open a child process in a new terminal but found no solution online or in any book.
I recently studied about Unix Domain Sockets and passing file descriptors and tried to achieve it using these.

The following is the pseudo-code for my program. send_fd and recv_fd are function for passing fds as defined in the Richard Stevens book.

The programs are working almost as expected. The output and input of the child process are redirected to the newly created terminal. But the child process is only able to print as long as process temp is still running. When temp terminates, child stops printing in the new terminal and the new terminal closes. How should I overcome this? Thanks in advance.

```<code>int forknt()
{
    system("gnome-terminal -- \"./temp\""); //run auxiliary program in a new terminal
    //sfd is fd of the unix domain socket used to connect to ./temp
    int fd0 = recv_fd(sfd); //get stdin of new terminal
    int fd1 = recv_fd(sfd); //get stdout of new terminal
    int c = fork();
    if(!c)
    {
        dup2(fd0, 0);
        dup2(fd1, 1);
    }
    close(sfd);
    return c;
}

int main()
{
    int c = forknt();
    printf("%d\n", c);
    return 0;
}
</code>```

Code for auxiliary program temp

```<code>int main()
{
    send_fd(sfd, 0);
    send_fd(sfd, 1);
    return 0;
}
</code>```

答:
The terminal program, which sets up the standard input and output of the sub-process it starts and connects them to itself for I/O, will also terminate when the sub-process terminates.  If instead you tell gnome-terminal to start a shell after the first ./temp program terminates, then it will stay open and I think then your first program should be able to continue to read and write to the transferred file descriptors.

```<code>gnome-terminal -- "./temp; exec sh"
</code>```

See this Unix answer.

Body:
I have tried to open a child process in a new terminal but found no solution online or in any book.
I recently studied about Unix Domain Sockets and passing file descriptors and tried to achieve it using these.

The following is the pseudo-code for my program. send_fd and recv_fd are function for passing fds as defined in the Richard Stevens book.

The programs are working almost as expected. The output and input of the child process are redirected to the newly created terminal. But the child process is only able to print as long as process temp is still running. When temp terminates, child stops printing in the new terminal and the new terminal closes. How should I overcome this? Thanks in advance.

int forknt()
{
    system("gnome-terminal -- \"./temp\""); //run auxiliary program in a new terminal
    //sfd is fd of the unix domain socket used to connect to ./temp
    int fd0 = recv_fd(sfd); //get stdin of new terminal
    int fd1 = recv_fd(sfd); //get stdout of new terminal
    int c = fork();
    if(!c)
    {
        dup2(fd0, 0);
        dup2(fd1, 1);
    }
    close(sfd);
    return c;
}

int main()
{
    int c = forknt();
    printf("%d\n", c);
    return 0;
}

Code for auxiliary program temp

int main()
{
    send_fd(sfd, 0);
    send_fd(sfd, 1);
    return 0;
}

Body:
The terminal program, which sets up the standard input and output of the sub-process it starts and connects them to itself for I/O, will also terminate when the sub-process terminates.  If instead you tell gnome-terminal to start a shell after the first ./temp program terminates, then it will stay open and I think then your first program should be able to continue to read and write to the transferred file descriptors.

gnome-terminal -- "./temp; exec sh"

See this Unix answer.