问:
display message in button click during postback
Hai frnds , i want to show the message on button click....please help advance thanks</p>

答:
Try this code

```<code>            <head>
              <script type="text/javascript" language="javascript">
                    function message() {
                        alert("THIS IS A MESSAGE!!!");
                    }

                </script>
            </head>

            <body>
                <form id="form1" runat="server">
                <div>
                <button onclick="message()">MESSAGE</button>
                </div>
                </form>
            </body>
            </html>
</code>```

And you can try JQUERY DIALOG: http://jqueryui.com/demos/dialog/

Body:
Try this code

            <head>
              <script type="text/javascript" language="javascript">
                    function message() {
                        alert("THIS IS A MESSAGE!!!");
                    }

                </script>
            </head>

            <body>
                <form id="form1" runat="server">
                <div>
                <button onclick="message()">MESSAGE</button>
                </div>
                </form>
            </body>
            </html>

And you can try JQUERY DIALOG: http://jqueryui.com/demos/dialog/


来源: stackexchange

问:
Input string to a char pointer member of an array of structure
I'm trying to input a string of characters to a pointer member of char type of an array of structure. The program is terminating after it receives the string for the member name of emp[0]. My code:

```<code>#include<stdio.h>
struct Employee
{
    char *name;
    int salary;
};

int main()
{
    struct Employee emp[3];

    int i;
    for(i=0;i<3;i++)
    {
        scanf("%s%d",emp[i].name,&emp[i].salary);
    }
    printf("\nOutput:");
    for(i=0;i<3;i++)
    {
        printf("\n%s%d",emp[i].name,emp[i].salary);
    }

    return 0;
}
</code>```

When without array, the following code for some variable emp is working fine:

```<code>scanf("%s%d",emp.name,&emp.salary);
</code>```

Any suggestions? Thanks in advance.

答:
The name field in struct Employee is a pointer.  You never give that pointer a value, but you pass it to scanf which then attempts to dereference it.  Dereferencing an uninitialized pointer invokes undefined behavior.

Instead of using a char * for name, make it an array large enough to hold whatever value you expect:

```<code>struct Employee
{
    char name[50];
    int salary;
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to input a string of characters to a pointer member of char type of an array of structure. The program is terminating after it receives the string for the member name of emp[0]. My code:

#include<stdio.h>
struct Employee
{
    char *name;
    int salary;
};

int main()
{
    struct Employee emp[3];

    int i;
    for(i=0;i<3;i++)
    {
        scanf("%s%d",emp[i].name,&emp[i].salary);
    }
    printf("\nOutput:");
    for(i=0;i<3;i++)
    {
        printf("\n%s%d",emp[i].name,emp[i].salary);
    }

    return 0;
}

When without array, the following code for some variable emp is working fine:

scanf("%s%d",emp.name,&emp.salary);

Any suggestions? Thanks in advance.

Body:
The name field in struct Employee is a pointer.  You never give that pointer a value, but you pass it to scanf which then attempts to dereference it.  Dereferencing an uninitialized pointer invokes undefined behavior.

Instead of using a char * for name, make it an array large enough to hold whatever value you expect:

struct Employee
{
    char name[50];
    int salary;
};


问:
Outlook API Authentication in Microsoft Graph
I am working into an Outlook integration via Microsoft Graph for our SaaS application. As it stands, my application has basic authentication (username/passsword) and to be able to call the API methods from Microsoft Graph, the user must be signed-in to his Microsoft account and changing authentication methods from the current to AD-driven one may not be an option yet as it'll affect a lot of modules in place.

Is it possible to link the profile to the Microsoft account the user has,
autologging them in and use it to call the API methods - like the style with Facebook & Twitter? If not, how can I be able to call API methods without having them to sign-in everytime the session expires?

答:
There are a few options for your scenario:

AD supports a resource owner credentials grant in V1 auth which allows you to authenticate with user credentials. This has some limitations such as lacking support for MFA, and requires you to be very careful about handling user credentials.

Alternatively, you can call into Graph using the V2 auth client credential flow in which a tenant admin consents to an application making calls to Graph on behalf of their tenant. Using this flow, your service would also be able to query for resources in Graph without requiring the user to go through the sign-in flow.


问:
SAPUI5 Master Detail Template App - Multiple EntitySets, binding data
I have created a Master Detail template app in Web IDE. (See image)

I have an OData service (ZSV_SURVEY_SRV) with many EntitySets.

Master (left side) calls my EntitySet SurveySet and loads all Surveys found.

Detail (right side) calls my EntitySet QuestionSet and I've just currently got it so it loads all Questions found. What I really need to do is bring back only the Questions specific to the Survey selected in the Master section.

It's the first time I've used the Master Detail app template and I'm a little lost with to pull data from one EntitySet that is related to data in another EntitySet.

Tried different variations of binding, but just have it set back to read all from the QuestionSet for now.

Detail View:

```<code><mvc:View xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form"
xmlns:semantic="sap.m.semantic" xmlns:footerbar="sap.ushell.ui.footerbar" controllerName="managesurveys.controller.Detail">
<semantic:DetailPage id="page" navButtonPress="onNavBack" showNavButton="{device>/system/phone}" title="{Name}" busy="{detailView>/busy}"
    busyIndicatorDelay="{detailView>/delay}">
    <semantic:content>
        <!-- Start of Survey Details Form -->
        <f:Form editable="true" class="sapUiSmallMarginTop">
            <f:formContainers>
                <!-- Survey Details -->
                <f:FormContainer>
                    <f:formElements>
                        <!-- Survey Name -->
                        <f:FormElement label="{i18n>surveyName}">
                            <f:fields>
                                <Input value="{Name}" width="100%" id="__inputSurveyName" liveChange="validateForm"/>
                            </f:fields>
                        </f:FormElement>
                        <!-- Description -->
                        <f:FormElement label="{i18n>description}">
                            <f:fields>
                                <TextArea value="{SurveyDesc}" id="__areaSurveyDescription"/>
                            </f:fields>
                        </f:FormElement>
                    </f:formElements>
                </f:FormContainer>
                <f:FormContainer>
                    <f:formElements>
                        <f:FormElement label="{i18n>reporting}">
                            <f:fields>
                                <RadioButtonGroup width="100%" selectedIndex="-1" id="__group0" columns="3">
                                    <buttons>
                                        <RadioButton selected="true" text="{i18n>onSubmission}" id="__reportingOnSubmission" select="onReportingSelected"/>
                                        <RadioButton text="{i18n>onDate}" id="__reportingOnDate" select="onReportingDateSelected"/>
                                        <RadioButton text="{i18n>none}" id="__reportingNo" select="onNoReportingSelected"/>
                                    </buttons>
                                </RadioButtonGroup>
                            </f:fields>
                        </f:FormElement>
                        <f:FormElement label="" id="__reportDateElement" visible="false">
                            <f:fields>
                                <DatePicker id="__reportDate" placeholder="{i18n>enterDate}" change="onReportingDateChange"/>
                            </f:fields>
                        </f:FormElement>
                    </f:formElements>
                </f:FormContainer>
            </f:formContainers>
            <f:layout>
                <f:ResponsiveGridLayout/>
            </f:layout>
        </f:Form>
        <!-- Categories -->
        <!--<IconTabBar items="{/CategorySet}" id="iconTabBar" enableTabReordering="true" class="sapUiResponsiveContentPadding" expandable="false">-->
            <!--<items>-->
                <!--<IconTabFilter text="{CategoryDesc}">-->
                    <List  id="list" mode="SingleSelectMaster" delete="handleDelete" items="{path:'/QuestionSet', templateShareable:true}"
                        includeItemInSelection="true" selectionChange="onQuestionSelect" headerText="{i18n>questions}">
                        <CustomListItem>
                            <l:Grid>
                                <Text text="ID ({SurveyId}) - Question ({QuestionDesc})"
                                    class="sapUiTinyMarginTop sapUiLargeMarginBegin">
                                    <layoutData>
                                        <l:GridData span="XL9 L9 M9 S9"/>
                                    </layoutData>
                                </Text>
                                <Button icon="sap-icon://navigation-up-arrow">
                                    <layoutData>
                                        <l:GridData span="XL1 L1 M1 S1"/>
                                    </layoutData>
                                </Button>
                                <Button icon="sap-icon://navigation-down-arrow">
                                    <layoutData>
                                        <l:GridData span="XL1 L1 M1 S1"/>
                                    </layoutData>
                                </Button>
                                <Button icon="sap-icon://delete" type="Reject">
                                    <layoutData>
                                        <l:GridData span="XL1 L1 M1 S1"/>
                                    </layoutData>
                                </Button>
                            </l:Grid>
                        </CustomListItem>
                    </List>
                <!--</IconTabFilter>-->
            <!--</items>-->
        <!--</IconTabBar>-->
    </semantic:content>
    <!-- Footer -->
    <semantic:positiveAction>
        <semantic:PositiveAction text="{i18n>btnSaveSurvey}" id="btnSurveySave" press="onSaveSurvey" enabled="false"/>
    </semantic:positiveAction>
