问:
Loading Image Gallery taking too time in Razor View
I use a image gallery plugin called Unite Gallery plugin in an ASP.NET MVC project in order to display images stored in database. However, loading all of the images at the same time takes too long time (because each photo is in 1MB-4MB size and loading 500 photos at the same time on page load is not a good idea) and I think there must be a better approach i.e. asenkron loading or partial loading.  Here is my Razor and Controller code. I have a look at many pages on the wweb and docs, but there is not an example in the documentation page. Do you have any idea?

```<code><div id="gallery" style="display:none;">

    @foreach (var item in Model)
    {
        if (item.FileData != null)
        {
            var base64 = Convert.ToBase64String(item.FileData);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

            <img alt='Image'
                    src="@imgSrc"
                    data-image="@imgSrc"
                    data-description='Image'>
        }
    }
</div>

<script type="text/javascript">

    jQuery(document).ready(function () {
    var gallery = jQuery("#gallery").unitegallery({
        gallery_theme: "default" //theme skin
    });

    gallery.on("item_change", function (num, data) {
        if((num%15) == 0)
        {
            $.ajax({
                url: '@Url.Action("List", "PhotoContest")',
                data: { isAll: isAllChecked, page: num }, //??? I pass the page parameter???
              success: function(data){
                //call is successfully completed and we got result in data

                //??? NO IDEA ???

              },
              error:function (xhr, ajaxOptions, thrownError){
                              //some errror, some show err msg to user and log the error
                              alert(xhr.responseText);
                            }
              });
        }
    });

});

</script>

public ActionResult List(string query)
{
    var model = db.Photo.Select(m => new PhotoViewModel
    {
        Id = m.Id,
        Name = m.Name,
        StatusId = m.StatusId,
        SubmitDate = m.SubmitDate,
        FileAttachments = m.FileAttachments,
        SubmitNo = m.SubmitNo
    })
    .ToArray();

    return View("List", model);
}
</code>```

Update:

After trying to apply @Kris's perfect approach, I encountered the error shown below. There is not a fix or solution regarding to this specific problem on the web. Any idea?

The image after page load overloads div and gallery borders as shown below:

答:
Load 30 images at a time

Load remaining in Itemchange event available in Unite gallery

Main Page

```<code><div id="gallery" >
<input type="hidden" id="galleryPage" value="0"/>
@HTML.Action("GalleryImages") //first load 30 items as PageNo = 0
</div>

<script type="text/javascript">
var gallery;
    jQuery(document).ready(function () {
    gallery = jQuery("#gallery").unitegallery({
        gallery_theme: "default" //theme skin
    });

    gallery.on("item_change", function (num, data) {
      //when item loaded equals to 15 or 30 or multiples of 15 another 30 items get loaded
        if((num%15) == 0)
        {
            $.ajax({
                url: '@HTML.Action("GalleryImages")'+"?pageNo="+jQuery("galleryPage").val(),
                data: { isAll: isAllChecked },
              success: function(data){
               jQuery("gallery").append(data);//partial view with new images
               jQuery("galleryPage").val(gallery.getNumItems()/30); //page number total items/number of items per page
              },
              error:function (xhr, ajaxOptions, thrownError){
                              //some errror, some show err msg to user and log the error
                              alert(xhr.responseText);
                            }
              });
        }
    });

});

</script>
</code>```

Partial View (_galleryImages.cshtml)

```<code>@foreach (var item in Model)
    {
        if (item.FileData != null)
        {
            var base64 = Convert.ToBase64String(item.FileData);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

            <img alt='Image'
                    src="@imgSrc"
                    data-image="@imgSrc"
                    data-description='Image'>
        }
    }
</code>```

Controller

```<code> //Main View
    public ActionResult List()
    {
            return View();
    }

//Partial View
public Action GalleryImages(int PageNo)
{
    int PageSize = 30;
     var model = db.Photo.Select(m => new PhotoViewModel
    {
        Id = m.Id,
        Name = m.Name,
        StatusId = m.StatusId,
        SubmitDate = m.SubmitDate,
        FileAttachments = m.FileAttachments,
        SubmitNo = m.SubmitNo
    }).Skip(PageNo*PageSize).Take(PageSize).ToArray();

    return PartialView("_galleryImages", model);
}
</code>```

Body:
I use a image gallery plugin called Unite Gallery plugin in an ASP.NET MVC project in order to display images stored in database. However, loading all of the images at the same time takes too long time (because each photo is in 1MB-4MB size and loading 500 photos at the same time on page load is not a good idea) and I think there must be a better approach i.e. asenkron loading or partial loading.  Here is my Razor and Controller code. I have a look at many pages on the wweb and docs, but there is not an example in the documentation page. Do you have any idea?

    @foreach (var item in Model)
    {
        if (item.FileData != null)
        {
            var base64 = Convert.ToBase64String(item.FileData);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

        }
    }

public ActionResult List(string query)
{
    var model = db.Photo.Select(m => new PhotoViewModel
    {
        Id = m.Id,
        Name = m.Name,
        StatusId = m.StatusId,
        SubmitDate = m.SubmitDate,
        FileAttachments = m.FileAttachments,
        SubmitNo = m.SubmitNo
    })
    .ToArray();

    return View("List", model);
}

Update:

After trying to apply @Kris's perfect approach, I encountered the error shown below. There is not a fix or solution regarding to this specific problem on the web. Any idea?

The image after page load overloads div and gallery borders as shown below:

Body:
Load 30 images at a time

Load remaining in Itemchange event available in Unite gallery

Main Page

<div id="gallery" >
<input type="hidden" id="galleryPage" value="0"/>
@HTML.Action("GalleryImages") //first load 30 items as PageNo = 0
</div>

<script type="text/javascript">
var gallery;
    jQuery(document).ready(function () {
    gallery = jQuery("#gallery").unitegallery({
        gallery_theme: "default" //theme skin
    });

    gallery.on("item_change", function (num, data) {
      //when item loaded equals to 15 or 30 or multiples of 15 another 30 items get loaded
        if((num%15) == 0)
        {
            $.ajax({
                url: '@HTML.Action("GalleryImages")'+"?pageNo="+jQuery("galleryPage").val(),
                data: { isAll: isAllChecked },
              success: function(data){
               jQuery("gallery").append(data);//partial view with new images
               jQuery("galleryPage").val(gallery.getNumItems()/30); //page number total items/number of items per page
              },
              error:function (xhr, ajaxOptions, thrownError){
                              //some errror, some show err msg to user and log the error
                              alert(xhr.responseText);
                            }
              });
        }
    });

});

</script>

Partial View (_galleryImages.cshtml)

@foreach (var item in Model)
    {
        if (item.FileData != null)
        {
            var base64 = Convert.ToBase64String(item.FileData);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

            <img alt='Image'
                    src="@imgSrc"
                    data-image="@imgSrc"
                    data-description='Image'>
        }
    }

Controller

 //Main View
    public ActionResult List()
    {
            return View();
    }

//Partial View
public Action GalleryImages(int PageNo)
{
    int PageSize = 30;
     var model = db.Photo.Select(m => new PhotoViewModel
    {
        Id = m.Id,
        Name = m.Name,
        StatusId = m.StatusId,
        SubmitDate = m.SubmitDate,
        FileAttachments = m.FileAttachments,
        SubmitNo = m.SubmitNo
    }).Skip(PageNo*PageSize).Take(PageSize).ToArray();

    return PartialView("_galleryImages", model);
}


来源: stackexchange

问:
Is my masking correct
What does it mean by

```<code>if ((readParameter - > type(0) & 0xff) == 0xff) {}
</code>```

I know when we dO '&'with oxff then it returns the LSB. But what does it mean by evaluating it with again == 0xff  ?

I feel it something like this(for instance) :

```<code> if ((00000000 00000000 00000000 11011001 & 00000000 00000000 00000000 11111111) == 00000000 00000000 00000000 11111111)
   {
     //IF THEY ARE EQUAL IT ENTERS IN THE LOOP ? IN THIS CASE THEY ARE  NOT EQUAL
   }
</code>```

Please correct me
if i am wrong ?

答:
But what does it mean by evaluating it with again == 0xff ?

this if checks if least significant byte is equal to 0xff. The rest of what readParameter->type(0) returns might contain other bits set. If they were not removed with & 0xff then equality to 0xff might never be true.

I know when we dO '&'with something then it returns the LSB.

this is not true, when you use binary bitwise AND then the result depends on the arguments used in the operation. If you & with 0xff then you will get least significant byte, but if you do (ui32value & 0xff000000) >> 24 then you will read the most significant byte.

ContentLicense: CC BY-SA 3.0

Title: Is my masking correct

Body:
What does it mean by

if ((readParameter - > type(0) & 0xff) == 0xff) {}

I know when we dO '&'with oxff then it returns the LSB. But what does it mean by evaluating it with again == 0xff  ?

I feel it something like this(for instance) :

 if ((00000000 00000000 00000000 11011001 & 00000000 00000000 00000000 11111111) == 00000000 00000000 00000000 11111111)
   {
     //IF THEY ARE EQUAL IT ENTERS IN THE LOOP ? IN THIS CASE THEY ARE  NOT EQUAL
   }

Please correct me
if i am wrong ?


问:
How to change text on the span use vue.js 2?
My vue component is like this :

```<code><template>
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
           aria-expanded="false" :title="...">
            ...
            <span v-if="totalNotif > 0" class="badge" id="total-notif">{{ totalNotif }}</span>
        </a>
    </li>
</template>
<script>
    ...
    export default {
        mounted() {
            this.initialMount()
        },
        ...
        computed: {
            ...mapGetters([
                'totalNotif'
            ])
        },
        methods: {
            initialMount() {
                Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
                    const totalNotif = $('#total-notif').text()
                    const totalNotifNew = parseInt(totalNotif) + 1
                    $('#total-notif').text(totalNotifNew )
                })
            },
        }
    }
</script>
</code>```