</semantic:DetailPage>
</code>```

Detail Controller:

```<code>sap.ui.define([
"managesurveys/controller/BaseController",
"sap/ui/model/json/JSONModel",
"managesurveys/model/formatter",
"sap/m/MessageBox",
"sap/m/MessageToast",
"managesurveys/libs/underscore"
</code>```

], function(BaseController, JSONModel, formatter, MessageBox, MessageToast, UnderScoreJS) {
    "use strict";

```<code>return BaseController.extend("managesurveys.controller.Detail", {

    formatter: formatter,

    /* =========================================================== */
    /* lifecycle methods                                           */
    /* =========================================================== */

    onInit: function() {
        // Model used to manipulate control states. The chosen values make sure,
        // detail page is busy indication immediately so there is no break in
        // between the busy indication for loading the view's meta data
        var oViewModel = new JSONModel({
            busy: false,
            delay: 0,
            questions: [{
                order: 1,
                title: "",
                criteria: "",
                category: "",
                competency: "",
                showScore: false,
                addImage: false,
                questionType: 0,
                minimumCommentsLength: 10,
                additionalQuestionTitle: "1",
                additionalQuestionDesc: "2",
                additionalQuestionType: 1,
                numberOfAnswers: 3,
                answers: [{
                    sequence: 1,
                    label: "Yes",
                    points: 2,
                    imageFlag: false,
                    image: "/images/happy-1.svg",
                    mandatoryComments: false,
                    additionalQuestion: false
                }, {
                    sequence: 2,
                    label: "No",
                    points: 0,
                    imageFlag: false,
                    image: "/images/sceptic.svg",
                    mandatoryComments: false,
                    additionalQuestion: false
                }, {
                    sequence: 3,
                    label: "N/A",
                    points: -2,
                    imageFlag: false,
                    image: "/images/angry-2.svg",
                    mandatoryComments: false,
                    additionalQuestion: false
                }]
            }]
        });

        this.getRouter().getRoute("object").attachPatternMatched(this._onObjectMatched, this);

        this.setModel(oViewModel, "detailView");

        this.getOwnerComponent().getModel().metadataLoaded().then(this._onMetadataLoaded.bind(this));
    },

    /* =========================================================== */
    /* begin: internal methods                                     */
    /* =========================================================== */

    /**
     * Binds the view to the object path and expands the aggregated line items.
     * @function
     * @param {sap.ui.base.Event} oEvent pattern match event in route 'object'
     * @private
     */
    _onObjectMatched: function(oEvent) {
        var sObjectId = oEvent.getParameter("arguments").objectId;
        this.getModel().metadataLoaded().then(function() {
            var sObjectPath = this.getModel().createKey("SurveySet", {
                SurveyId: sObjectId
            });
            this._bindView("/" + sObjectPath);
        }.bind(this));
    },

    /**
     * Binds the view to the object path. Makes sure that detail view displays
     * a busy indicator while data for the corresponding element binding is loaded.
     * @function
     * @param {string} sObjectPath path to the object to be bound to the view.
     * @private
     */
    _bindView: function(sObjectPath) {
        // Set busy indicator during view binding
        var oViewModel = this.getModel("detailView");

        // If the view was not bound yet its not busy, only if the binding requests data it is set to busy again
        oViewModel.setProperty("/busy", false);

        this.getView().bindElement({
            path: sObjectPath,
            events: {
                change: this._onBindingChange.bind(this),
                dataRequested: function() {
                    oViewModel.setProperty("/busy", true);
                },
                dataReceived: function() {
                    oViewModel.setProperty("/busy", false);
                }
            }
        });
    },

    _onBindingChange: function() {
        var oView = this.getView(),
            oElementBinding = oView.getElementBinding();

        // No data for the binding
        if (!oElementBinding.getBoundContext()) {
            this.getRouter().getTargets().display("detailObjectNotFound");
            // if object could not be found, the selection in the master list
            // does not make sense anymore.
            this.getOwnerComponent().oListSelector.clearMasterListSelection();
            return;
        }

        var sPath = oElementBinding.getPath(),
            oResourceBundle = this.getResourceBundle(),
            oObject = oView.getModel().getObject(sPath),
            sObjectId = oObject.SurveyId,
            sObjectName = oObject.SurveyDesc,
            oViewModel = this.getModel("detailView");

        this.getOwnerComponent().oListSelector.selectAListItem(sPath);

        oViewModel.setProperty("/saveAsTileTitle", oResourceBundle.getText("shareSaveTileAppTitle", [sObjectName]));
        oViewModel.setProperty("/shareOnJamTitle", sObjectName);
        oViewModel.setProperty("/shareSendEmailSubject",
            oResourceBundle.getText("shareSendEmailObjectSubject", [sObjectId]));
        oViewModel.setProperty("/shareSendEmailMessage",
            oResourceBundle.getText("shareSendEmailObjectMessage", [sObjectName, sObjectId, location.href]));
    },

    _onMetadataLoaded: function() {
        // Store original busy indicator delay for the detail view
        var iOriginalViewBusyDelay = this.getView().getBusyIndicatorDelay(),
            oViewModel = this.getModel("detailView");

        // Make sure busy indicator is displayed immediately when
        // detail view is displayed for the first time
        oViewModel.setProperty("/delay", 0);

        // Binding the view will set it to not busy - so the view is always busy if it is not bound
        oViewModel.setProperty("/busy", true);
        // Restore original busy indicator delay for the detail view
        oViewModel.setProperty("/delay", iOriginalViewBusyDelay);
    },

    // Question radio button selected, ready for delete question
    onQuestionSelect: function(oEvent) {
        console.log("Question Selected");
        this.getView().byId("btnSurveySave").setEnabled(true);

        var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
        oRouter.navTo("questiondetails");

        //var oContext = oEvent.getParameters().listItem.getBindingContext(this.MODEL_SITE);
        //var oData = oContext.getModel().getProperty(oContext.getPath());
        //this.getRouter().navTo("QuestionDetails", {QuestionId: oData.QuestionId});
    },

    // Delete Question Message Box
    onDeleteQuestion: function() {
        var that = this;
        var oViewModel = this.getModel("masterView");
        MessageBox.show("Are you sure you want to delete this Question?", {
            icon: MessageBox.Icon.ERROR,
            title: "Delete Question",
            actions: [MessageBox.Action.YES, MessageBox.Action.NO],
            onClose: function(oAction) {
                if (oAction === MessageBox.Action.YES) {
                    that.getModel().remove("/SurveySet", {
                        SurveyId: oViewModel.SurveyId
                    }, {
                        success: function() {
                            MessageToast.show("Survey successfully deleted", {
                                duration: 2000
                            });
                        },
                        error: function() {
                            MessageToast.show("Error deleting Survey", {
                                duration: 2000
                            });
                        }
                    });
                }
            }
        });
    },

    // Save Survey
    onSaveSurvey: function() {
        MessageToast.show("Survey successfully saved", {
            duration: 2000
        });
    }

});
</code>```

});

答:
Your question is very common and it is not related only with a Master/Detail app.

Actually, the solution needed is as simple as fixing your UI5 code but a mix of fixed in your oData model (so, you will have to adapt your SAP Gateway project in SEGW transaction) + service implementation + UI5 code.

oData part

You need to create an association + navigation property between your entity types.

Assuming your entity type names are Survey and Question.

Create an association between Survey and Question entity types. As a survey might have multiple questions in your model, it's very important to set the cardinality to 1:n

Create an association set between SurveySet and QuestionSet entity sets

Create a navigation property in Survey entity type which is linked with the association you created. Let's assume your navigation property is called "ToQuestions"

This fixes your odata model

Your oData calls will be something like:

```<code>Get all surveys
GET /sap/opu/odata/sap/ZSV_SURVEY_SRV/SurveySet

Get a specific survey
GET /sap/opu/odata/sap/ZSV_SURVEY_SRV/SurveySet(1)

Get all questions from a survey
GET /sap/opu/odata/sap/ZSV_SURVEY_SRV/SurveySet(1)/ToQuestions
</code>```

ABAP part

Assuming you have used Gateway Service Generation to implement your project, you will have to add a mandatory importing parameter in the function module which fetches your questions (the one mapped with the GetEntitySet operation of QuestionSet). This parameter will represent the ID of a survey. You will have also to map the SurveyId property with the imporing parameter. So you will have two rows in your mappings for SurveyId Propety. One row will have an arrow pointing to the right (for the importing parameter), and the other will have an arrow pointing to the left (for the survey id column of the exported internal table)

Assuming you have not used service generation but service implementation (when you manually develop your ABAP code in DPC_EXT class) you will need to read the survey id using the following method call:

```<code>io_tech_request_context->get_converted_keys(
  IMPORTING
    es_key_values = ls_converted_keys ).
</code>```

UI5 part

You will also have to do a minor fix in your UI5 code.

Apart from using your second entity set in the list aggregation binding, like this...

```<code><List  items="{path:'/QuestionSet', templateShareable:true}" >
</code>```

You will have to use the exact name of your navigation property

```<code><List  items="{path:'/ToQuestions' }" >
</code>```

or just

```<code><List  items="{/ToQuestions}" >
</code>```

I bet templateShareable is not needed in your scenario.

So, the detail page will be binded with '/SurveySet(1)' because you already have a call to .bindElement method

```<code>this._bindView("/" + sObjectPath);
</code>```

So relative to this binding, your question table will be binded to /ToQuestions navigation property.

Body:
I have created a Master Detail template app in Web IDE. (See image)

I have an OData service (ZSV_SURVEY_SRV) with many EntitySets.

Master (left side) calls my EntitySet SurveySet and loads all Surveys found.

Detail (right side) calls my EntitySet QuestionSet and I've just currently got it so it loads all Questions found. What I really need to do is bring back only the Questions specific to the Survey selected in the Master section.

It's the first time I've used the Master Detail app template and I'm a little lost with to pull data from one EntitySet that is related to data in another EntitySet.

Tried different variations of binding, but just have it set back to read all from the QuestionSet for now.

Detail View:

<mvc:View xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form"
xmlns:semantic="sap.m.semantic" xmlns:footerbar="sap.ushell.ui.footerbar" controllerName="managesurveys.controller.Detail">
<semantic:DetailPage id="page" navButtonPress="onNavBack" showNavButton="{device>/system/phone}" title="{Name}" busy="{detailView>/busy}"
    busyIndicatorDelay="{detailView>/delay}">
    <semantic:content>

        <f:Form editable="true" class="sapUiSmallMarginTop">
            <f:formContainers>

                <f:FormContainer>
                    <f:formElements>

                        <f:FormElement label="{i18n>surveyName}">
                            <f:fields>
                                <Input value="{Name}" width="100%" id="__inputSurveyName" liveChange="validateForm"/>
                            </f:fields>
                        </f:FormElement>

                        <f:FormElement label="{i18n>description}">
                            <f:fields>
                                <TextArea value="{SurveyDesc}" id="__areaSurveyDescription"/>
                            </f:fields>
                        </f:FormElement>
                    </f:formElements>
                </f:FormContainer>
                <f:FormContainer>
                    <f:formElements>
                        <f:FormElement label="{i18n>reporting}">
                            <f:fields>
                                <RadioButtonGroup width="100%" selectedIndex="-1" id="__group0" columns="3">
                                    <buttons>
                                        <RadioButton selected="true" text="{i18n>onSubmission}" id="__reportingOnSubmission" select="onReportingSelected"/>
                                        <RadioButton text="{i18n>onDate}" id="__reportingOnDate" select="onReportingDateSelected"/>
                                        <RadioButton text="{i18n>none}" id="__reportingNo" select="onNoReportingSelected"/>
                                    </buttons>
                                </RadioButtonGroup>
                            </f:fields>
                        </f:FormElement>
                        <f:FormElement label="" id="__reportDateElement" visible="false">
                            <f:fields>
                                <DatePicker id="__reportDate" placeholder="{i18n>enterDate}" change="onReportingDateChange"/>
                            </f:fields>
                        </f:FormElement>
                    </f:formElements>
                </f:FormContainer>
            </f:formContainers>
            <f:layout>
                <f:ResponsiveGridLayout/>
            </f:layout>
        </f:Form>

                    <List  id="list" mode="SingleSelectMaster" delete="handleDelete" items="{path:'/QuestionSet', templateShareable:true}"
                        includeItemInSelection="true" selectionChange="onQuestionSelect" headerText="{i18n>questions}">
                        <CustomListItem>
                            <l:Grid>
                                <Text text="ID ({SurveyId}) - Question ({QuestionDesc})"
                                    class="sapUiTinyMarginTop sapUiLargeMarginBegin">
                                    <layoutData>
                                        <l:GridData span="XL9 L9 M9 S9"/>
                                    </layoutData>
                                </Text>
                                <Button icon="sap-icon://navigation-up-arrow">
                                    <layoutData>
                                        <l:GridData span="XL1 L1 M1 S1"/>
                                    </layoutData>
                                </Button>
                                <Button icon="sap-icon://navigation-down-arrow">
                                    <layoutData>
                                        <l:GridData span="XL1 L1 M1 S1"/>
                                    </layoutData>
                                </Button>
                                <Button icon="sap-icon://delete" type="Reject">
                                    <layoutData>
                                        <l:GridData span="XL1 L1 M1 S1"/>
                                    </layoutData>
                                </Button>
                            </l:Grid>
                        </CustomListItem>
                    </List>

    </semantic:content>

    <semantic:positiveAction>
        <semantic:PositiveAction text="{i18n>btnSaveSurvey}" id="btnSurveySave" press="onSaveSurvey" enabled="false"/>
    </semantic:positiveAction>
</semantic:DetailPage>

Detail Controller:

sap.ui.define([
"managesurveys/controller/BaseController",
"sap/ui/model/json/JSONModel",
"managesurveys/model/formatter",
"sap/m/MessageBox",
"sap/m/MessageToast",
"managesurveys/libs/underscore"

], function(BaseController, JSONModel, formatter, MessageBox, MessageToast, UnderScoreJS) {
    "use strict";

return BaseController.extend("managesurveys.controller.Detail", {

    formatter: formatter,

    /* =========================================================== */
    /* lifecycle methods                                           */
    /* =========================================================== */

    onInit: function() {
        // Model used to manipulate control states. The chosen values make sure,
        // detail page is busy indication immediately so there is no break in
        // between the busy indication for loading the view's meta data
        var oViewModel = new JSONModel({
            busy: false,
            delay: 0,
            questions: [{
                order: 1,
                title: "",
                criteria: "",
                category: "",
                competency: "",
                showScore: false,
                addImage: false,
                questionType: 0,
                minimumCommentsLength: 10,
                additionalQuestionTitle: "1",
                additionalQuestionDesc: "2",
                additionalQuestionType: 1,
                numberOfAnswers: 3,
                answers: [{
                    sequence: 1,
                    label: "Yes",
                    points: 2,
                    imageFlag: false,
                    image: "/images/happy-1.svg",
                    mandatoryComments: false,
                    additionalQuestion: false
                }, {
                    sequence: 2,
                    label: "No",
                    points: 0,
                    imageFlag: false,
                    image: "/images/sceptic.svg",
                    mandatoryComments: false,
                    additionalQuestion: false
                }, {
                    sequence: 3,
                    label: "N/A",
                    points: -2,
                    imageFlag: false,
                    image: "/images/angry-2.svg",
                    mandatoryComments: false,
                    additionalQuestion: false
                }]
            }]
        });

        this.getRouter().getRoute("object").attachPatternMatched(this._onObjectMatched, this);

        this.setModel(oViewModel, "detailView");

        this.getOwnerComponent().getModel().metadataLoaded().then(this._onMetadataLoaded.bind(this));
    },

    /* =========================================================== */
    /* begin: internal methods                                     */
    /* =========================================================== */

    /**
     * Binds the view to the object path and expands the aggregated line items.
     * @function
     * @param {sap.ui.base.Event} oEvent pattern match event in route 'object'
     * @private
     */
    _onObjectMatched: function(oEvent) {
        var sObjectId = oEvent.getParameter("arguments").objectId;
        this.getModel().metadataLoaded().then(function() {
            var sObjectPath = this.getModel().createKey("SurveySet", {
                SurveyId: sObjectId
            });
            this._bindView("/" + sObjectPath);
        }.bind(this));
    },

    /**
     * Binds the view to the object path. Makes sure that detail view displays
     * a busy indicator while data for the corresponding element binding is loaded.
     * @function
     * @param {string} sObjectPath path to the object to be bound to the view.
     * @private
     */
    _bindView: function(sObjectPath) {
        // Set busy indicator during view binding
        var oViewModel = this.getModel("detailView");

        // If the view was not bound yet its not busy, only if the binding requests data it is set to busy again
        oViewModel.setProperty("/busy", false);

        this.getView().bindElement({
            path: sObjectPath,
            events: {
                change: this._onBindingChange.bind(this),
                dataRequested: function() {
                    oViewModel.setProperty("/busy", true);
                },
                dataReceived: function() {
                    oViewModel.setProperty("/busy", false);
                }
            }
        });
    },

    _onBindingChange: function() {
        var oView = this.getView(),
            oElementBinding = oView.getElementBinding();

        // No data for the binding
        if (!oElementBinding.getBoundContext()) {
            this.getRouter().getTargets().display("detailObjectNotFound");
            // if object could not be found, the selection in the master list
            // does not make sense anymore.
            this.getOwnerComponent().oListSelector.clearMasterListSelection();
            return;
        }

        var sPath = oElementBinding.getPath(),
            oResourceBundle = this.getResourceBundle(),
            oObject = oView.getModel().getObject(sPath),
            sObjectId = oObject.SurveyId,
            sObjectName = oObject.SurveyDesc,
            oViewModel = this.getModel("detailView");

        this.getOwnerComponent().oListSelector.selectAListItem(sPath);

        oViewModel.setProperty("/saveAsTileTitle", oResourceBundle.getText("shareSaveTileAppTitle", [sObjectName]));
        oViewModel.setProperty("/shareOnJamTitle", sObjectName);
        oViewModel.setProperty("/shareSendEmailSubject",
            oResourceBundle.getText("shareSendEmailObjectSubject", [sObjectId]));
        oViewModel.setProperty("/shareSendEmailMessage",
            oResourceBundle.getText("shareSendEmailObjectMessage", [sObjectName, sObjectId, location.href]));
    },

    _onMetadataLoaded: function() {
        // Store original busy indicator delay for the detail view
        var iOriginalViewBusyDelay = this.getView().getBusyIndicatorDelay(),
            oViewModel = this.getModel("detailView");

        // Make sure busy indicator is displayed immediately when
        // detail view is displayed for the first time
        oViewModel.setProperty("/delay", 0);

        // Binding the view will set it to not busy - so the view is always busy if it is not bound
        oViewModel.setProperty("/busy", true);
        // Restore original busy indicator delay for the detail view
        oViewModel.setProperty("/delay", iOriginalViewBusyDelay);
    },

    // Question radio button selected, ready for delete question
    onQuestionSelect: function(oEvent) {
        console.log("Question Selected");
        this.getView().byId("btnSurveySave").setEnabled(true);

        var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
        oRouter.navTo("questiondetails");

        //var oContext = oEvent.getParameters().listItem.getBindingContext(this.MODEL_SITE);
        //var oData = oContext.getModel().getProperty(oContext.getPath());
        //this.getRouter().navTo("QuestionDetails", {QuestionId: oData.QuestionId});
    },

    // Delete Question Message Box
    onDeleteQuestion: function() {
        var that = this;
        var oViewModel = this.getModel("masterView");
        MessageBox.show("Are you sure you want to delete this Question?", {
            icon: MessageBox.Icon.ERROR,
            title: "Delete Question",
            actions: [MessageBox.Action.YES, MessageBox.Action.NO],
            onClose: function(oAction) {
                if (oAction === MessageBox.Action.YES) {
                    that.getModel().remove("/SurveySet", {
                        SurveyId: oViewModel.SurveyId
                    }, {
                        success: function() {
                            MessageToast.show("Survey successfully deleted", {
                                duration: 2000
                            });
                        },
                        error: function() {
                            MessageToast.show("Error deleting Survey", {
                                duration: 2000
                            });
                        }
                    });
                }
            }
        });
    },

    // Save Survey
    onSaveSurvey: function() {
        MessageToast.show("Survey successfully saved", {
            duration: 2000
        });
    }

});

});

Body:
Your question is very common and it is not related only with a Master/Detail app.

Actually, the solution needed is as simple as fixing your UI5 code but a mix of fixed in your oData model (so, you will have to adapt your SAP Gateway project in SEGW transaction) + service implementation + UI5 code.

oData part

You need to create an association + navigation property between your entity types.

Assuming your entity type names are Survey and Question.

Create an association between Survey and Question entity types. As a survey might have multiple questions in your model, it's very important to set the cardinality to 1:n

Create an association set between SurveySet and QuestionSet entity sets

Create a navigation property in Survey entity type which is linked with the association you created. Let's assume your navigation property is called "ToQuestions"

This fixes your odata model

Your oData calls will be something like:

Get all surveys
GET /sap/opu/odata/sap/ZSV_SURVEY_SRV/SurveySet

Get a specific survey
GET /sap/opu/odata/sap/ZSV_SURVEY_SRV/SurveySet(1)

Get all questions from a survey
GET /sap/opu/odata/sap/ZSV_SURVEY_SRV/SurveySet(1)/ToQuestions

ABAP part

Assuming you have used Gateway Service Generation to implement your project, you will have to add a mandatory importing parameter in the function module which fetches your questions (the one mapped with the GetEntitySet operation of QuestionSet). This parameter will represent the ID of a survey. You will have also to map the SurveyId property with the imporing parameter. So you will have two rows in your mappings for SurveyId Propety. One row will have an arrow pointing to the right (for the importing parameter), and the other will have an arrow pointing to the left (for the survey id column of the exported internal table)

Assuming you have not used service generation but service implementation (when you manually develop your ABAP code in DPC_EXT class) you will need to read the survey id using the following method call:

io_tech_request_context->get_converted_keys(
  IMPORTING
    es_key_values = ls_converted_keys ).

UI5 part

You will also have to do a minor fix in your UI5 code.

Apart from using your second entity set in the list aggregation binding, like this...

<List  items="{path:'/QuestionSet', templateShareable:true}" >

You will have to use the exact name of your navigation property

<List  items="{path:'/ToQuestions' }" >

or just

<List  items="{/ToQuestions}" >

I bet templateShareable is not needed in your scenario.

So, the detail page will be binded with '/SurveySet(1)' because you already have a call to .bindElement method

this._bindView("/" + sObjectPath);

So relative to this binding, your question table will be binded to /ToQuestions navigation property.


问:
Virtual host not working in zend framework
Following is my virtual host in /etc/apache2/sites-available:

```<code><VirtualHost *:80>

DocumentRoot "/var/www/roomstays/public"

ServerName roomstays

#This should be omitted in the production environment
SetEnv APPLICATION_ENV development

<Directory "/var/www/roomstays/public">
Options Indexes MultiViews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>

</VirtualHost>
</code>```

Also it enabled on /etc/apache2/sites-enabled folder

And following is my host file:

```<code>127.0.0.1   localhost
127.0.0.1   roomstays

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
</code>```

I configured my site in var/www/roomstays. But when I entered roomstays on it not opening the site and showing this message :

It works!

This is the default web page for this server.

The web server software is running but no content has been added, yet.

What's wrong with virtual host.

答:
Be sure that # Virtual hosts line is active in your httpd.conf file.

Generally, it places under: /etc/apache2/httpd.conf

To edit the file you need root permission, so:

```<code>sudo vim /etc/apache2/httpd.conf
</code>```

Uncomment the line

```<code>Include /private/etc/apache2/extra/httpd-vhosts.conf
</code>```

Save file ESC + :wq + Enter

Restart your apache

Body:
Following is my virtual host in /etc/apache2/sites-available:

<VirtualHost *:80>

DocumentRoot "/var/www/roomstays/public"

ServerName roomstays

#This should be omitted in the production environment
SetEnv APPLICATION_ENV development

<Directory "/var/www/roomstays/public">
Options Indexes MultiViews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>

</VirtualHost>

Also it enabled on /etc/apache2/sites-enabled folder

And following is my host file:

127.0.0.1   localhost
127.0.0.1   roomstays

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

I configured my site in var/www/roomstays. But when I entered roomstays on it not opening the site and showing this message :

It works!

This is the default web page for this server.

The web server software is running but no content has been added, yet.

What's wrong with virtual host.

Body:
Be sure that # Virtual hosts line is active in your httpd.conf file.

Generally, it places under: /etc/apache2/httpd.conf

To edit the file you need root permission, so:

sudo vim /etc/apache2/httpd.conf

Uncomment the line

Include /private/etc/apache2/extra/httpd-vhosts.conf

Save file ESC + :wq + Enter

Restart your apache


问:
fopen fails invisibly when creating files in system drive (C:\)
Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file.  My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any errors?

Any idea how to tell if there's an error or not?  The file handle that gets returned when I'm trying to open the file in a protected directory is exactly the same as when I open a file in a directory where I have write access.

I've tried this with the various different versions of fopen (fopen, _wfopen, _wfopen_s) but they all have the same output.

Interestingly enough, GetLastError() returns ERROR_ALREADY_EXISTS.

Here's the code that I'm using:

```<code>FILE *FileHandle;
DWORD error = _wfopen_s(&FileHandle, L"\\filename.txt", L"a");
Win32Error = GetLastError();

if (error != 0 || FileHandle == NULL)
{
    //Throw error
}
else
{
    //write to file
    //close file
}
</code>```

EDIT: As rerun pointed out, the file is getting created in %APPDATA% because of virtualization.  Does anyone know how to disable this feature?

答:
We had a similar problem in registry virtualization, yes it is also virtualized after Vista.

Our solution was Properties->Linker->Manifest File->UAC Execution Level-> requireAdministrator. IMHO, It may work for your case also.

ContentLicense: CC BY-SA 2.5

Body:
Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file.  My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any errors?

Any idea how to tell if there's an error or not?  The file handle that gets returned when I'm trying to open the file in a protected directory is exactly the same as when I open a file in a directory where I have write access.

I've tried this with the various different versions of fopen (fopen, _wfopen, _wfopen_s) but they all have the same output.

Interestingly enough, GetLastError() returns ERROR_ALREADY_EXISTS.

Here's the code that I'm using:

FILE *FileHandle;
DWORD error = _wfopen_s(&FileHandle, L"\\filename.txt", L"a");
Win32Error = GetLastError();

if (error != 0 || FileHandle == NULL)
{
    //Throw error
}
else
{
    //write to file
    //close file
}

EDIT: As rerun pointed out, the file is getting created in %APPDATA% because of virtualization.  Does anyone know how to disable this feature?


问:
why mapping result is undefined?
I'm trying get jSon from server and mapping it to the class in Angular 5 app.
Following is service method that working without errors:

```<code>getSearchResultTable(hash: number): Observable<Model.SearchResult.RootObject> {

    return this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .map(res => new Model.SearchResult.RootObject());
    return tmp;
}
</code>```

following comoponent class:

```<code>export class SearchResultPageComponent implements OnInit {
  searchResult: Model.SearchResult.RootObject;

  constructor(private searchResultService: SearchResultService, private router: Router) { }

  ngOnInit(): void {
    this.searchResultService.getSearchResultTable(122).subscribe( data => {
      this.searchResult = data;
    });
    let t = this.searchResult;
  }
}
</code>```

The Model.SearchResult.RootObject is an complex object and i generate it by jSon on following service.

In all examples this method is described...but in my case this.searchResult is undefined. What i'm doing wrong?

UPDATE

Also I tried remove map and change the service method in a way:

```<code>getSearchResultTable(hash: number): Model.SearchResult.RootObject {
this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .subscribe( data => {
        this.searchResult = data;
      });
    return this.searchResult;
}
</code>```

And component method like:

```<code>  ngOnInit(): void {
    this.searchResult = this.searchResultService.getSearchResultTable(122);
    }
</code>```

Service get next exception:

ReferenceError: data is not defined

at eval (eval at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts),
:1:1)

at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts:27:21)

at SearchResultPageComponent.ngOnInit (webpack-internal:///../../../../../src/app/search-module/pages/search-result/search-result.component.ts:23:54)

at checkAndUpdateDirectiveInline (webpack-internal:///../../../core/esm5/core.js:12291:19)

at checkAndUpdateNodeInline (webpack-internal:///../../../core/esm5/core.js:13794:20)

at checkAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:13737:16)

at debugCheckAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:14609:76)

at debugCheckDirectivesFn (webpack-internal:///../../../core/esm5/core.js:14550:13)

at Object.eval [as updateDirectives] (ng:///SearchModule/SearchResultPageComponent_Host.ngfactory.js:9:5)

at Object.debugUpdateDirectives [as updateDirectives] (webpack-internal:///../../../core/esm5/core.js:14535:21)

UPDATE

In my case following snippet is correct:

```<code>this.http.get<Model.SearchResult.RootObject>('http://someurl/api/SearchResult/123')
.subscribe( (data: Model.SearchResult.RootObject) => {
    this.searchResult = data;
  });
return this.searchResult;
</code>```

答:
Let me explain you by example:
this is my service(Postman) returning data in json format.

Now this my component's method--getdata which is calling the service method

```<code>getdata() {
    this.apiHelperService.getdata().subscribe(domainres => {
      // this.domain = domainres,
      this.msg = JSON.stringify(domainres);//,
      // this.availabilty = this.domain.Available
    }
      , error => { this.msg = "Error function: " + error; })

  }
</code>```

Now this is my service :

```<code>import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

@Injectable()
export class ApiHelperService {
    constructor(private _http: Http) { }

    getdata( ): Observable<any> {

        return this._http.get("http://localhost:8080/domain/facebookjhjhj.com")
            .map((response: Response) => <any>response.json())
            .do(data => console.log("All: " + JSON.stringify(data)))
            .catch(this.handleError);
    }
    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}
</code>```

and I am getting the result like this on browser:

If I comment the map() line then then my output is like this.

Now coming to your question Look at this line, You are not converting res to anything,

```<code>.map(res => new Model.SearchResult.RootObject());
</code>```

Try this :

```<code>.map(res => <new Model.SearchResult.RootObject()>response.json());
</code>```

Title: why mapping result is undefined?

Body:
I'm trying get jSon from server and mapping it to the class in Angular 5 app.
Following is service method that working without errors:

getSearchResultTable(hash: number): Observable<Model.SearchResult.RootObject> {

    return this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .map(res => new Model.SearchResult.RootObject());
    return tmp;
}

following comoponent class:

export class SearchResultPageComponent implements OnInit {
  searchResult: Model.SearchResult.RootObject;

  constructor(private searchResultService: SearchResultService, private router: Router) { }

  ngOnInit(): void {
    this.searchResultService.getSearchResultTable(122).subscribe( data => {
      this.searchResult = data;
    });
    let t = this.searchResult;
  }
}

The Model.SearchResult.RootObject is an complex object and i generate it by jSon on following service.

In all examples this method is described...but in my case this.searchResult is undefined. What i'm doing wrong?

UPDATE

Also I tried remove map and change the service method in a way:

getSearchResultTable(hash: number): Model.SearchResult.RootObject {
this.http.get<Model.SearchResult.RootObject>('http://somelink/api/SearchResult/123')
    .subscribe( data => {
        this.searchResult = data;
      });
    return this.searchResult;
}

And component method like:

  ngOnInit(): void {
    this.searchResult = this.searchResultService.getSearchResultTable(122);
    }

Service get next exception:

ReferenceError: data is not defined

at eval (eval at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts),
:1:1)

at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts:27:21)

at SearchResultPageComponent.ngOnInit (webpack-internal:///../../../../../src/app/search-module/pages/search-result/search-result.component.ts:23:54)

at checkAndUpdateDirectiveInline (webpack-internal:///../../../core/esm5/core.js:12291:19)

at checkAndUpdateNodeInline (webpack-internal:///../../../core/esm5/core.js:13794:20)

at checkAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:13737:16)

at debugCheckAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:14609:76)

at debugCheckDirectivesFn (webpack-internal:///../../../core/esm5/core.js:14550:13)

at Object.eval [as updateDirectives] (ng:///SearchModule/SearchResultPageComponent_Host.ngfactory.js:9:5)

at Object.debugUpdateDirectives [as updateDirectives] (webpack-internal:///../../../core/esm5/core.js:14535:21)

UPDATE

In my case following snippet is correct:

this.http.get<Model.SearchResult.RootObject>('http://someurl/api/SearchResult/123')
.subscribe( (data: Model.SearchResult.RootObject) => {
    this.searchResult = data;
  });
return this.searchResult;

Body:
Let me explain you by example:
this is my service(Postman) returning data in json format.

Now this my component's method--getdata which is calling the service method

getdata() {
    this.apiHelperService.getdata().subscribe(domainres => {
      // this.domain = domainres,
      this.msg = JSON.stringify(domainres);//,
      // this.availabilty = this.domain.Available
    }
      , error => { this.msg = "Error function: " + error; })

  }

Now this is my service :

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

@Injectable()
export class ApiHelperService {
    constructor(private _http: Http) { }

    getdata( ): Observable<any> {

        return this._http.get("http://localhost:8080/domain/facebookjhjhj.com")
            .map((response: Response) => <any>response.json())
            .do(data => console.log("All: " + JSON.stringify(data)))
            .catch(this.handleError);
    }
    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

and I am getting the result like this on browser:

If I comment the map() line then then my output is like this.

Now coming to your question Look at this line, You are not converting res to anything,

.map(res => new Model.SearchResult.RootObject());

Try this :

.map(res => <new Model.SearchResult.RootObject()>response.json());


答:
You need to initialize char pointer name before can point it to a String entered by user.

```<code>#include<stdio.h>
struct Employee
{
    char *name;
    int salary;
};

int main()
{
    struct Employee emp[3];

    int i;
    for(i=0;i<3;i++)
    {
        emp[i].name = (char*)malloc(3);
        scanf("%s%d",emp[i].name,&emp[i].salary);
    }
    printf("\nOutput:");
    for(i=0;i<3;i++)
    {
        printf("\n%s%d",emp[i].name,emp[i].salary);
    }

    return 0;
}
</code>```

Title: Input string to a char pointer member of an array of structure

Body:
You need to initialize char pointer name before can point it to a String entered by user.

#include<stdio.h>
struct Employee
{
    char *name;
    int salary;
};

int main()
{
    struct Employee emp[3];

    int i;
    for(i=0;i<3;i++)
    {
        emp[i].name = (char*)malloc(3);
        scanf("%s%d",emp[i].name,&emp[i].salary);
    }
    printf("\nOutput:");
    for(i=0;i<3;i++)
    {
        printf("\n%s%d",emp[i].name,emp[i].salary);
    }

    return 0;
}


问:
detail about javascript callbacks
I am curious about something, imagine a link that closes the window. See the code below, and read the comments:

```<code>var a = document.querySelector('a');

//
// Since a.onclick requires a callback I have the following code:
//

a.onclick = function() { window.close() }; // This works fine.
a.onclick = function() { close() }; // This works as well.
a.onclick = () => { close() }; // This also work.
a.onclick = () => close(); // This works.

// But...

a.onclick = window.close; // This doesn't work.
a.onclick = close; // Neither this.

// But, why not?? Since onclick requires a function, and window.close is a
// function and close is just the shorten way to call window.close?

// However...

a.onclick = close.bind(); // This works fine....
</code>```

So fellows, since onclick receives a function, why to set just "close" does not do the job? It should "register" the function close (window.close) as the "callback" for that action, and call it when the event was triggered (like close.call());

I really don't understand this behavior

答:
It's all about the binding of the method to its this. When you have a Function reference to a method, then call it, it won't "know" which object the method belongs to (this will no-longer be a Window), so if .close() needs to know about its window object, the function call will fail.

bind works around this by fixing this to a particular object:

```<code>a.onclick = window.close.bind(window);
</code>```

Title: detail about javascript callbacks

Body:
I am curious about something, imagine a link that closes the window. See the code below, and read the comments:

var a = document.querySelector('a');

//
// Since a.onclick requires a callback I have the following code:
//

a.onclick = function() { window.close() }; // This works fine.
a.onclick = function() { close() }; // This works as well.
a.onclick = () => { close() }; // This also work.
a.onclick = () => close(); // This works.

// But...

a.onclick = window.close; // This doesn't work.
a.onclick = close; // Neither this.

// But, why not?? Since onclick requires a function, and window.close is a
// function and close is just the shorten way to call window.close?

// However...

a.onclick = close.bind(); // This works fine....

So fellows, since onclick receives a function, why to set just "close" does not do the job? It should "register" the function close (window.close) as the "callback" for that action, and call it when the event was triggered (like close.call());

I really don't understand this behavior

Body:
It's all about the binding of the method to its this. When you have a Function reference to a method, then call it, it won't "know" which object the method belongs to (this will no-longer be a Window), so if .close() needs to know about its window object, the function call will fail.

bind works around this by fixing this to a particular object:

a.onclick = window.close.bind(window);


问:
Flask test client using GET request instead of POST
I have a route for only POST request and it returns json response if conditions are met. It's something like this:

```<code>@app.route('/panel', methods=['POST'])
def post_panel():
    # Check for conditions and database operations
    return jsonify({"message": "Panel added to database!"
                    "success": 1})
</code>```

I am using flask-sslify to force http requests to https.

I am testing this route with Flask test client and unittest. The test function is similar to following:

```<code>class TestAPI2_0(unittest.TestCase):
    def setUp(self):
    self.app = create_app('testing')
    self.app_context = self.app.app_context()
    self.app_context.push()
    db.create_all()
    create_fake_data(db)
    self.client = self.app.test_client()

    def tearDown(self):
        ....

    def test_post_panel_with_good_data(self):
        # data
        r = self.client.post('/panel',
                            data=json.dumps(data),
                            follow_redirects=True)
        print(r.data)
        self.assertEqual(r.status_code, 200)
</code>```

Output is exactly below:

```<code>test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n'

======================================================================
FAIL: test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/tanjibpa/work/craftr-master/tests/test_api_2_0.py", line 110, in test_post_panel_with_good_data
    self.assertEqual(r.status_code, 200)
AssertionError: 405 != 200
</code>```

I am getting an error that Method is not allowed in that route.
If I specify GET as a method (methods=['GET', 'POST']) for the route test seems to work. But why test client is making a GET request? Is there any way around rather than specifying a GET request for the route?

Update:

If do it like this:

```<code>@app.route('/panel', methods=['GET', 'POST'])
def post_panel():
    if request.method == 'POST':
        # Check for conditions and database operations
        return jsonify({"message": "Panel added to database!"
                        "success": 1})
    return jsonify({"message": "GET request"})
</code>```

I get output like this:

```<code>test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'{\n  "message": "GET request"\n}\n'
</code>```

答:
I found out what was causing the GET request within flask test client.
I am using flask-sslify to force http requests to https.
Somehow flask-sslify is enforcing a GET request although test client is specified with other kind of requests (POST, PUT, DELETE...). </p>

<p>So, If I disable sslify during testing flask test client works as it should. </p>

Body:
I have a route for only POST request and it returns json response if conditions are met. It's something like this:

@app.route('/panel', methods=['POST'])
def post_panel():
    # Check for conditions and database operations
    return jsonify({"message": "Panel added to database!"
                    "success": 1})

I am using flask-sslify to force http requests to https.

I am testing this route with Flask test client and unittest. The test function is similar to following:

class TestAPI2_0(unittest.TestCase):
    def setUp(self):
    self.app = create_app('testing')
    self.app_context = self.app.app_context()
    self.app_context.push()
    db.create_all()
    create_fake_data(db)
    self.client = self.app.test_client()

    def tearDown(self):
        ....

    def test_post_panel_with_good_data(self):
        # data
        r = self.client.post('/panel',
                            data=json.dumps(data),
                            follow_redirects=True)
        print(r.data)
        self.assertEqual(r.status_code, 200)

Output is exactly below:

test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>405 Method Not Allowed</title>\n
Method Not Allowed
\n
The method is not allowed for the requested URL.
\n'

======================================================================
FAIL: test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/tanjibpa/work/craftr-master/tests/test_api_2_0.py", line 110, in test_post_panel_with_good_data
    self.assertEqual(r.status_code, 200)
AssertionError: 405 != 200

I am getting an error that Method is not allowed in that route.
If I specify GET as a method (methods=['GET', 'POST']) for the route test seems to work. But why test client is making a GET request? Is there any way around rather than specifying a GET request for the route?

Update:

If do it like this:

@app.route('/panel', methods=['GET', 'POST'])
def post_panel():
    if request.method == 'POST':
        # Check for conditions and database operations
        return jsonify({"message": "Panel added to database!"
                        "success": 1})
    return jsonify({"message": "GET request"})

I get output like this:

test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'{\n  "message": "GET request"\n}\n'

Body:
I found out what was causing the GET request within flask test client.
I am using flask-sslify to force http requests to https.
Somehow flask-sslify is enforcing a GET request although test client is specified with other kind of requests (POST, PUT, DELETE...).

So, If I disable sslify during testing flask test client works as it should.


问:
Remove All Styles and Indent from Ordered List
How do I remove the indent and style of an ordered list, so that it behaves like regular text?

Example:

```<code>   1. Item
   1. Item
   [...]
1000. Item
</code>```

Should look like this:

```<code>1. Item
2. Item
[...]
1000. Item 100
</code>```

Code:

```<code><ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>
</code>```

Thanks!

答:
You can try to put display css property for example to inline-block

li{
display:inline-block;
}

li{
display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol></code>```

Body:
How do I remove the indent and style of an ordered list, so that it behaves like regular text?

Example:

   1. Item
   1. Item
   [...]
1000. Item

Should look like this:

1. Item
2. Item
[...]
1000. Item 100

Code:

Item

Item

Item

Thanks!

Body:
You can try to put display css property for example to inline-block

li{
display:inline-block;
}

li{
display:inline-block;
}

<ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>


问:
Textview size needs to change according to user's given value in EditText
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

```<code>     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks
</code>```

答:
One way to resolve your issue is by attaching a listener to the editText box.

Here's an example TextWatcher implementation:

```<code>edittext.addTextChangedListener(new TextWatcher() {

   public void onTextChanged(CharSequence s, int start, int before,
        int count) {
       if(!s.equals("") )
            { //do your work here }
       }

   }

   public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {

   }

   public void afterTextChanged(Editable s) {

   }
});
</code>```

You can have a little size check inside onTextChanged. Once it reaches a certain breakpoint, you increase the size of the text. :-)

Body:
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks

Body:
One way to resolve your issue is by attaching a listener to the editText box.

Here's an example TextWatcher implementation:

edittext.addTextChangedListener(new TextWatcher() {

   public void onTextChanged(CharSequence s, int start, int before,
        int count) {
       if(!s.equals("") )
            { //do your work here }
       }

   }

   public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {

   }

   public void afterTextChanged(Editable s) {

   }
});

You can have a little size check inside onTextChanged. Once it reaches a certain breakpoint, you increase the size of the text. :-)