It works

But, it still use jquery to get and update text on the span

How can I do it using vue.js 2?

I read some references, that it using watch. But I am still confused to use it

答:
Change

```<code>const totalNotif = $('#total-notif').text()
const totalNotifNew = parseInt(totalNotif) + 1
$('#total-notif').text(totalAllNew)
</code>```

By

```<code>//Set this.totalNotif to 1 if not exist or equals to 0. Else increment by 1
this.totalNotif = (this.totalNotif) ? (this.totalNotif + 1) : 1;
</code>```

But I don't understand the code :

```<code>    computed: {
        ...mapGetters([
            'totalNotif'
        ])
    },
</code>```

For my example I think you can have :

```<code>export default {
    mounted() {
        this.initialMount()
    },
    data() {
       return {
           totalNotif: 0
       }
    },
    ...
</code>```

Body:
My vue component is like this :

<template>

            ...
             0" class="badge" id="total-notif">{{ totalNotif }}

</template>

It works

But, it still use jquery to get and update text on the span

How can I do it using vue.js 2?

I read some references, that it using watch. But I am still confused to use it

Body:
Change

const totalNotif = $('#total-notif').text()
const totalNotifNew = parseInt(totalNotif) + 1
$('#total-notif').text(totalAllNew)

By

//Set this.totalNotif to 1 if not exist or equals to 0. Else increment by 1
this.totalNotif = (this.totalNotif) ? (this.totalNotif + 1) : 1;

But I don't understand the code :

    computed: {
        ...mapGetters([
            'totalNotif'
        ])
    },

For my example I think you can have :

export default {
    mounted() {
        this.initialMount()
    },
    data() {
       return {
           totalNotif: 0
       }
    },
    ...


答:
On the template you will change the span with:

```<code><span v-if="totalNotif > 0" class="badge" id="total-notif" v-text="totalNotif"></span>
</code>```

This will connect span with value totalNotif.
So on VueJs part, remove jquery part, updating only data totalNotif and automatically will update span text content.

EDIT
To better understand, the script part become:

```<code>export default {
    mounted() {
        this.initialMount()
    },

    data() {
       return {
          totalNotif: 0
       }
    },

    methods: {
        initialMount() {
            Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
                this.totalNotif = this.totalNotif + 1

            })
        },
    }
}
</code>```

Title: How to change text on the span use vue.js 2?

Body:
On the template you will change the span with:

<span v-if="totalNotif > 0" class="badge" id="total-notif" v-text="totalNotif"></span>

This will connect span with value totalNotif.
So on VueJs part, remove jquery part, updating only data totalNotif and automatically will update span text content.

EDIT
To better understand, the script part become:

export default {
    mounted() {
        this.initialMount()
    },

    data() {
       return {
          totalNotif: 0
       }
    },

    methods: {
        initialMount() {
            Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
                this.totalNotif = this.totalNotif + 1

            })
        },
    }
}


问:
In JSP, why do my radio buttons cause onSubmit to no longer be called?
Major Update: Due to Spring, the validator is called before the onSubmit invocation occurs.  When no radio buttons are selected, this runs fine.   When a radio button is selected, the POST data contains a variable for the radio button and this causes a NestedServletException.

This variable is not bound to any property or class.  Is there a "correct" way that such a variable needs to be handled, either within JSP or within my code?

I have a JSP page, hooked up with Spring, where the onSubmit listener is no longer invoked after I add some radio buttons to the JSP page.  Without the radio buttons, a bare version of the page looks like this.

```<code><form:form>
    <fieldset>
        <input type="submit" value="Submit"/>
    </fieldset>
</form:form>
</code>```

This works as expected.  My debugger reaches a breakpoint for onSubmit once the submit button is pressed.  Then I add the following code for radio buttons, which can be seen below.

```<code><form:form>
    <fieldset>
        <input type="submit" value="Submit"/>
    </fieldset>

    <fieldset class="contentHalfFieldset"><legend>NID</legend>
        <input type="radio" name="someName" value="value1" />
        <input type="radio" name="someName" value="value2" />
        <input type="radio" name="someName" value="value3" />
    </fieldset>
</form:form>
</code>```

Now, when I don't select any radio button, the submit button still causes the submission event to reach the breakpoint in the onSubmit method.  It still works as intended.  However, when I select one of the radio buttons and then press the submit button, the page simply refreshes.

Why is that?  What's happening that makes input buttons prevent the processing of a submission?

------- Generated HTML -------

```<code><form id="cmd" method="post" action="/page/pageAction.html?param=k" onsubmit="disableSubmit(this);">
    <fieldset class="contentHalfFieldset"><legend>NID</legend>
        <label class="labelClass">First radio button:</label>
        <input type="radio" name="nidStatus" value="first" /><br style="clear: both"/>
        <label class="labelClass">Second radion button:</label>
        <input type="radio" name="nidStatus" value="second" /><br style="clear: both"/>
        <label class="labelClass">Third radio button</label>
        <input type="radio" name="nidStatus" value="third" /><br style="clear: both"/>
    </fieldset>

</form>
</code>```

------- More Requested Code -------

This is the disableSubmit(..) method.

```<code>function disableSubmit(parentElement) {
    elements = parentElement.elements;

    for(var i = 0; i < elements.length; i++) {
        var element = elements[i];

        if(element.type == "submit") {
            element.disabled=true;
            element.value="Please Wait...";
        }
    }
};
</code>```

答:
Spring tries to bind your variables if they happen to be named as the same thing as your controls (in my case, the radio button).  Depending on your code to handle the variable. which you are not intending to bind, an exception can occur before the onSubmit method is reached.

In my case, I had a class that had a "nidStatus" variable, of an enum type.  When the variable "US&nidStatus" (see comments in response to Michael Kopinsky) was sent in the POST action, there was an automatic attempt to bind this.  Interestingly, validation went fine before the exception was thrown, so -- if you found this question despite someone marking it unacceptable -- make sure to check your errors variable in your validate() method, as the handler will still continue on beyond that point as if things are fine.

ContentLicense: CC BY-SA 2.5

Body:
Major Update: Due to Spring, the validator is called before the onSubmit invocation occurs.  When no radio buttons are selected, this runs fine.   When a radio button is selected, the POST data contains a variable for the radio button and this causes a NestedServletException.

This variable is not bound to any property or class.  Is there a "correct" way that such a variable needs to be handled, either within JSP or within my code?

I have a JSP page, hooked up with Spring, where the onSubmit listener is no longer invoked after I add some radio buttons to the JSP page.  Without the radio buttons, a bare version of the page looks like this.

<form:form>
    <fieldset>
        <input type="submit" value="Submit"/>
    </fieldset>
</form:form>

This works as expected.  My debugger reaches a breakpoint for onSubmit once the submit button is pressed.  Then I add the following code for radio buttons, which can be seen below.

<form:form>
    <fieldset>
        <input type="submit" value="Submit"/>
    </fieldset>

    <fieldset class="contentHalfFieldset"><legend>NID</legend>
        <input type="radio" name="someName" value="value1" />
        <input type="radio" name="someName" value="value2" />
        <input type="radio" name="someName" value="value3" />
    </fieldset>
</form:form>

Now, when I don't select any radio button, the submit button still causes the submission event to reach the breakpoint in the onSubmit method.  It still works as intended.  However, when I select one of the radio buttons and then press the submit button, the page simply refreshes.

Why is that?  What's happening that makes input buttons prevent the processing of a submission?

------- Generated HTML -------

<form id="cmd" method="post" action="/page/pageAction.html?param=k" onsubmit="disableSubmit(this);">
    <fieldset class="contentHalfFieldset"><legend>NID</legend>
        First radio button:
        <input type="radio" name="nidStatus" value="first" />

        Second radion button:
        <input type="radio" name="nidStatus" value="second" />

        Third radio button
        <input type="radio" name="nidStatus" value="third" />

    </fieldset>

</form>

------- More Requested Code -------

This is the disableSubmit(..) method.

function disableSubmit(parentElement) {
    elements = parentElement.elements;

    for(var i = 0; i < elements.length; i++) {
        var element = elements[i];

        if(element.type == "submit") {
            element.disabled=true;
            element.value="Please Wait...";
        }
    }
};


问:
How can I get the result of a request after executing the request using c++ builder XE6 and Firebird?
After connecting to a Firebird database with C++ builder, I cannot get a result from a simple select request.

I have some confusion about a lot of members of classes:

```<code>void __fastcall TForm2::btn1Click(TObject *Sender)
{  TSQLConnection   co = new TSQLConnection(this);
   Base_Firebird *fb = new Base_Firebird()  ;
   bool  bl = fb->Connecter(co);
   String sqlstring = "select nom_action from T_ACTION where CLE_ACTION=6 ";
   if (bl)
      TSQLQuery *req = new TSQLQuery(NULL) ;
   req->SQLConnection = co ;
   req->SQL->Add(sqlstring);
   req->Open() ;
  }
</code>```

My problem is here after opening the TSQLQuery, I don't know how I can get the result and execute the command.

答:
Try changing the end of your subroutine to something like this:

```<code>if (bl)
{ /// you forgot compound operator here !!!!!
      TSQLQuery *req = new TSQLQuery(this) ;
   req->SQLConnection = co ;
   req->SQL->Text = sqlstring;
   req->Open() ;

   int j = 0;
   while( !req->EOF() )
   {
      ++j;
      String Value = req->Fields[0]->AsString;
      ShowMessageFmt( "Row %d ==> Value: %s ", ARRAYOFCONST(( j, Value )) );

      // String MSG = Format( "Row %d ==> Value: %s ", ARRAYOFCONST(( j, Value )) );
      // ShowMessage( MSG );

     req -> Next();
   };
   req->Close();
   ShowMessage("Data over.");
  }
  req -> Free();  // maybe "delete req;" would work too, dunno
}
</code>```

To check:

http://docwiki.embarcadero.com/Libraries/Seattle/en/Vcl.Dialogs.ShowMessageFmt

http://docwiki.embarcadero.com/Libraries/Seattle/en/System.SysUtils.Format

https://osdn.net/projects/cc1101driver/scm/svn/blobs/head/trunk/VC_test/Cpp_builder_2009/Cpp_Builder_test/documents/JVC_20120502/jvcl/examples/JvProgressDialog/BCB/JvProgressDialogMain.cpp

http://www.texttransformer.com/d2chelp/cbuilderarrayofconst.htm

http://docwiki.embarcadero.com/RADStudio/Seattle/en/Open_Arrays#C.2B.2B_functions_that_take_open_array_arguments

http://docwiki.embarcadero.com/RADStudio/Seattle/en/Support_for_Object_Pascal_Data_Types_and_Language_Concepts

Body:
After connecting to a Firebird database with C++ builder, I cannot get a result from a simple select request.

I have some confusion about a lot of members of classes:

void __fastcall TForm2::btn1Click(TObject *Sender)
{  TSQLConnection   co = new TSQLConnection(this);
   Base_Firebird *fb = new Base_Firebird()  ;
   bool  bl = fb->Connecter(co);
   String sqlstring = "select nom_action from T_ACTION where CLE_ACTION=6 ";
   if (bl)
      TSQLQuery *req = new TSQLQuery(NULL) ;
   req->SQLConnection = co ;
   req->SQL->Add(sqlstring);
   req->Open() ;
  }

My problem is here after opening the TSQLQuery, I don't know how I can get the result and execute the command.

Body:
Try changing the end of your subroutine to something like this:

if (bl)
{ /// you forgot compound operator here !!!!!
      TSQLQuery *req = new TSQLQuery(this) ;
   req->SQLConnection = co ;
   req->SQL->Text = sqlstring;
   req->Open() ;

   int j = 0;
   while( !req->EOF() )
   {
      ++j;
      String Value = req->Fields[0]->AsString;
      ShowMessageFmt( "Row %d ==> Value: %s ", ARRAYOFCONST(( j, Value )) );

      // String MSG = Format( "Row %d ==> Value: %s ", ARRAYOFCONST(( j, Value )) );
      // ShowMessage( MSG );

     req -> Next();
   };
   req->Close();
   ShowMessage("Data over.");
  }
  req -> Free();  // maybe "delete req;" would work too, dunno
}

To check:

http://docwiki.embarcadero.com/Libraries/Seattle/en/Vcl.Dialogs.ShowMessageFmt

http://docwiki.embarcadero.com/Libraries/Seattle/en/System.SysUtils.Format

https://osdn.net/projects/cc1101driver/scm/svn/blobs/head/trunk/VC_test/Cpp_builder_2009/Cpp_Builder_test/documents/JVC_20120502/jvcl/examples/JvProgressDialog/BCB/JvProgressDialogMain.cpp

http://www.texttransformer.com/d2chelp/cbuilderarrayofconst.htm

http://docwiki.embarcadero.com/RADStudio/Seattle/en/Open_Arrays#C.2B.2B_functions_that_take_open_array_arguments

http://docwiki.embarcadero.com/RADStudio/Seattle/en/Support_for_Object_Pascal_Data_Types_and_Language_Concepts


问:
internet explorer font face ssl
The fonts for my site are working fine in all browsers using http. However when I change to https the fonts don't work in IE8 and below, works correctly in ie9.

Using IE, when I type the path to the .eot file using http, I get the option to download the file, but when I use https, it says it can't be found.

I'm using a self assigned certificate. iis 7.5 .net 4.0, umbraco 4.7.0 cms, client dependency framework (I have tried with client dependency framework removed, still didn't work).

```<code><style type="text/css">
@font-face {
                font-family: 'GGX88UltraLight';
                src: url('/css/type/ggx88_ul-webfont.eot');
                src: url('/css/type/ggx88_ul-webfont.eot?iefix') format('embedded-opentype'),
                     url('/css/type/ggx88_ul-webfont.woff') format('woff'),
                     url('/css/type/ggx88_ul-webfont.ttf') format('truetype'),
                     url('/css/type/ggx88_ul-webfont.svg#webfontU6kiGgEl') format('svg');
                font-weight: normal;
                font-style: normal;
    }
</style>
</code>```

web config values that might be useful

```<code><staticContent>
  <!-- Set expire headers to 30 days for static content-->
  <clientCache cacheControlMode="DisableCache" cacheControlMaxAge="30.00:00:00" />
  <!-- use utf-8 encoding for anything served text/plain or text/html -->
  <remove fileExtension=".css" />
  <mimeMap fileExtension=".css" mimeType="text/css; charset=UTF-8" />
  <remove fileExtension=".js" />
  <mimeMap fileExtension=".js" mimeType="text/javascript; charset=UTF-8" />
  <remove fileExtension=".json" />
  <mimeMap fileExtension=".json" mimeType="application/json; charset=UTF-8" />
  <remove fileExtension=".rss" />
  <mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8" />
  <remove fileExtension=".html" />
  <mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
  <remove fileExtension=".xml" />
  <mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8" />
  <!-- HTML5 Video mime types-->
  <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
  <mimeMap fileExtension=".m4v" mimeType="video/m4v" />
  <mimeMap fileExtension=".ogg" mimeType="video/ogg" />
  <mimeMap fileExtension=".ogv" mimeType="video/ogg" />
  <mimeMap fileExtension=".webm" mimeType="video/webm" />
  <!-- Remove default IIS mime type for .eot which is application/octet-stream -->
  <remove fileExtension=".eot" />
  <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
  <mimeMap fileExtension=".otf" mimeType="font/otf" />
  <mimeMap fileExtension=".woff" mimeType="font/x-woff" />
  <mimeMap fileExtension=".crx" mimeType="application/x-chrome-extension" />
  <mimeMap fileExtension=".xpi" mimeType="application/x-xpinstall" />
  <mimeMap fileExtension=".safariextz" mimeType="application/octet-stream" />
</staticContent>
<httpProtocol allowKeepAlive="true">
  <customHeaders>
    <add name="X-UA-Compatible" value="IE=Edge,chrome=1" />
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>
</code>```

答:
I faced the same behaviour using spring-boot:
the solution I found was to

- Hide  Pragma and Cache-Control returned headers to the browser:

Spring-boot is responding with specific Cache-Control and Pragma HTTP headers.

```<code>Cache-Control :"no-cache, no-store, max-age=0, must-revalidate"
Pragma :"no-cache"
</code>```

Internet explorer (IE11 in my case) is not able to load fonts with those headers.
I believe its a bug and we have to cope with it.

Using nginx to proxy our spring-boot application,
I could overcome the problem ,
hiding that headers to the browser by using the following nginx configuration commands:

```<code>server {
        listen 443;
        server_name server.dns.name;
        ssl on;
        ssl_certificate /etc/nginx/ssl/server.dns.name.pem;
        ssl_certificate_key /etc/nginx/ssl/server.dns.name.key;

        location / {
            include  /etc/nginx/mime.types;
            rewrite ^/(.*) /$1 break;
            proxy_pass  http://127.0.0.1:8080;
            proxy_read_timeout 90;

            #IE specific tweak for fonts not to be ignored:
            proxy_hide_header Cache-Control;
            proxy_hide_header Pragma;
            #END IE specific tweak for fonts not to be ignored
        }
}
</code>```

Title: internet explorer font face ssl

Body:
The fonts for my site are working fine in all browsers using http. However when I change to https the fonts don't work in IE8 and below, works correctly in ie9.

Using IE, when I type the path to the .eot file using http, I get the option to download the file, but when I use https, it says it can't be found.

I'm using a self assigned certificate. iis 7.5 .net 4.0, umbraco 4.7.0 cms, client dependency framework (I have tried with client dependency framework removed, still didn't work).

web config values that might be useful

<staticContent>

  <clientCache cacheControlMode="DisableCache" cacheControlMaxAge="30.00:00:00" />

  <remove fileExtension=".css" />
  <mimeMap fileExtension=".css" mimeType="text/css; charset=UTF-8" />
  <remove fileExtension=".js" />
  <mimeMap fileExtension=".js" mimeType="text/javascript; charset=UTF-8" />
  <remove fileExtension=".json" />
  <mimeMap fileExtension=".json" mimeType="application/json; charset=UTF-8" />
  <remove fileExtension=".rss" />
  <mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8" />
  <remove fileExtension=".html" />
  <mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
  <remove fileExtension=".xml" />
  <mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8" />

  <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
  <mimeMap fileExtension=".m4v" mimeType="video/m4v" />
  <mimeMap fileExtension=".ogg" mimeType="video/ogg" />
  <mimeMap fileExtension=".ogv" mimeType="video/ogg" />
  <mimeMap fileExtension=".webm" mimeType="video/webm" />

  <remove fileExtension=".eot" />
  <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
  <mimeMap fileExtension=".otf" mimeType="font/otf" />
  <mimeMap fileExtension=".woff" mimeType="font/x-woff" />
  <mimeMap fileExtension=".crx" mimeType="application/x-chrome-extension" />
  <mimeMap fileExtension=".xpi" mimeType="application/x-xpinstall" />
  <mimeMap fileExtension=".safariextz" mimeType="application/octet-stream" />