问:
show pop up when is mouse over image control
I would like show pop up when is mouse over the image control.  So I create control template, it look like this:

```<code>        <ControlTemplate x:Key="AvatarImageTemplate" TargetType="{x:Type Image}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>

                <HERE I WANT IMAGE SOURCE  Grid.Row="0"/>
                <Popup  IsOpen="False"
                            Name="OponentImagePopUp"
                            AllowsTransparency="True"
                            PopupAnimation="Slide"
                            HorizontalOffset="-35"
                            VerticalOffset="0"
                            Grid.Row="1">
                    <Border BorderThickness="1"
                                BorderBrush="Black">
                        <Grid  Height="350" MinWidth="350">
                            <Grid.Background>
                                <LinearGradientBrush StartPoint="0,0" EndPoint="0,0.3">
                                    <LinearGradientBrush.GradientStops>
                                        <GradientStop Color="LightGray" Offset="0"/>
                                        <GradientStop Color="WhiteSmoke" Offset="1"/>
                                    </LinearGradientBrush.GradientStops>
                                </LinearGradientBrush>
                            </Grid.Background>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="75"></ColumnDefinition>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"></RowDefinition>
                            </Grid.RowDefinitions>

                            <Border BorderThickness="1"
                                    BorderBrush="Black"
                                    Background="White"
                                    Margin="4,4,4,4"
                                    Grid.Column="0">
                                <Image Margin="2,2,2,2">
                                    <Image.Source >
                                        <MultiBinding Converter="{StaticResource avatarConverter}">
                                            <Binding Path="ProfilePhoto"></Binding>
                                            <Binding Path="StatusInfo.IsLogged"></Binding>
                                        </MultiBinding>
                                    </Image.Source>
                                </Image>
                            </Border>
                        </Grid>
                    </Border>
                </Popup>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="OponentImagePopUp" Property="IsOpen" Value="True" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
</code>```

I have two problems:

I don’t how can I acces to image source in control template

Also If I try make a style on Image control and set property Template -> Image control don’t have a property template.

My aim is show pop pop window with same image only bigger.

EDIT:

I create simple control, as advice Mr. Glazkov, which have image control, here is it:

```<code><UserControl x:Class="Spirit.Controls.AvatarImageControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Image x:Name="SmallImage"
            Source="{Binding ElementName=root, Path=ImageSource}"
            Stretch="Fill"/>
    </Grid>
</UserControl>
</code>```

Code behind is the same:

```<code>  public partial class AvatarImageControl : UserControl
    {
        public AvatarImageControl()
        {
            InitializeComponent();
        }

        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(AvatarImageControl), new UIPropertyMetadata(null));

    }
</code>```

I try use this contol in view:

```<code><Grid Background="#99CCFF"  Margin="4,4,4,4">
      <Controls:AvatarImageControl ImageSource="{Binding Path=Oponent.Info.ProfilePhoto,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</code>```

I bind property type of Uri to ImageSource of AvatarImageControl.

What I do bad?

Also I try this in user control:

```<code><Grid>
    <Image x:Name="SmallImage"
        Source="{Binding Path=ImageSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
        Stretch="Fill"/>
</Grid>
</code>```

Result is same.