</staticContent>
<httpProtocol allowKeepAlive="true">
  <customHeaders>
    <add name="X-UA-Compatible" value="IE=Edge,chrome=1" />
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

Body:
I faced the same behaviour using spring-boot:
the solution I found was to

- Hide  Pragma and Cache-Control returned headers to the browser:

Spring-boot is responding with specific Cache-Control and Pragma HTTP headers.

Cache-Control :"no-cache, no-store, max-age=0, must-revalidate"
Pragma :"no-cache"

Internet explorer (IE11 in my case) is not able to load fonts with those headers.
I believe its a bug and we have to cope with it.

Using nginx to proxy our spring-boot application,
I could overcome the problem ,
hiding that headers to the browser by using the following nginx configuration commands:

server {
        listen 443;
        server_name server.dns.name;
        ssl on;
        ssl_certificate /etc/nginx/ssl/server.dns.name.pem;
        ssl_certificate_key /etc/nginx/ssl/server.dns.name.key;

        location / {
            include  /etc/nginx/mime.types;
            rewrite ^/(.*) /$1 break;
            proxy_pass  http://127.0.0.1:8080;
            proxy_read_timeout 90;

            #IE specific tweak for fonts not to be ignored:
            proxy_hide_header Cache-Control;
            proxy_hide_header Pragma;
            #END IE specific tweak for fonts not to be ignored
        }
}


问:
Could not fetch Places - REQUEST_DENIED
I want to fetch places from google place api, I just download SPGooglePlacesAutocomplete & created new API Key enable place, direction & map api's from Google API Console still i am getting error alert.

Any help very much appreciated.

答:
I assume you are using key which is made for iOS apps.But SPGooglePlacesAutocomplete might be using Google's public API to fetch the places list. So in that case you should use key for your browser apps. You can refer following link for more elaborated ans

REQUEST_DENIED when using the Google Places API

Title: Could not fetch Places - REQUEST_DENIED


问:
Do we need interfaces for dependency injection?
I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example

```<code> public interface IStorage
 {
    Task Download(string file);
 }

 public class Storage
 {
    public Task Download(string file)
    {
    }
 }

 public interface IOcr
 {
     Task Process();
 }

 public class Ocr:IOcr
 {
    public Task Process()
    {

    }
 }
</code>```

Basically for each interface there is only one class. Then i register these types with DI as

```<code> services.AddScoped<IStorage, Storage>();
 services.AddScoped<IOcr,Ocr>();
</code>```

But i can register type without having interfaces so interfaces here look redundant. eg

```<code> services.AddScoped<Storage>();
 services.AddScoped<Ocr>();
</code>```

So do i really need interfaces?

答:
I won't try to cover what others have already mentioned, using interfaces with DI will often be the best option.  But it's worth mentioning that using object inheritance at times may provide another useful option.  So for example:

```<code>public class Storage
 {
    public virtual Task Download(string file)
    {
    }
 }

public class DiskStorage: Storage
 {
    public override Task Download(string file)
    {
    }
 }
</code>```

and registering it like so:

```<code>services.AddScoped<Storage, DiskStorage>();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example

 public interface IStorage
 {
    Task Download(string file);
 }

 public class Storage
 {
    public Task Download(string file)
    {
    }
 }

 public interface IOcr
 {
     Task Process();
 }

 public class Ocr:IOcr
 {
    public Task Process()
    {

    }
 }

Basically for each interface there is only one class. Then i register these types with DI as

 services.AddScoped<IStorage, Storage>();
 services.AddScoped<IOcr,Ocr>();

But i can register type without having interfaces so interfaces here look redundant. eg

 services.AddScoped<Storage>();
 services.AddScoped<Ocr>();

So do i really need interfaces?

Body:
I won't try to cover what others have already mentioned, using interfaces with DI will often be the best option.  But it's worth mentioning that using object inheritance at times may provide another useful option.  So for example:

public class Storage
 {
    public virtual Task Download(string file)
    {
    }
 }

public class DiskStorage: Storage
 {
    public override Task Download(string file)
    {
    }
 }

and registering it like so:

services.AddScoped<Storage, DiskStorage>();


问:
Swift's "if let" equivalent in Objective C
What would be "if let" equivalent in Objective C? The example snippet I want to convert to Objective C is below;</p>
```<code>if let pfobjects = images as? [PFObject] {
    if pfobjects.count > 0 {
        var imageView: PFImageView = PFImageView()
        imageView.file = pfobjects[0] as! PFFile
        imageView.loadInBackground()
    }
}
</code>```

答:
You can use Objective-C++ in place of Objective-C. In this you can use the next define:

```<code>#define let const auto
</code>```

Note: it is not the same exactly (Swift has wrapped values, ...) but it makes the work easier.

And through of this define you can use it of this way:

```<code>if (let pfobjects = images) {
    if (pfobjects.count > 0 {
        let imageView = [[PFImageView alloc] init];
        imageView.file = pfobjects[0];
        imageView loadInBackground();
    }
}
</code>```

To convert your Objective-C class in Objective-C++ class you only must change the extension of implementation file of .m to .mm

Body:
What would be "if let" equivalent in Objective C? The example snippet I want to convert to Objective C is below;

if let pfobjects = images as? [PFObject] {
    if pfobjects.count > 0 {
        var imageView: PFImageView = PFImageView()
        imageView.file = pfobjects[0] as! PFFile
        imageView.loadInBackground()
    }
}

Body:
You can use Objective-C++ in place of Objective-C. In this you can use the next define:

#define let const auto

Note: it is not the same exactly (Swift has wrapped values, ...) but it makes the work easier.

And through of this define you can use it of this way:

if (let pfobjects = images) {
    if (pfobjects.count > 0 {
        let imageView = [[PFImageView alloc] init];
        imageView.file = pfobjects[0];
        imageView loadInBackground();
    }
}

To convert your Objective-C class in Objective-C++ class you only must change the extension of implementation file of .m to .mm


问:
Xcode with SDK 4.2 always starting iPad Simulator
Why does Xcode, after updating to SDK 4.2, always run my application in iPad Simulator instead of iPhone???
If I select iPhone Simulator as active executable it doesn't store my preference and runs the iPad simulator after any new Build & Run.</p>

答: Check the Active Executable setting, as well as the Simulator's setting for "Device."</p>


问:
TypeError: Cannot read property 'then' of undefined at m.$scope.profile
I am trying to call a child service function in Main Controller.

But I am getting error on than in profile function.
This is my profile function inside main controller.

```<code>App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {

                if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = getClientResponse[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              });
            }
          }
      };
)};
</code>```

This is Service of another controller whom function "getClient" I am calling in profile function.

```<code>App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});
</code>```

Need Help. cant figure out the Problem. Thanks in advance!

答:
Change your service to just return a promise and handle that promise in your controller using then

The service directly returns API call, no then in service

```<code>var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER)
</code>```

Here is your service:

```<code>App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE, $q) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER)
            }
        else {
             var promise =  $q.reject();
        }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});
</code>```

Now, the controller handles the success and failure response using then

```<code>ClientService.getClient(getOrganizationId).then(function(){},function(){})
</code>```

Here is your controller, observe then

```<code>App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $cookieStore, toastr, ClientService) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {
               var response = [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];

                if(response[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = response[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
          }
      };
)};
</code>```

Body:
I am trying to call a child service function in Main Controller.

But I am getting error on than in profile function.
This is my profile function inside main controller.

App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {

                if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = getClientResponse[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              });
            }
          }
      };
)};

This is Service of another controller whom function "getClient" I am calling in profile function.

App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});

Need Help. cant figure out the Problem. Thanks in advance!

Body:
Change your service to just return a promise and handle that promise in your controller using then

The service directly returns API call, no then in service

var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER)

Here is your service:

App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE, $q) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER)
            }
        else {
             var promise =  $q.reject();
        }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});

Now, the controller handles the success and failure response using then

ClientService.getClient(getOrganizationId).then(function(){},function(){})

Here is your controller, observe then

App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $cookieStore, toastr, ClientService) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {
               var response = [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];

                if(response[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = response[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
          }
      };
)};


问:
How to retrieve specific value of key in json?
this is my json content.

```<code> [
  {
    "sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
     "commit":{
     "author":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "committer":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "message":"Merge branch '1.5.x'",

   }
 }
 ]
</code>```

and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.

```<code>    NSMutableArray *CommitArray = [[NSMutableArray alloc] init];

    for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        commitDictObj.message = [CommitDictionary objectForKey:@"message"];

        for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:@"committer"]) {
            Committer *author = [[Committer alloc] init];
            author.name = [CommitterDictionary objectForKey:@"name"];
            author.email = [CommitterDictionary objectForKey:@"email"];
            author.date = [CommitterDictionary objectForKey:@"date"];
        }

        [CommitArray addObject:commitDictObj];
    }

    for (int i =0 ; i < [CommitArray count] ; i++){
        CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
        NSLog(@"Commit Message: %@", commitDictObj.message);

    }

     return 0;
}

}
</code>```

i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?

答:
(1) Convert JSON to NSDictionary

```<code>NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
</code>```

(2) Access the dictionary values (fast enumeration available by now!!

```<code>NSString *message = dictionary[@"message"];

NSDictionary *author = dictionary[@"author"];
NSString *name = author[@"author"];
NSString *email = author[@"author"];
NSString *date = author[@"author"];
// OR:
// NSString *name = dictionary[@"author"][@"author"];
// NSString *email = dictionary[@"author"][@"author"];
// NSString *date = dictionary[@"author"][@"author"];
</code>```

And thats it. I think the tricky thing is to get the JSON Data to the NSDictionary?
See here: https://stackoverflow.com/a/30561781/464016

Body:
this is my json content.

 [
  {
    "sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
     "commit":{
     "author":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "committer":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "message":"Merge branch '1.5.x'",

   }
 }
 ]

and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.

    NSMutableArray *CommitArray = [[NSMutableArray alloc] init];

    for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        commitDictObj.message = [CommitDictionary objectForKey:@"message"];

        for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:@"committer"]) {
            Committer *author = [[Committer alloc] init];
            author.name = [CommitterDictionary objectForKey:@"name"];
            author.email = [CommitterDictionary objectForKey:@"email"];
            author.date = [CommitterDictionary objectForKey:@"date"];
        }

        [CommitArray addObject:commitDictObj];
    }

    for (int i =0 ; i < [CommitArray count] ; i++){
        CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
        NSLog(@"Commit Message: %@", commitDictObj.message);

    }

     return 0;
}

}

i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?

Body:
(1) Convert JSON to NSDictionary

NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

(2) Access the dictionary values (fast enumeration available by now!!

NSString *message = dictionary[@"message"];

NSDictionary *author = dictionary[@"author"];
NSString *name = author[@"author"];
NSString *email = author[@"author"];
NSString *date = author[@"author"];
// OR:
// NSString *name = dictionary[@"author"][@"author"];
// NSString *email = dictionary[@"author"][@"author"];
// NSString *date = dictionary[@"author"][@"author"];

And thats it. I think the tricky thing is to get the JSON Data to the NSDictionary?
See here: https://stackoverflow.com/a/30561781/464016


问:
Javassist throwing notfound / null pointer in CtMethod.make and getDeclaredMethod using OSGI
javassist is throwing null pointer in CtMethod.make com.company.test is the package of the Activator and Joe

```<code>public class Activator implements BundleActivator {

public Class<?> creerClasse() {
    CtClass toGenerateClass;
    ClassPool pool;
    pool = ClassPool.getDefault();
    try {
        Class c;
        c = Class.forName("com.company.test.Joe");
        pool.appendClassPath(new ClassClassPath(c));
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    pool.importPackage("com.company.test");

    toGenerateClass = pool.makeClass("Test118");

    try {
        toGenerateClass
                .addMethod(CtMethod
                        .make("public void afficher (com.company.test.Joe msg) { System.out.println(msg); } ;",
                                toGenerateClass));
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }

    try {
        return toGenerateClass.toClass();
    } catch (CannotCompileException e) {
        e.printStackTrace();
        return null;
    }
}

public void start(BundleContext context) throws Exception {

        Class<?> genClass = creerClasse();
        Class<?> c = Class.forName("com.company.test.Joe");

        for (Method me : genClass.getDeclaredMethods()) { // test print, ok
            System.out.println(me);
        }

        Method method = genClass.getDeclaredMethod("afficher", c);

        Joe person = new Joe();
        person.setId(17);
        method.invoke(genClass.newInstance(), person);

}

}
</code>```

and when i instansiate pool with pool = new ClassPool(true);
it throws  java.lang.NoClassDefFoundError: com/company/test/Joe in getDeclaredMethod

答:
Class.forName("com.company.test.Joe") will use the ClassLoader of the object it is called from. So in this case it will use the ClassLoader of your Activator class. In OSGi the ClassLoader of a class is typically the ClassLoder of the bundle the Class is in.

The ClassLoader of a bundle can only load classes that are inside the bundle and classes in packages that it has an Import-Package statement for.

So if you want to load a Class from any package you can not simply use Class.forName. In fact a simple class name is not even unique in OSGi as different bundles might provide the package in different versions.

I am not sure what your exact use case is. You use a fixed String for the name but I guess you want to load a class with a name that comes from some source like a config. If you give me more informations about the use case then I can recommend how to approach this problem.

Body:
javassist is throwing null pointer in CtMethod.make com.company.test is the package of the Activator and Joe

public class Activator implements BundleActivator {

public Class<?> creerClasse() {
    CtClass toGenerateClass;
    ClassPool pool;
    pool = ClassPool.getDefault();
    try {
        Class c;
        c = Class.forName("com.company.test.Joe");
        pool.appendClassPath(new ClassClassPath(c));
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    pool.importPackage("com.company.test");

    toGenerateClass = pool.makeClass("Test118");

    try {
        toGenerateClass
                .addMethod(CtMethod
                        .make("public void afficher (com.company.test.Joe msg) { System.out.println(msg); } ;",
                                toGenerateClass));
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }

    try {
        return toGenerateClass.toClass();
    } catch (CannotCompileException e) {
        e.printStackTrace();
        return null;
    }
}

public void start(BundleContext context) throws Exception {

        Class<?> genClass = creerClasse();
        Class<?> c = Class.forName("com.company.test.Joe");

        for (Method me : genClass.getDeclaredMethods()) { // test print, ok
            System.out.println(me);
        }

        Method method = genClass.getDeclaredMethod("afficher", c);

        Joe person = new Joe();
        person.setId(17);
        method.invoke(genClass.newInstance(), person);

}

}

and when i instansiate pool with pool = new ClassPool(true);
it throws  java.lang.NoClassDefFoundError: com/company/test/Joe in getDeclaredMethod


答:
Try something like this to ensure that there is always a promise object available.

```<code>getClient: function() {

    var deferred = $q.defer();

    if(theClient.OrganizationId) {
        //API Call
       $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
        function(aGetClientResponse) { //Success Callback
            deferred.resolve(aGetClientResponse);
        },
        function(aGetClientResponse) { //Error Callback
            deferred.resolve(aGetClientResponse);
        });
    }else{
        deferred.reject('Missing OrganizationId');
    }

    return deferred.promise;
}
</code>```

Title: TypeError: Cannot read property 'then' of undefined at m.$scope.profile

Body:
Try something like this to ensure that there is always a promise object available.

getClient: function() {

    var deferred = $q.defer();

    if(theClient.OrganizationId) {
        //API Call
       $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
        function(aGetClientResponse) { //Success Callback
            deferred.resolve(aGetClientResponse);
        },
        function(aGetClientResponse) { //Error Callback
            deferred.resolve(aGetClientResponse);
        });
    }else{
        deferred.reject('Missing OrganizationId');
    }

    return deferred.promise;
}


问:
Joomla add article via php script Application Instantiation Error
i created a script in order to insert some articles via a php script. This script is working on my local machine (xampp), but when i deploy the whole joomla project to my web server i get the following error message:

Error displaying the error page: Application Instantiation Error: Application Instantiation Error

By adding some echo calls, i was able to find the line which causes the error:

```<code>$app = JFactory::getApplication('site');
</code>```

Now i am wondering how to fix this behaviour and make my function also run on the web server.

Below i will provide my system informations and the beginning of my php function until the line, which causes the error message:

Systeminformations

joomla version: 3.6.5 Stable

db version: 5.6.34-79.1-log

php version: 5.6.30-he.0

web server: Apache

PHP snippet

```<code><?php

echo "STARTING;   ";

// get db connection
include('../includes/mysql.inc.php');

// get all sql querys
include('./autoNewsQuerys.inc.php');

/**
 * Prepare joomla framework to insert article correctly
 */
if (!defined('_JEXEC')) {
    define('_JEXEC', 1);
    define('JPATH_BASE','/is/htdocs/wp1088688_4E1H7PYJFK/www');
    require_once(JPATH_BASE . '/includes/defines.php');
    require_once(JPATH_BASE . '/includes/framework.php');
    defined('DS') or define('DS', DIRECTORY_SEPARATOR);
}

echo "searching app;";
$app = JFactory::getApplication('site');
echo "Found app;";