I use user control in view, I bind on ImageSource property property from view model type of Uri. Nothing else.

EDIT 2:
Code of Mr. Glazkov produce exception:

```<code>{"Set property 'System.Windows.Controls.Primitives.Popup.IsOpen' threw an exception."}
{"A TwoWay or OneWayToSource binding cannot work on the read-only property 'IsMouseOver' of type 'System.Windows.Controls.Image'."}
StackTrace:
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at Spirit.Controls.AvatarImageControl.InitializeComponent() in c:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml:line 1
   at Spirit.Controls.AvatarImageControl..ctor() in C:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml.cs:line 24
</code>```

Solution is :

```<code> <Popup IsOpen="{Binding ElementName=SmallImage, Path=IsMouseOver, Mode=OneWay}">
</code>```

Set binding mode  on oneway.

It works good.

Thank Mr. Glazkov for help.

答:
You cannot define a control template for the image control because it is not derived from Control, thus it doesn't have a control template. It just renders itself in the OnRender method.

What you can do is to create a User Control with one dependency property ImageSource. Here is the XAML of this control:

```<code><UserControl x:Class="AvatarImage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Name="root">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <Image x:Name="SmallImage"
               Source="{Binding ElementName=root, Path=ImageSource}"
               Grid.Row="0" />
        <Popup IsOpen="{Binding ElementName=SmallImage, Path=IsMouseOver, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
               Name="OponentImagePopUp"
               AllowsTransparency="True"
               PopupAnimation="Slide"
               HorizontalOffset="-35"
               VerticalOffset="0"
               Grid.Row="1">
            <Border BorderThickness="1"
                    BorderBrush="Black">
                <Grid Height="350"
                      MinWidth="350">
                    <Grid.Background>
                        <LinearGradientBrush StartPoint="0,0"
                                             EndPoint="0,0.3">
                            <LinearGradientBrush.GradientStops>
                                <GradientStop Color="LightGray"
                                              Offset="0" />
                                <GradientStop Color="WhiteSmoke"
                                              Offset="1" />
                            </LinearGradientBrush.GradientStops>
                        </LinearGradientBrush>
                    </Grid.Background>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="75"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"></RowDefinition>
                    </Grid.RowDefinitions>

                    <Border BorderThickness="1"
                            BorderBrush="Black"
                            Background="White"
                            Margin="4,4,4,4"
                            Grid.Column="0">
                        <Image Margin="2,2,2,2">
                            <Image.Source>
                                <MultiBinding Converter="{StaticResource avatarConverter}">
                                    <Binding Path="ProfilePhoto"></Binding>
                                    <Binding Path="StatusInfo.IsLogged"></Binding>
                                </MultiBinding>
                            </Image.Source>
                        </Image>
                    </Border>
                </Grid>
            </Border>
        </Popup>
    </Grid>
</UserControl>
</code>```