</code>```

Full browser output

STARTING; searching app;Error displaying the error page: Application Instantiation Error: Failed to start the session because headers have already been sent by "/is/htdocs/wp1088688_4E1H7PYJFK/www/1500AutoNews/autoNews.php" at line 3.

So as you can see the error is caused by the JFactory call. 'Found app' is never printed out.

答:
if it was working on localhost and it is not working on Web server then the biggest issue is with defining the base path. Give a hardcoded base path of your joomla installation. I suggest you to check your base path using a php script. Create a php file and name it path.php. Put it in the Joomla main folder. Content of the file

```<code><?php
echo "The Base path is ".getcwd();
?>
</code>```

Once you get the path just change the Base_Path. For ex:

```<code>define('JPATH_BASE', '\var\www\joomla');
</code>```

Body:
i created a script in order to insert some articles via a php script. This script is working on my local machine (xampp), but when i deploy the whole joomla project to my web server i get the following error message:

Error displaying the error page: Application Instantiation Error: Application Instantiation Error

By adding some echo calls, i was able to find the line which causes the error:

$app = JFactory::getApplication('site');

Now i am wondering how to fix this behaviour and make my function also run on the web server.

Below i will provide my system informations and the beginning of my php function until the line, which causes the error message:

Systeminformations

joomla version: 3.6.5 Stable

db version: 5.6.34-79.1-log

php version: 5.6.30-he.0

web server: Apache

PHP snippet

<?php

echo "STARTING;   ";

// get db connection
include('../includes/mysql.inc.php');

// get all sql querys
include('./autoNewsQuerys.inc.php');

/**
 * Prepare joomla framework to insert article correctly
 */
if (!defined('_JEXEC')) {
    define('_JEXEC', 1);
    define('JPATH_BASE','/is/htdocs/wp1088688_4E1H7PYJFK/www');
    require_once(JPATH_BASE . '/includes/defines.php');
    require_once(JPATH_BASE . '/includes/framework.php');
    defined('DS') or define('DS', DIRECTORY_SEPARATOR);
}

echo "searching app;";
$app = JFactory::getApplication('site');
echo "Found app;";

Full browser output

STARTING; searching app;Error displaying the error page: Application Instantiation Error: Failed to start the session because headers have already been sent by "/is/htdocs/wp1088688_4E1H7PYJFK/www/1500AutoNews/autoNews.php" at line 3.

So as you can see the error is caused by the JFactory call. 'Found app' is never printed out.

Body:
if it was working on localhost and it is not working on Web server then the biggest issue is with defining the base path. Give a hardcoded base path of your joomla installation. I suggest you to check your base path using a php script. Create a php file and name it path.php. Put it in the Joomla main folder. Content of the file

<?php
echo "The Base path is ".getcwd();
?>

Once you get the path just change the Base_Path. For ex:

define('JPATH_BASE', '\var\www\joomla');


问:
Fire rewrite rule on class constraint
I'm trying to write a maybeShow function which is show but without a Show class constraint. Here's my attempt:

```<code>{-# INLINE [1] maybeShow #-}
maybeShow :: a -> Maybe String
maybeShow _ = Nothing

canShow :: Show a => a -> Maybe String
canShow = Just . show

data CantShow = CantShow

main = do
  print (maybeShow (42 :: Int))
  print (maybeShow CantShow)

{-# RULES
"maybeShow" forall (x :: (Show a => a)). maybeShow x = canShow x
#-}
</code>```

But in this code, the rewrite rule never seems to fire.

I know this will sometimes return Nothing for showable types. For example, I entirely expect uses of maybeShow in non-inlined functions which are not specialised to a particular type to return Nothing. But as I'm using maybeShow as something to add to the output of error, it doesn't really matter if it doesn't always work.

But I'd like it to sometimes work (for example, when it's been inlined into the calling function) rather than never as seems to be currently the case.

Any ideas on how to get the rewrite rule to fire? This on wiki.haskell.org suggests it can be done, but the advice dates back to GHC 6.6 so I'm not sure it's still valid.

答:
The requirements are still unclear to me, but I can't think of other solutions than the following two, e.g., to debug a library of polymorphic functions by tracing trace values of parametric types, but adding a Show constraint would break code downstream.

Use rewrite rules on monomorphic types. I assume that for debugging purposes, you need only a few types. However this may be rather unreliable, and you might need to specialise/inline functions explicitly.

Perhaps you can get by with another type class with a blanket overlappable instance.

```<code>class MaybeShow a where
  maybeShow :: a -> Maybe String

instance {-# OVERLAPPABLE #-} MaybeShow a where
  maybeShow _ = Nothing
</code>```

You then specialize it selectively to the few types you are using to debug.

```<code>instance MaybeShow Int where
  maybeShow n = Just (show n)
</code>```

However you still need to add a MaybeShow constraint to every function that uses it.

Here you can often use PartialTypeSignatures to write more concise toplevel signatures

```<code>myFun :: _ => a -> w a
constrainedFun :: (_, RealConstraint a) => a -> b a
</code>```

This method however has the advantage of having much more predictable behavior.

Title: Fire rewrite rule on class constraint

Body:
I'm trying to write a maybeShow function which is show but without a Show class constraint. Here's my attempt:

{-# INLINE [1] maybeShow #-}
maybeShow :: a -> Maybe String
maybeShow _ = Nothing

canShow :: Show a => a -> Maybe String
canShow = Just . show

data CantShow = CantShow

main = do
  print (maybeShow (42 :: Int))
  print (maybeShow CantShow)

{-# RULES
"maybeShow" forall (x :: (Show a => a)). maybeShow x = canShow x
#-}

But in this code, the rewrite rule never seems to fire.

I know this will sometimes return Nothing for showable types. For example, I entirely expect uses of maybeShow in non-inlined functions which are not specialised to a particular type to return Nothing. But as I'm using maybeShow as something to add to the output of error, it doesn't really matter if it doesn't always work.

But I'd like it to sometimes work (for example, when it's been inlined into the calling function) rather than never as seems to be currently the case.

Any ideas on how to get the rewrite rule to fire? This on wiki.haskell.org suggests it can be done, but the advice dates back to GHC 6.6 so I'm not sure it's still valid.

Body:
The requirements are still unclear to me, but I can't think of other solutions than the following two, e.g., to debug a library of polymorphic functions by tracing trace values of parametric types, but adding a Show constraint would break code downstream.

Use rewrite rules on monomorphic types. I assume that for debugging purposes, you need only a few types. However this may be rather unreliable, and you might need to specialise/inline functions explicitly.

Perhaps you can get by with another type class with a blanket overlappable instance.

class MaybeShow a where
  maybeShow :: a -> Maybe String

instance {-# OVERLAPPABLE #-} MaybeShow a where
  maybeShow _ = Nothing

You then specialize it selectively to the few types you are using to debug.

instance MaybeShow Int where
  maybeShow n = Just (show n)

However you still need to add a MaybeShow constraint to every function that uses it.

Here you can often use PartialTypeSignatures to write more concise toplevel signatures

myFun :: _ => a -> w a
constrainedFun :: (_, RealConstraint a) => a -> b a

This method however has the advantage of having much more predictable behavior.


问:
Is Restlet returning 415 Unsupported Media Type when it should return 400 Bad Request?
I'm using Restlet 2.1 with jackson to build a json REST api.

When I make a request with the expected content type but a malformed body, I get back a 415 "Unsuppored Media Type" status code. I think the correct error code should be 400 "Bad Request".

Apparently the mixup happens when Jackson tries and fails to decode the garbage.

I'll try to make the case more clear with some code:

```<code>// java method mapping
@Post("json")
public Project create(Project project) {
</code>```

The service invocation with curl

```<code>$ curl -i -XPOST -H 'content-type: application/json' -d '{xgarbage}' http://localhost:8080/projects HTTP/1.1 415 Unsupported Media Type
</code>```

And a fragmente of the stack trace os recorde in the logs:

```<code>Nov 29, 2010 9:51:56 PM org.restlet.ext.jackson.JacksonRepresentation getObject
WARNING: Unable to parse the object with Jackson.
org.codehaus.jackson.JsonParseException: Unexpected character ('x' (code 120)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.ByteArrayInputStream@693e4a5a; line: 1, column: 2]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:929)
</code>```

The actual implementation of the service is never hit, so somewhere a decision is made to map the garbled content to a 415.

Now, my question is: is this correct? If I'm reading correctly the following quotes from the book "RESTful Web Services", it is not, but I'm open to corrections.

[400 Bad Request] It’s commonly used when the client submits a representation along with a PUT or POST request, and the representation is in the right format, but it doesn’t make any sense.

.

[415 Unsupported Media Type] If the client sends a document that’s got the right media type but the wrong format (such as an XML document written in the wrong vocabulary), a better response is the more generic 400 (“Bad Request”)

Right or wrong, I'd prefer to return a 400.

Is there a way to change the behaviour without renouncing at the auto-magic serialisation provided by Jackson?

Any help is greatly appreciated,
thanks!

答:
415 is correct, as the request is NOT in the right format if it is corrupted in anyway. For example non-parseable JSON or XML. Malformed JSON or XML is NOT JSON or XML by definition, and thus is an unsupported media type, there is no way for Jackson to know that is is supposed to be JSON, it just knows that it isn't JSON that it can parse.

The offical documentation is really clear about this.

10.4.16 415 Unsupported Media Type

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

you said, hey this is JSON, and it isn't so the server says, hey, what I got isn't JSON and not supported by this resource.

Body:
I'm using Restlet 2.1 with jackson to build a json REST api.

When I make a request with the expected content type but a malformed body, I get back a 415 "Unsuppored Media Type" status code. I think the correct error code should be 400 "Bad Request".

Apparently the mixup happens when Jackson tries and fails to decode the garbage.

I'll try to make the case more clear with some code:

// java method mapping
@Post("json")
public Project create(Project project) {

The service invocation with curl

$ curl -i -XPOST -H 'content-type: application/json' -d '{xgarbage}' http://localhost:8080/projects HTTP/1.1 415 Unsupported Media Type

And a fragmente of the stack trace os recorde in the logs:

Nov 29, 2010 9:51:56 PM org.restlet.ext.jackson.JacksonRepresentation getObject
WARNING: Unable to parse the object with Jackson.
org.codehaus.jackson.JsonParseException: Unexpected character ('x' (code 120)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.ByteArrayInputStream@693e4a5a; line: 1, column: 2]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:929)

The actual implementation of the service is never hit, so somewhere a decision is made to map the garbled content to a 415.

Now, my question is: is this correct? If I'm reading correctly the following quotes from the book "RESTful Web Services", it is not, but I'm open to corrections.

[400 Bad Request] It’s commonly used when the client submits a representation along with a PUT or POST request, and the representation is in the right format, but it doesn’t make any sense.

.

[415 Unsupported Media Type] If the client sends a document that’s got the right media type but the wrong format (such as an XML document written in the wrong vocabulary), a better response is the more generic 400 (“Bad Request”)

Right or wrong, I'd prefer to return a 400.

Is there a way to change the behaviour without renouncing at the auto-magic serialisation provided by Jackson?

Any help is greatly appreciated,
thanks!


问:
2 PickerViews on same ViewController - titleForRow fund "will not be executed"
I've tagged the PickerViews 1 and 2 but I'm getting a "will not be executed" message on the func titleForRow, how do I solve this?

```<code>@IBOutlet weak var shoeDetailPic: UIImageView!
@IBOutlet weak var shoeDetailName: UILabel!
@IBOutlet weak var shoeDetailPrice: UILabel!
@IBOutlet weak var shoeColourPickerView: UIPickerView!
@IBOutlet weak var shoeSizePickerView: UIPickerView!

var pickerColour = [""]
var pickerSize = [""]

var getName = String()
var getPrice = String()
var getImage = UIImage()

override func viewDidLoad() {
super.viewDidLoad()

shoeDetailPic.image = getImage
shoeDetailName.text = getName
shoeDetailPrice.text = getPrice

pickerColour = ["Gold", "Black", "Red"]
pickerSize = ["35", "36", "37", "38", "39", "40", "41", "42"]

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1

}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component:   Int) -> Int {
    if (pickerView.tag == 1){
        return pickerColour.count
    }else{
        return pickerSize.count
    }
</code>```

Message here - will not be executed. Is it something to do with the IBOutlet names?

```<code>  func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent    component: Int) -> String?{
        if (pickerView.tag == 1){
            return "\(pickerColour[row])"
        }else{
            return "\(pickerSize[row])"
        }

}
}
}
</code>```

答:
Problem is you have put titleForRow delegate method inside the numberOfRowsInComponent, it should be outside of that method as instance method of class.

```<code>func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if (pickerView == shoeColourPickerView){
        return pickerColour.count
    }else{
        return pickerSize.count
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if (pickerView == shoeColourPickerView){
        return pickerColour[row]
    }else{
        return pickerSize[row]
    }

}
</code>```

Note: You have already created outlet for both pickerView then instead of comparing tag in delegate method it is batter if you compare with your outlet.

Body:
I've tagged the PickerViews 1 and 2 but I'm getting a "will not be executed" message on the func titleForRow, how do I solve this?

@IBOutlet weak var shoeDetailPic: UIImageView!
@IBOutlet weak var shoeDetailName: UILabel!
@IBOutlet weak var shoeDetailPrice: UILabel!
@IBOutlet weak var shoeColourPickerView: UIPickerView!
@IBOutlet weak var shoeSizePickerView: UIPickerView!

var pickerColour = [""]
var pickerSize = [""]

var getName = String()
var getPrice = String()
var getImage = UIImage()

override func viewDidLoad() {
super.viewDidLoad()

shoeDetailPic.image = getImage
shoeDetailName.text = getName
shoeDetailPrice.text = getPrice

pickerColour = ["Gold", "Black", "Red"]
pickerSize = ["35", "36", "37", "38", "39", "40", "41", "42"]

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1

}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component:   Int) -> Int {
    if (pickerView.tag == 1){
        return pickerColour.count
    }else{
        return pickerSize.count
    }

Message here - will not be executed. Is it something to do with the IBOutlet names?

  func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent    component: Int) -> String?{
        if (pickerView.tag == 1){
            return "\(pickerColour[row])"
        }else{
            return "\(pickerSize[row])"
        }

}
}
}

Body:
Problem is you have put titleForRow delegate method inside the numberOfRowsInComponent, it should be outside of that method as instance method of class.

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if (pickerView == shoeColourPickerView){
        return pickerColour.count
    }else{
        return pickerSize.count
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if (pickerView == shoeColourPickerView){
        return pickerColour[row]
    }else{
        return pickerSize[row]
    }

}

Note: You have already created outlet for both pickerView then instead of comparing tag in delegate method it is batter if you compare with your outlet.


问:
How to perform some action when the tab is selected in javafx scene builder?
This is my layout fxml file:

<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="443.0" prefWidth="610.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <TabPane fx:id="tabPane" layoutY="37.0" nodeOrientation="RIGHT_TO_LEFT" onContextMenuRequested="#event" prefHeight="400.0" prefWidth="610.0" tabClosingPolicy="UNAVAILABLE">
        <tabs>
          <Tab fx:id="total" closable="false" text="x" onSelectionChanged="#event">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
            </content>
          </Tab>
          <Tab text="x">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
            </content>
          </Tab>
            <Tab text="y">
               <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
               </content>
            </Tab>
            <Tab text="y">
               <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
               </content>
            </Tab>
        </tabs>
      </TabPane>
   </children>
</Pane>
```

I want to perform an action if the user clicks on the tab with total id but I used onSelectionChanged and that can not help me. How I can handle it if user clicks on the total id tab?

答:
Please try the code below;</p>

```<code>tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>()
{
    @Override
    public void changed(ObservableValue<? extends Tab> ov, Tab t, Tab t1)
    {
       if ("total".equals(t1.getId()))
       {
        //TODO
       }
    }
});
</code>```

Body:
This is my layout fxml file:

<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="443.0" prefWidth="610.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <TabPane fx:id="tabPane" layoutY="37.0" nodeOrientation="RIGHT_TO_LEFT" onContextMenuRequested="#event" prefHeight="400.0" prefWidth="610.0" tabClosingPolicy="UNAVAILABLE">
        <tabs>
          <Tab fx:id="total" closable="false" text="x" onSelectionChanged="#event">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
            </content>
          </Tab>
          <Tab text="x">
            <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
            </content>
          </Tab>
            <Tab text="y">
               <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
               </content>
            </Tab>
            <Tab text="y">
               <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
               </content>
            </Tab>
        </tabs>
      </TabPane>
   </children>
</Pane>

I want to perform an action if the user clicks on the tab with total id but I used onSelectionChanged and that can not help me. How I can handle it if user clicks on the total id tab?

Body:
Please try the code below;

tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>()
{
    @Override
    public void changed(ObservableValue<? extends Tab> ov, Tab t, Tab t1)
    {
       if ("total".equals(t1.getId()))
       {
        //TODO
       }
    }
});


问:
how to reset value of groups of a Test method in TestNG when running the programme
With two groups defined already:

```<code>public class GroupA {

    @BeforeGroups(groups = "groupA")
    public void beforeGroup1(){
        System.out.println("In before GroupA");
    }
}

public class GroupB {

    @BeforeGroups(groups = "groupB")
    public void beforeGroup1(){
        System.out.println("In beforeGroupB");
    }
}
</code>```

The test class is:

```<code>public class TestCls {

    @Test(groups="groupA")
    public void test(){
        System.out.println("In Test Class");
    }

}
</code>```

in the code of BeforeSuite, trying to reset the value of groups to "groupB" using the following code, it doesn't work as expected.

```<code>public class Suite {

    @BeforeSuite()
    public void test() throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ct = pool.get(TestCls.class.getName());

        //reset attribute groups from groupA to groupB
        CtMethod ctMethod = ct.getDeclaredMethod("test");
        MethodInfo ctMethodInfo = ctMethod.getMethodInfo();
        ConstPool cp = ctMethodInfo.getConstPool();

        //reset attribute groups from groupA to groupB
        AnnotationsAttribute attribute = (AnnotationsAttribute)ctMethodInfo.getAttribute(AnnotationsAttribute.visibleTag);
        Annotation annotation = attribute.getAnnotation("org.testng.annotations.Test");
        ArrayMemberValue arrayMemberValue = new ArrayMemberValue(cp);
        StringMemberValue[] memberValues = new StringMemberValue[]{new StringMemberValue("groupB", cp)};
        arrayMemberValue.setValue(memberValues);
        annotation.addMemberValue("groups", arrayMemberValue);
        attribute.setAnnotation(annotation);
        ctMethodInfo.addAttribute(attribute);

        //check if groups changed successfully
        Annotation annotation2 = attribute.getAnnotation("org.testng.annotations.Test");
        MemberValue[] text = ((ArrayMemberValue)annotation2.getMemberValue("groups")).getValue();
        System.out.println("the groups after modified is " + text[0]);
    }
}
</code>```

the output is

```<code>the groups after modified is groupB
In beforeGroup1
In Test Class
</code>```

答:
If you want to modify TestNG annotation values at runtime, you can use an AnnotationTransformer.</p>

```<code>public class MyTransformer implements IAnnotationTransformer {
  public void transform(ITest annotation, Class<?> testClass,
      Constructor testConstructor, Method testMethod) {
    annotation.setGroups(new String[]{"groupB"});
  }
}
</code>```

Body:
With two groups defined already:

public class GroupA {

    @BeforeGroups(groups = "groupA")
    public void beforeGroup1(){
        System.out.println("In before GroupA");
    }
}

public class GroupB {

    @BeforeGroups(groups = "groupB")
    public void beforeGroup1(){
        System.out.println("In beforeGroupB");
    }
}

The test class is:

public class TestCls {

    @Test(groups="groupA")
    public void test(){
        System.out.println("In Test Class");
    }

}

in the code of BeforeSuite, trying to reset the value of groups to "groupB" using the following code, it doesn't work as expected.

public class Suite {

    @BeforeSuite()
    public void test() throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ct = pool.get(TestCls.class.getName());

        //reset attribute groups from groupA to groupB
        CtMethod ctMethod = ct.getDeclaredMethod("test");
        MethodInfo ctMethodInfo = ctMethod.getMethodInfo();
        ConstPool cp = ctMethodInfo.getConstPool();

        //reset attribute groups from groupA to groupB
        AnnotationsAttribute attribute = (AnnotationsAttribute)ctMethodInfo.getAttribute(AnnotationsAttribute.visibleTag);
        Annotation annotation = attribute.getAnnotation("org.testng.annotations.Test");
        ArrayMemberValue arrayMemberValue = new ArrayMemberValue(cp);
        StringMemberValue[] memberValues = new StringMemberValue[]{new StringMemberValue("groupB", cp)};
        arrayMemberValue.setValue(memberValues);
        annotation.addMemberValue("groups", arrayMemberValue);
        attribute.setAnnotation(annotation);
        ctMethodInfo.addAttribute(attribute);

        //check if groups changed successfully
        Annotation annotation2 = attribute.getAnnotation("org.testng.annotations.Test");
        MemberValue[] text = ((ArrayMemberValue)annotation2.getMemberValue("groups")).getValue();
        System.out.println("the groups after modified is " + text[0]);
    }
}