And here is the code behind (AvatarImage.xaml.cs):

```<code>public partial class AvatarImage : UserControl
{
    public AvatarImage() {
        InitializeComponent();
    }

    public ImageSource ImageSource {
        get { return (ImageSource)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }

    public static readonly DependencyProperty ImageSourceProperty =
        DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(AvatarImage), new UIPropertyMetadata(null));
}
</code>```

Body:
I would like show pop up when is mouse over the image control.  So I create control template, it look like this:

        <ControlTemplate x:Key="AvatarImageTemplate" TargetType="{x:Type Image}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>

                <HERE I WANT IMAGE SOURCE  Grid.Row="0"/>
                <Popup  IsOpen="False"
                            Name="OponentImagePopUp"
                            AllowsTransparency="True"
                            PopupAnimation="Slide"
                            HorizontalOffset="-35"
                            VerticalOffset="0"
                            Grid.Row="1">
                    <Border BorderThickness="1"
                                BorderBrush="Black">
                        <Grid  Height="350" MinWidth="350">
                            <Grid.Background>
                                <LinearGradientBrush StartPoint="0,0" EndPoint="0,0.3">
                                    <LinearGradientBrush.GradientStops>
                                        <GradientStop Color="LightGray" Offset="0"/>
                                        <GradientStop Color="WhiteSmoke" Offset="1"/>
                                    </LinearGradientBrush.GradientStops>
                                </LinearGradientBrush>
                            </Grid.Background>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="75"></ColumnDefinition>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"></RowDefinition>
                            </Grid.RowDefinitions>

                            <Border BorderThickness="1"
                                    BorderBrush="Black"
                                    Background="White"
                                    Margin="4,4,4,4"
                                    Grid.Column="0">
                                <Image Margin="2,2,2,2">
                                    <Image.Source >
                                        <MultiBinding Converter="{StaticResource avatarConverter}">
                                            <Binding Path="ProfilePhoto"></Binding>
                                            <Binding Path="StatusInfo.IsLogged"></Binding>
                                        </MultiBinding>
                                    </Image.Source>
                                </Image>
                            </Border>
                        </Grid>
                    </Border>
                </Popup>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="OponentImagePopUp" Property="IsOpen" Value="True" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

I have two problems:

I don’t how can I acces to image source in control template

Also If I try make a style on Image control and set property Template -> Image control don’t have a property template.

My aim is show pop pop window with same image only bigger.

EDIT:

I create simple control, as advice Mr. Glazkov, which have image control, here is it:

<UserControl x:Class="Spirit.Controls.AvatarImageControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Image x:Name="SmallImage"
            Source="{Binding ElementName=root, Path=ImageSource}"
            Stretch="Fill"/>
    </Grid>
</UserControl>

Code behind is the same:

  public partial class AvatarImageControl : UserControl
    {
        public AvatarImageControl()
        {
            InitializeComponent();
        }

        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(AvatarImageControl), new UIPropertyMetadata(null));

    }

I try use this contol in view:

<Grid Background="#99CCFF"  Margin="4,4,4,4">
      <Controls:AvatarImageControl ImageSource="{Binding Path=Oponent.Info.ProfilePhoto,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

I bind property type of Uri to ImageSource of AvatarImageControl.

What I do bad?

Also I try this in user control:

<Grid>
    <Image x:Name="SmallImage"
        Source="{Binding Path=ImageSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
        Stretch="Fill"/>
</Grid>

Result is same.

I use user control in view, I bind on ImageSource property property from view model type of Uri. Nothing else.