the output is

the groups after modified is groupB
In beforeGroup1
In Test Class

Body:
If you want to modify TestNG annotation values at runtime, you can use an AnnotationTransformer.

public class MyTransformer implements IAnnotationTransformer {
  public void transform(ITest annotation, Class<?> testClass,
      Constructor testConstructor, Method testMethod) {
    annotation.setGroups(new String[]{"groupB"});
  }
}


问:
Pandas forward fill with maximum until position
My DataFrame looks like this:

```<code>pd.DataFrame([3,1,2,5,2], columns=['Var'], index=pd.date_range('2017-01-01',periods=5))
            Var
2017-01-01    3
2017-01-02    1
2017-01-03    2
2017-01-04    5
2017-01-05    2
</code>```

And i want to create a new column with the maximum value until time period like this:

```<code>            Var   MaxVar
2017-01-01    3     3
2017-01-02    1     3
2017-01-03    2     3
2017-01-04    5     5
2017-01-05    2     5
</code>```

Is this possible with pandas ?

Body:
My DataFrame looks like this:

pd.DataFrame([3,1,2,5,2], columns=['Var'], index=pd.date_range('2017-01-01',periods=5))
            Var
2017-01-01    3
2017-01-02    1
2017-01-03    2
2017-01-04    5
2017-01-05    2

And i want to create a new column with the maximum value until time period like this:

            Var   MaxVar
2017-01-01    3     3
2017-01-02    1     3
2017-01-03    2     3
2017-01-04    5     5
2017-01-05    2     5

Is this possible with pandas ?

Body:
use Series.cummax() method:

In [146]: df['MaxVar'] = df.Var.cummax()

In [147]: df
Out[147]:
            Var  MaxVar
2017-01-01    3       3
2017-01-02    1       3
2017-01-03    2       3
2017-01-04    5       5
2017-01-05    2       5


问:
ASP checkbox value incorrect when AutoPostBack is set to false
I am still relatively new at VB.Net and Visual Studio and I'm assuming that this is a simple fix, but I'm not sure.

I have an asp:checkbox control on an aspx page I am working on.  This checkbox is within a custom control and previously was posting back every time it was clicked.  I am in the process of ajaxifying the page and have come across a problem.  When I remove the attribute AutoPostBack="True" from the asp:checkbox, the vb code returns False when I check myCheckbox.checked (this is on a postback else where on the page what has not be ajaxified), even though I can see the box is indeed checked.

I am assuming that because the checkbox no longer posts back, for some reason the VB code (or the view state maybe) doesn't see it as having been checked.  Is this correct, and if so, how to I correct it?

答: I changed the checkbox from an ASP control to be an HTML input of type checkbox and now it works :) </p>


问:
ios7 navigation bar : 3 strange dots appearing when back animation with custom button
I would like to use the back navigation animation using

```<code>[self.navigationController popViewControllerAnimated:YES]
</code>```

with a custom button added to the navigation bar.

As I don't want the back button to be seen, i've hidden it with     self.navigationItem.hidesBackButton = YES;

But during the back animation, on ios7 (not ios6) 3 dots can be seen sliding in the navigation bar.
They are not appearing with self.navigationItem.hidesBackButton = NO; but of course the button can be seen.

Does anyone has any idea to make them not appearing ?

答:
You don't need to write any code just follow 4 simple step and you done it.

Select your Main.storyboard

Select Navigation Bar in Navigation Controller

Select Attributes Inspector

Clear Tint color

Body:
I would like to use the back navigation animation using

[self.navigationController popViewControllerAnimated:YES]

with a custom button added to the navigation bar.

As I don't want the back button to be seen, i've hidden it with     self.navigationItem.hidesBackButton = YES;

But during the back animation, on ios7 (not ios6) 3 dots can be seen sliding in the navigation bar.
They are not appearing with self.navigationItem.hidesBackButton = NO; but of course the button can be seen.

Does anyone has any idea to make them not appearing ?


问:
Why do people hate SQL cursors so much?
I can understand wanting to avoid having to use a cursor due to the overhead and inconvenience, but it looks like there's some serious cursor-phobia-mania going on where people are going to great lengths to avoid having to use one.

For example, one question asked how to do something obviously trivial with a cursor and the accepted answer proposed using a common table expression (CTE) recursive query with a recursive custom function, even though this limits the number of rows that could be processed to 32 (due to recursive function call limit in sql server). This strikes me as a terrible solution for system longevity, not to mention a tremendous effort just to avoid using a simple cursor.

What is the reason for this level of insane hatred? Has some 'noted authority' issued a fatwa against cursors? Does some unspeakable evil lurk in the heart of cursors that corrupts the morals of children or something?

Wiki question, more interested in the answer than the rep.

Related Info:

SQL Server Fast Forward Cursors

EDIT: let me be more precise: I understand that cursors should not be used instead of normal relational operations; that is a no-brainer. What I don't understand is people going waaaaay out of their way to avoid cursors like they have cooties or something, even when a cursor is a simpler and/or more efficient solution. It's the irrational hatred that baffles me, not the obvious technical efficiencies.

答:
In Oracle PL/SQL cursors will not result in table locks and it is possible to use bulk-collecting/bulk-fetching.

In Oracle 10 the often used implicit cursor

```<code>  for x in (select ....) loop
    --do something
  end loop;
</code>```

fetches implicitly 100 rows at a time. Explicit bulk-collecting/bulk-fetching is also possible.

However PL/SQL cursors are something of a last resort, use them when you are unable to solve a problem with set-based SQL.

Another reason is parallelization, it is easier for the database to parallelize big set-based statements than row-by-row imperative code. It is the same reason why functional programming becomes more and more popular (Haskell, F#, Lisp, C# LINQ, MapReduce ...), functional programming makes parallelization easier. The number CPUs per computer is rising so parallelization becomes more and more an issue.

OwnerDisplayName: Steven A. Lowe

Title: Why do people hate SQL cursors so much?

LastEditorDisplayName: Steven A. Lowe

Body:
In Oracle PL/SQL cursors will not result in table locks and it is possible to use bulk-collecting/bulk-fetching.

In Oracle 10 the often used implicit cursor

  for x in (select ....) loop
    --do something
  end loop;

fetches implicitly 100 rows at a time. Explicit bulk-collecting/bulk-fetching is also possible.

However PL/SQL cursors are something of a last resort, use them when you are unable to solve a problem with set-based SQL.

Another reason is parallelization, it is easier for the database to parallelize big set-based statements than row-by-row imperative code. It is the same reason why functional programming becomes more and more popular (Haskell, F#, Lisp, C# LINQ, MapReduce ...), functional programming makes parallelization easier. The number CPUs per computer is rising so parallelization becomes more and more an issue.

OwnerDisplayName: tuinstoel


问:
Cartesian product data frame
I have three or more independent variables represented as R vectors, like so:

```<code>A <- c(1,2,3)
B <- factor(c('x','y'))
C <- c(0.1,0.5)
</code>```

and I want to take the Cartesian product of all of them and put the result into a data frame, like this:

```<code>A B C
1 x 0.1
1 x 0.5
1 y 0.1
1 y 0.5
2 x 0.1
2 x 0.5
2 y 0.1
2 y 0.5
3 x 0.1
3 x 0.5
3 y 0.1
3 y 0.5
</code>```

I can do this by manually writing out calls to rep:

```<code>d <- data.frame(A = rep(A, times=length(B)*length(C)),
                B = rep(B, times=length(A), each=length(C)),
                C = rep(C, each=length(A)*length(B))
</code>```

but there must be a more elegant way to do it, yes?  product in itertools does part of the job, but I can't find any way to absorb the output of an iterator and put it into a data frame.  Any suggestions?

p.s. The next step in this calculation looks like

```<code>d$D <- f(d$A, d$B, d$C)
</code>```

so if you know a way to do both steps at once, that would also be helpful.

答:
You can use expand.grid(A, B, C)

EDIT: an alternative to using do.call to achieve the second part, is the function mdply from the package plyr:

library(plyr)

d = expand.grid(x = A, y = B, z = C)
d = mdply(d, f)
```
<p>To illustrate its usage using a trivial function 'paste', you can try</p>
<pre class="lang-r prettyprint-override"><code>d = mdply(d, 'paste', sep = '+');
</code>```

Title: Cartesian product data frame

Body:
I have three or more independent variables represented as R vectors, like so:

A <- c(1,2,3)
B <- factor(c('x','y'))
C <- c(0.1,0.5)

and I want to take the Cartesian product of all of them and put the result into a data frame, like this:

A B C
1 x 0.1
1 x 0.5
1 y 0.1
1 y 0.5
2 x 0.1
2 x 0.5
2 y 0.1
2 y 0.5
3 x 0.1
3 x 0.5
3 y 0.1
3 y 0.5

I can do this by manually writing out calls to rep:

d <- data.frame(A = rep(A, times=length(B)*length(C)),
                B = rep(B, times=length(A), each=length(C)),
                C = rep(C, each=length(A)*length(B))

but there must be a more elegant way to do it, yes?  product in itertools does part of the job, but I can't find any way to absorb the output of an iterator and put it into a data frame.  Any suggestions?

p.s. The next step in this calculation looks like

d$D <- f(d$A, d$B, d$C)

so if you know a way to do both steps at once, that would also be helpful.

Body:
You can use expand.grid(A, B, C)

EDIT: an alternative to using do.call to achieve the second part, is the function mdply from the package plyr:

library(plyr)

d = expand.grid(x = A, y = B, z = C)
d = mdply(d, f)

To illustrate its usage using a trivial function 'paste', you can try

d = mdply(d, 'paste', sep = '+');