EDIT 2:
Code of Mr. Glazkov produce exception:

{"Set property 'System.Windows.Controls.Primitives.Popup.IsOpen' threw an exception."}
{"A TwoWay or OneWayToSource binding cannot work on the read-only property 'IsMouseOver' of type 'System.Windows.Controls.Image'."}
StackTrace:
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at Spirit.Controls.AvatarImageControl.InitializeComponent() in c:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml:line 1
   at Spirit.Controls.AvatarImageControl..ctor() in C:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml.cs:line 24

Solution is :

 <Popup IsOpen="{Binding ElementName=SmallImage, Path=IsMouseOver, Mode=OneWay}">

Set binding mode  on oneway.

It works good.

Thank Mr. Glazkov for help.

Body:
You cannot define a control template for the image control because it is not derived from Control, thus it doesn't have a control template. It just renders itself in the OnRender method.

What you can do is to create a User Control with one dependency property ImageSource. Here is the XAML of this control:

<UserControl x:Class="AvatarImage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Name="root">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <Image x:Name="SmallImage"
               Source="{Binding ElementName=root, Path=ImageSource}"
               Grid.Row="0" />
        <Popup IsOpen="{Binding ElementName=SmallImage, Path=IsMouseOver, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
               Name="OponentImagePopUp"
               AllowsTransparency="True"
               PopupAnimation="Slide"
               HorizontalOffset="-35"
               VerticalOffset="0"
               Grid.Row="1">
            <Border BorderThickness="1"
                    BorderBrush="Black">
                <Grid Height="350"
                      MinWidth="350">
                    <Grid.Background>
                        <LinearGradientBrush StartPoint="0,0"
                                             EndPoint="0,0.3">
                            <LinearGradientBrush.GradientStops>
                                <GradientStop Color="LightGray"
                                              Offset="0" />
                                <GradientStop Color="WhiteSmoke"
                                              Offset="1" />
                            </LinearGradientBrush.GradientStops>
                        </LinearGradientBrush>
                    </Grid.Background>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="75"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"></RowDefinition>
                    </Grid.RowDefinitions>

                    <Border BorderThickness="1"
                            BorderBrush="Black"
                            Background="White"
                            Margin="4,4,4,4"
                            Grid.Column="0">
                        <Image Margin="2,2,2,2">
                            <Image.Source>
                                <MultiBinding Converter="{StaticResource avatarConverter}">
                                    <Binding Path="ProfilePhoto"></Binding>
                                    <Binding Path="StatusInfo.IsLogged"></Binding>
                                </MultiBinding>
                            </Image.Source>
                        </Image>
                    </Border>
                </Grid>
            </Border>
        </Popup>
    </Grid>
</UserControl>

And here is the code behind (AvatarImage.xaml.cs):

public partial class AvatarImage : UserControl
{
    public AvatarImage() {
        InitializeComponent();
    }

    public ImageSource ImageSource {
        get { return (ImageSource)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }

    public static readonly DependencyProperty ImageSourceProperty =
        DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(AvatarImage), new UIPropertyMetadata(null));
}