vendredi 11 septembre 2015

Styling a nested XML element with XSLT?

I’m a print designer working on a travel guide that we recently started managing with XML-tagged content and XSLT styling. It mostly works, aside from this one small issue that has driven us to wit’s end! We have some sub-attraction listings that should appear as “child” listings that we can style differently in InDesign layout, and they’re noted in the XML by noting a value for their “parent” attraction in the MainAttraction tag.

My understanding is that we need the .XSL to notice whether there’s a value in the MainAttraction tags, and if there is, then to pull out the elements associated with that attraction to go under a different container tag so we can style them differently. I just haven’t had any luck writing syntax for this that works after doing some basic training and Googling around forums.

Here's what I'm experimenting with, which pulls in everything correctly except for sub-attractions (they're listed within the Attraction tags for their associated parent listing):

XSLT

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://ift.tt/tCZ8VR" version="1.0">

    <xsl:template match="/">

    <Cities>
        <xsl:for-each select="Root/City">
            <City>
                <City_Name>
                    <xsl:value-of select="City_Name"/>
                </City_Name>
                <xsl:text>&#xa;</xsl:text>
                <City_Stats>
                    <xsl:text>POP. </xsl:text>
                    <xsl:value-of select="Population"/>
                    <xsl:text>  ALT. </xsl:text>
                    <xsl:value-of select="Altitude"/>
                    <xsl:text>  MAP </xsl:text>
                    <xsl:value-of select="Map_Grid_Location"/>
                </City_Stats>
                <xsl:text>&#xa;</xsl:text>

                <Visitor_Info>

                    <Visitor_Center>
                        <xsl:value-of select="Visitor_Center"/><xsl:text>: </xsl:text>
                    </Visitor_Center>

                    <Visitor_Information>

                        <xsl:value-of select="Visitor_Information"/><xsl:text> </xsl:text>
                        <xsl:value-of select="Address"/>
                        <xsl:text> </xsl:text>

                        <xsl:value-of select="normalize-space(Phone1)"/>
                            <xsl:if test="string-length(Phone2) &gt; 0">
                            <xsl:text> or </xsl:text>
                            <xsl:value-of select="Phone2"/>
                            </xsl:if>
                            <xsl:if test="string-length(Phone1) &gt; 0">
                            <xsl:text>. </xsl:text>
                            </xsl:if>


                        <xsl:value-of select="normalize-space(Website1)"/>
                            <xsl:if test="string-length(Website2) &gt; 0">
                            <xsl:text> or </xsl:text>
                            <xsl:value-of select="Website2"/>
                            </xsl:if>
                            <xsl:if test="string-length(Website1) &gt; 0">
                            <xsl:text>. </xsl:text>
                            </xsl:if>


                        </Visitor_Information>

                    </Visitor_Info>
                <xsl:text>&#xa;</xsl:text>

                <Description>
                    <xsl:value-of select="Description"/>
                </Description>
                    <xsl:text>&#xa;</xsl:text>

                <Attractions>
                    <xsl:apply-templates select="Attraction"/>
                </Attractions>



            </City>

        </xsl:for-each>

    </Cities>

    </xsl:template>


    <xsl:template match="Attraction">

        <Attraction>

                    <Attraction_Title>
                        <xsl:value-of select="normalize-space(Attraction_Title)"/>
                    </Attraction_Title>
                    <xsl:text>&#8212;</xsl:text>

                    <xsl:value-of select="Desc"/><xsl:text> </xsl:text>

                    <xsl:value-of select="normalize-space(Admissions)"/>
                        <xsl:if test="string-length(Admissions) &gt; 0">
                            <xsl:text>. </xsl:text>
                        </xsl:if>

                    <xsl:value-of select="normalize-space(Address)"/>
                    <xsl:if test="string-length(Address) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:value-of select="normalize-space(Directions)"/>
                <xsl:if test="string-length(Directions) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Phone)"/>
                <xsl:if test="string-length(AltPhone) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(AltPhone)"/>
                </xsl:if>

                <xsl:if test="string-length(Phone) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(WebAddress)"/>
                <xsl:if test="string-length(WebAddress2) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(WebAddress2)"/>
                </xsl:if>

                <xsl:if test="string-length(WebAddress) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Email)"/>
                    <xsl:if test="string-length(Email) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                    <xsl:if test="string-length(SeeAlso) &gt; 0">
                        <xsl:text> </xsl:text>
                        <xsl:text>See </xsl:text>
                        <xsl:value-of select="normalize-space(SeeAlso)"/>
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:text>&#xa;</xsl:text>

        </Attraction>

    </xsl:template>

    <xsl:template match="SubAttraction">

        <SubAttraction>

            <xsl:if test="string-length(MainAttraction) &gt; 0">

                <xsl:text>&#9;</xsl:text>

                    <SubAttraction_Title>
                        <xsl:value-of select="normalize-space(Attraction_Title)"/>
                    </SubAttraction_Title>
                    <xsl:text>&#8212;</xsl:text>

                    <xsl:value-of select="Desc"/><xsl:text> </xsl:text>

                    <xsl:value-of select="normalize-space(Admissions)"/>
                        <xsl:if test="string-length(Admissions) &gt; 0">
                            <xsl:text>. </xsl:text>
                        </xsl:if>

                    <xsl:value-of select="normalize-space(Address)"/>
                    <xsl:if test="string-length(Address) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:value-of select="normalize-space(Directions)"/>
                <xsl:if test="string-length(Directions) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Phone)"/>
                <xsl:if test="string-length(AltPhone) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(AltPhone)"/>
                </xsl:if>

                <xsl:if test="string-length(Phone) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(WebAddress)"/>
                <xsl:if test="string-length(WebAddress2) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(WebAddress2)"/>
                </xsl:if>

                <xsl:if test="string-length(WebAddress) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Email)"/>
                    <xsl:if test="string-length(Email) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:text>&#xa;</xsl:text>

            </xsl:if>

        </SubAttraction>

    </xsl:template>

</xsl:stylesheet>

XML INPUT SAMPLE (note that the sub-attraction example, the Fredda Turner Durham Children's Museum, has a value in its Main Attraction tags and is nested within the attraction tags for its parent listing)

<?xml version="1.0" encoding="UTF-8"?>

<Root>
    <City>
        <City_Name>MIDLAND</City_Name>
        <Region>BIG BEND COUNTRY</Region>
        <Population>127,598</Population>
        <Altitude>2,891</Altitude>
        <Map_Grid_Location>L-9/KK-4</Map_Grid_Location>
        <Visitor_Center>Midland Visitors Center</Visitor_Center>                    <Visitor_Information>Midland Convention &amp; Visitors Bureau: Open 8 a.m.-5 p.m. Mon.-Sat. 109 N Main St. 800/624-6435.</Visitor_Information><Address>1406 W. I-20 (Exit 136).</Address><Hours>Open 9 a.m.-5 p.m. Mon.-Sat.</Hours><Phone1>432/683-2882</Phone1><Phone2>800/624-6435</Phone2><Website1>&lt;a href="http://ift.tt/ZyZBJr" &gt;http://ift.tt/1Kft3Yo;
        <CityId>MIDLAND</CityId>
        <Description>Description text goes here.</Description>

        <Attraction>
            <Attraction_Title>Haley Library &amp; History Center</Attraction_Title>
            <Desc>Description text goes here. </Desc>
            <Admissions>Donations accepted.</Admissions>
            <Hours>Open 9 a.m.-5 p.m. Mon.-Fri.</Hours>
            <Address>1805 W. Indiana Ave.</Address>
            <Directions></Directions>
            <Phone>432/682-5785</Phone>
            <AltPhone></AltPhone>
            <WebAddress></WebAddress>
            <WebAddress2></WebAddress2>
            <Email></Email>
            <SeeAlso></SeeAlso>
            <MainAttraction></MainAttraction>
        </Attraction>

        <Attraction>
            <Attraction_Title>I-20 Wildlife Preserve &amp; Jenna Welch Nature Study Center</Attraction_Title>
            <Desc>Description text goes here.</Desc>
            <Admissions></Admissions>
            <Hours>Open dusk–dawn daily.</Hours>
            <Address>2201 S. Midland Dr.</Address>
            <Phone>432/853-9453</Phone>
            <AltPhone></AltPhone>
            <WebAddress>http://ift.tt/1gf6NS9;
            <WebAddress2></WebAddress2>
            <Email></Email>
            <SeeAlso></SeeAlso>
            <MainAttraction></MainAttraction>
        </Attraction>

        <Attraction>
            <Attraction_Title>Museum of the Southwest</Attraction_Title>
            <Desc>Description text goes here.</Desc>
            <Admissions>Admission charged.</Admissions>
            <Hours>Open 10 a.m.-5 p.m. Tue.-Sat. and 2-5 p.m. Sun.</Hours>
            <Address>1705 W. Missouri.</Address>
            <Directions></Directions>
            <Phone>432/683-2882</Phone>
            <AltPhone></AltPhone>
            <WebAddress>http://ift.tt/1Kft2ni;
            <WebAddress2></WebAddress2>
            <Email></Email>
            <SeeAlso></SeeAlso>
            <MainAttraction></MainAttraction>

                <Attraction>
                    <Attraction_Title>Fredda Turner Durham Children's Museum</Attraction_Title>
                    <Desc>Description text goes here.</Desc>
                    <Admissions>Admission charge.</Admissions>
                    <Hours>Open 10 a.m.-5 p.m. Tue.-Sat. and 2-5 p.m. Sun. Free admission on Sundays.</Hours>
                    <Address></Address><Directions></Directions><Phone>432/683-2882</Phone><AltPhone></AltPhone><WebAddress></WebAddress><WebAddress2></WebAddress2><Email></Email><SeeAlso></SeeAlso><MainAttraction>Museum of the Southwest</MainAttraction>

            </Attraction>

        </Attraction>

    </City>

</Root>

CURRENT OUTPUT (the sub-attraction doesn't display)

    <?xml version="1.0" encoding="UTF-8"?>
<Cities>
   <City>
      <City_Name>MIDLAND</City_Name>
      <City_Stats>POP. 127,598  ALT. 2,891  MAP L-9/KK-4</City_Stats>
      <Visitor_Info>
         <Visitor_Center>Midland Visitors Center:</Visitor_Center>
         <Visitor_Information>Midland Convention &amp; Visitors Bureau: Open 8 a.m.-5 p.m. Mon.-Sat. 109 N Main St. 800/624-6435. 1406 W. I-20 (Exit 136). 432/683-2882 or 800/624-6435. &lt;a href="http://ift.tt/ZyZBJr" &gt;http://ift.tt/1gf6MO6;
      </Visitor_Info>
      <Description>Description text goes here.</Description>
      <Attractions>
         <Attraction>
            <Attraction_Title>Haley Library &amp; History Center</Attraction_Title>
            —Description text goes here.  Donations accepted.. 1805 W. Indiana Ave.. 432/682-5785.
         </Attraction>
         <Attraction>
            <Attraction_Title>I-20 Wildlife Preserve &amp; Jenna Welch Nature Study Center</Attraction_Title>
            —Description text goes here. 2201 S. Midland Dr.. 432/853-9453. http://ift.tt/1Kft3Yq.
         </Attraction>
         <Attraction>
            <Attraction_Title>Museum of the Southwest</Attraction_Title>
            —Description text goes here. Admission charged.. 1705 W. Missouri.. 432/683-2882. www.museumsw.org.
         </Attraction>
      </Attractions>
   </City>
</Cities>

DESIRED OUTPUT (the sub-attraction displays and had its own container tags)

<?xml version="1.0" encoding="UTF-8"?>
<Cities>
   <City>
      <City_Name>MIDLAND</City_Name>
      <City_Stats>POP. 127,598  ALT. 2,891  MAP L-9/KK-4</City_Stats>
      <Visitor_Info>
         <Visitor_Center>Midland Visitors Center:</Visitor_Center>
         <Visitor_Information>Midland Convention &amp; Visitors Bureau: Open 8 a.m.-5 p.m. Mon.-Sat. 109 N Main St. 800/624-6435. 1406 W. I-20 (Exit 136). 432/683-2882 or 800/624-6435. &lt;a href="http://ift.tt/ZyZBJr" &gt;http://ift.tt/1gf6MO6;
      </Visitor_Info>
      <Description>Description text goes here.</Description>
      <Attractions>
         <Attraction>
            <Attraction_Title>Haley Library &amp; History Center</Attraction_Title>
            —Description text goes here.  Donations accepted.. 1805 W. Indiana Ave.. 432/682-5785.
         </Attraction>
         <Attraction>
            <Attraction_Title>I-20 Wildlife Preserve &amp; Jenna Welch Nature Study Center</Attraction_Title>—Description text goes here. 2201 S. Midland Dr.. 432/853-9453. http://ift.tt/1Kft3Yq.
         </Attraction>
         <Attraction>
            <Attraction_Title>Museum of the Southwest</Attraction_Title>—Description text goes here. Admission charged.. 1705 W. Missouri.. 432/683-2882. www.museumsw.org.
         </Attraction>
         <SubAttraction>
            <SubAttraction_Title>Fredda Turner Durham Children's Museum</SubAttraction_Title>—Description text goes here. Admission charge.. 432/683-2882.
         </SubAttraction>
     </Attractions>
  </City>
</Cities>

So what do I do here to make it so sub-attractions (attractions with a value int he MainAttraction field) can get pulled into new container tags? I understand that we want to create a new template for SubAttractions, but I don't know how to get only the desired elements into it. I'd greatly appreciate help in finding something to plug in here if it's not too difficult for someone more experienced.

[Original post has been edited to provide more useful info.]



via Chebli Mohamed

Configure HTTPS port using netbeans

I have created one website using Netbeans on apache tomcat server using JSP. Currently, website is running on HTTP protocol. I just wanted to change the protocol from HTTP to secure protocol HTTPS. My website should only run on HTTPS port.

What configuration is required on server?

Please help me on this.



via Chebli Mohamed

Oracle numeric string column and indexing

I have a numeric string column in oracle with or without leading zeros samples:

00000000056
5755
0123938784579343
00000000333  
984454  

The issue is that partial Search operations using like are very slow

select account_number from accounts where account_number like %57%

one solution is to restrict the search to exact match only and add an additional integer column that will represent the numeric value for exact matches.
At this point I am not sure we can add an additional column,
Do you guys have any other ideas?

Is it possible to tell Oracle to index the numeric string column as an integer value so we can do exact numeric match on it?

for example query on value :00000000333
will be:

select account_number from accounts where account_number = '333'

While ignoring the leading zeros.
I can use regex_like and ignore them, but i am afraid its going to be slow.



via Chebli Mohamed

link in fastboot adb libraries into executeble

we are implementing an application in c/c++ which uses adb and fastboot. To use my application adb and fastboot should be installed. Is there any way to link in the fastboot, adb libraries into the executable so that its self-contained?

Thanks in Advance



via Chebli Mohamed

Get Cell Value with column name in Php Excel

This is my excel sheet Excel Sheet it has got lots of columns but i'm breaking down for ease in understanding the question

I'm reading Excel Sheet using PHP Excel and using rangeToArray() which give me all row from excel but i want the output as

Column as Key:Cell Value as Value

Currently I'm get output as

Col Index :Cell Value

So my Question is which is that function in Php Excel which return array with Column name and it Cell value?

try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
    die('Error loading file"'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++){ 
    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                            NULL,
                                            TRUE,
                                            FALSE);
    printArr($rowData);
    printArr("-------");

}

I get output as

Array
(
    [0] => Array
        (
            [0] => 27745186
            [1] => 42058
            [2] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
    [1] => Array
        (
            [0] => 27745186
            [1] => 42058
            [2] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
)

Desire Output

Array
(
    [0] => Array
        (
            [Invoice_no] => 27745186
            [Invoice Date] => 42058
            [Description] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
    [1] => Array
        (
            [Invoice_no] => 27745186
            [Invoice Date] => 42058
            [Description] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
)



via Chebli Mohamed

Angular datatable add row keep search value / display selected record

I have an angular datatable that is displaying "multiple" pages of 10 records each. If I use the search box to only view selected records and add a new row the table completely refreshes. The value in the search box is reset and my view goes back to the first page of records. Is it possible to maintain the value in the search box?

Similar but different. I have a radio button to select a record in the table. Is it possible when the table is redrawn to show the page with the selected record and not the first page.

enter image description here



via Chebli Mohamed

c++ not recognizing negative number as a number entered

In a program I have to write for class, I can not get the code to read a negative from cin to increment a variable by one.

int input;

while (input != 9999)
{
    sum += input;
    count ++;
}

There is other code that counts the number of pos, neg, and zeros entered. this is the only place count is used. so if I enter -10 then 9999, the sum is -10 and the number of negative is 1 but count says zero. i am using dev c++ as a compiler. and windows 10



via Chebli Mohamed

How can I show two background images, using internet explorer 6?

I need to show two background images. I'm doing this:

table.grid thead.grid-header th
{
    background: url('../images/up-down-arrow.gif') no-repeat center right, url('../images/tt-caption-light.gif') repeat;
}

This work fine in internet explorer 11, but I need to do this for internet explorer 6. How can I resolve it? Thank you very much!



via Chebli Mohamed

Invalid Swift Support - Files don’t match

I just re-wrote an app in Swift 2. I'm trying to upload the app to iTunesConnect (via Xcode 7 GM) for internal testing.

I wrestled with an "Invalid Swift Support" error for awhile (which has other, related questions) ... but now it's changed to something a little different.

The error from Apple now says:

Invalid Swift Support

The files libswiftCoreLocation.dylib, libswiftCoreMedia.dylib, libswiftCoreData.dylib, libswiftAVFoundation.dylib don’t match

/Payload/http://ift.tt/1XTi1Om, /Payload/http://ift.tt/1FBPwcO, /Payload/http://ift.tt/1XTi1Oo, /Payload/http://ift.tt/1FBPyBu

Make sure the files are correct (?), rebuild your app, and resubmit it.

Don’t apply post-processing to

/Payload/http://ift.tt/1XTi1Om, /Payload/http://ift.tt/1FBPwcO, /Payload/http://ift.tt/1XTi1Oo, /Payload/http://ift.tt/1FBPyBu.

I've been unable to find similar errors by searching for "Don’t apply post-processing", "Make sure the files are correct (?), rebuild your app, and resubmit it", etc.

Does anyone know how I can "Make sure the files are correct" --or-- any other recommendations? Thank you.



via Chebli Mohamed

C# FTP Download large files

i know this is probably not the first time, this is asked. But i can't find the solution to the problem..

  private void bgftpdownload_DoWork(object sender, DoWorkEventArgs e)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl + "/" + clientlabel.Text + "/data.7z");
        request.Credentials = new NetworkCredential(ftpuser, ftppass);
        request.Method = WebRequestMethods.Ftp.GetFileSize;
        request.Proxy = null;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        long fileSize = response.ContentLength;

        request = (FtpWebRequest)WebRequest.Create(ftpurl + "/" + clientlabel.Text + "/data.7z");
        request.Credentials = new NetworkCredential(ftpuser, ftppass);
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        using (FtpWebResponse responseFileDownload = (FtpWebResponse)request.GetResponse())
        using (Stream responseStream = responseFileDownload.GetResponseStream())
        using (FileStream writeStream = new FileStream(LocationFile, FileMode.Create))
        {

            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);
            int bytes = 0;

            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
                bytes += bytesRead;
                int totalSize = (int)(fileSize / 1048576);
                bgftpdownload.ReportProgress((bytes / 1048576) * 100 / totalSize, totalSize);
            }
        }
    }
    private void bgftpdownload_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
            progresslabel.Text = e.ProgressPercentage * (int)e.UserState / 100 + " Mb / " + e.UserState + " Mb";
            progressBar1.Value = e.ProgressPercentage;
    }

I have this code, and its working great.. until its hitting a 2 gb file on the ftp server

I can read on other forums, the value limit for (int) is = 2147483591 So the problem is off cause my byte is getting higher than limit (2147483591)

What can i do to fix this problem?



via Chebli Mohamed

Comparing fix fields in quickfix for python

How can I compare two fix fields in quickfix for python? I've tried this:

execType = fix.ExecType(fix.Exectype_NEW)
if execType == fix.ExecType(fix.ExecType_NEW):
   print 'success'

, but didn't succed. Is there any other way to do it?



via Chebli Mohamed

Spring cannot create filter on online server only (works fine on the localhost)

My Spring application deploys and works fine on my localhost but fails on the online server with the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private it.kahoot.robot.rest.filter.SimpleCORSFilter it.kahoot.robot.rest.config.WebSecurityConfiguration.simpleCORSFilter; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'simpleCORSFilter': Requested bean is currently in creation: Is there an unresolvable circular reference?
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanP

The filter class is:

@Component
public class SimpleCORSFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(SimpleCORSFilter.class);

    private static final String ORIGIN = "Origin";
    private static final String OPTIONS = "OPTIONS";
    private static final String OK = "OK";

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        if (httpServletRequest.getHeader(ORIGIN) != null) {
            String origin = httpServletRequest.getHeader(ORIGIN);
            httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Accept-Language,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Content-Disposition,Content-Length,"+CommonConstants.EXPORT_FILENAME_HEADER_NAME+","+CommonConstants.AUTH_HEADER_NAME);
            // Allow more than the 6 default headers to be returned, as the content length is required for a download file request to get the file size 
            httpServletResponse.setHeader("Access-Control-Expose-Headers", "Accept-Language,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Content-Disposition,Content-Length,"+CommonConstants.EXPORT_FILENAME_HEADER_NAME+","+CommonConstants.AUTH_HEADER_NAME);
        }

        if (httpServletRequest.getMethod().equals(OPTIONS)) {
            try {
                httpServletResponse.getWriter().print(OK);
                httpServletResponse.getWriter().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }       
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }

}

Again, it works just fine on my localhost.



via Chebli Mohamed

Should i implement a database or let operating system manage files(Media Library Application)

I'm writing a media library application.(Like iTunes). Users can have thousands of media files.(Some files may be small like music and some files may be large like movies) Users should do operations like search,add,remove,change info etc. fast enough. I'm trying to make a decision about how i store & retrive these files.

One way: Like itunes i can create a folder for library, in that folder i can create another folder for each artist, in each artist folder i can create a folder for each album and at last in album folder i can store music files. I'll create another file for storing information about music files(Album arts, lyrics and etc.) This way is easy to implement and manage. It will be fast also.

Second way: I can store everything in 1 file. I can use a database to store everything or i can use other methods like BinarySerialization and creating my own file type. This file type can have media file itself and it's information in it. I don't know if its possible. I don't know if it will be fast enough to extract a file and change smthng on it and storing it back.

Should i use itune's way or can you recommand another way to do it.



via Chebli Mohamed

JQuery hide Class if other class is visible

I know this question already have asked before and i also tried the answer and it almost worked for me but there is one issue which i can't able to sort i tried plenty of ways but all in wain. This is the div i want to hide

    <div class="price-box" itemprop="offers" itemscope="" itemtype="http://schema.org/Offer">

       <p class="price"><span class="special-price" style="display: none;">
        <span class="amount">$43.50</span>
        </span>
       </p>
    </div>

when this div is not empty

<div class="single_variation"><span class="price"><span class="amount">$43.50</span></span></div>

This is what i implement

  jQuery(document).ready(function() {

    if( jQuery('.single_variation').is(':empty') ){
      alert('hi');
        jQuery('.price-box').show();
      }

});

and also

if($('.price').length){ $('.price-box').hide(); }



via Chebli Mohamed

Is the $scope.$apply() call warranted for this scenario?

New to AngularJS (and JavaScript frankly), but from what I've gathered, explicit calls to $scope.$apply() are only needed when changes happen outside of angular's radar. The code below (pasted in from this plunker) makes me think it wouldn't be a case where the call is required, but it's the only way I can get it to work. Is there a different approach I should be taking?

index.html:

<html ng-app="repro">
  <head> 
    ...
  </head>
  <body class="container" ng-controller="pageController">
    <table class="table table-hover table-bordered">
        <tr class="table-header-row">
          <td class="table-header">Name</td>
        </tr>
        <tr class="site-list-row" ng-repeat="link in siteList">
          <td>{{link.name}}
            <button class="btn btn-danger btn-xs action-button" ng-click="delete($index)">
              <span class="glyphicon glyphicon-remove"></span>
            </button>
          </td>
        </tr>
    </table>
  </body>
</html>

script.js:

var repro = angular.module('repro', []);

var DataStore = repro.service('DataStore', function() {
  var siteList = [];

  this.getSiteList = function(callback) {
    siteList = [ 
      { name: 'One'}, 
      { name: 'Two'}, 
      { name: 'Three'}];

    // Simulate the async delay
    setTimeout(function() { callback(siteList); }, 2000);
  }

  this.deleteSite = function(index) {
    if (siteList.length > index) {
      siteList.splice(index, 1);
    }
  };
});

repro.controller('pageController', ['$scope', 'DataStore', function($scope, DataStore) {
  DataStore.getSiteList(function(list) {

    $scope.siteList = list; // This doesn't work
    //$scope.$apply(function() { $scope.siteList = list; }); // This works

  });

  $scope.delete = function(index) {
    DataStore.deleteSite(index);
  };
}]);



via Chebli Mohamed

lifetime of a variable inside a self invoking anonymous function - function closures

I'm studying function closures from http://ift.tt/1vKs8WG

I don't understand the below code. variable add refers to a self-invoking anonymous function which returns an anonymous function. In this case, what happens to variable counter? when we call function add, what happens?

<!DOCTYPE html>
<html>
<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function () {
    var counter = 0;    })();
    return function () {return counter += 1;}


function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>

in addition I dont understand why the code below does not work?

<!DOCTYPE html>
<html>
<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function () {
    var counter = 0;
    return function () 
           {
             var semih=0;
             if(counter >5) 
             {
                 return function(){ semih += 5;  }
             }
             return counter += 1;}
           }
)();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>



via Chebli Mohamed

Assign line colors in pandas

I am trying to plot some data in pandas and the inbuilt plot function conveniently plots one line per column. What I want to do is to manually assign each line a color based on a classification I make.

The following works:

df = pd.DataFrame({'1': [1, 2, 3, 4], '2': [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=['1','2'])
df.plot(color = s)

But when my indices are integers it no longer works and throws as KeyError:

df = pd.DataFrame({1: [1, 2, 3, 4], 2: [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=[1,2])
df.plot(color = s)

The way I understand it is that when an integer index is used it somehow has to start from 0. That is my guess since the following works as well:

df = pd.DataFrame({0: [1, 2, 3, 4], 1: [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=[1,0])
df.plot(color = s)

My question is:

  • What is happening here?
  • Assuming I have an integer index that does not start from 0 or is not formed of successive numbers, how can I make this work without having to convert the index to string or reindex starting from 0?

EDIT:

I realised that even in the first case, the code doesn't do what I expected it to do. It seems like pandas matches the index of DataFrame and Series only if both are integer indices starting from 0. If that isn't the case, a KeyError is thrown or if the index is a str the order of the elements is used.

Is this correct? And is there a way to match the Series and DataFrame indices? Or do I have to make sure I pass a list of colours in the right order?



via Chebli Mohamed

How to inscribe the following shape with CSS inside div?

FIDDLE enter image description here

HTML

<div id="DiamondCenter">
    <div id="triangle-topleft"></div>
</div>

CSS

#DiamondCenter {
    position:fixed;
    top:2%;
    left:48%;
    background: #24201a;
    height:40px;
    width:40px;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
    z-index:20 !important;
}
#triangle-topleft {
    width: 0;
    height: 0;
    border-top: 40px solid gray;
    border-right: 40px solid transparent;
}



via Chebli Mohamed

Roslyn - how to reliably format whitespace for a class

I need to format a class to ensure it's easily human readable. I have the syntax tree, the root CompilationUnitSyntax and the ClassDeclarationSyntax. I format the whitespace as follows.

root = root.ReplaceNode(classSyntax, classSyntax.NormalizeWhitespace(elasticTrivia: true));
syntaxTree = syntaxTree.WithRootAndOptions(root, syntaxTree.Options);

Before:

#region MyRegion
public class MyClass
{

    // Info about MyClass

}
#endregion

After:

#region MyRegion
public class MyClass
{
// Info about MyClass    
}#endregion

Why is the class's closing brace slammed into the #endregion?

If I run NormalizeWhitespace once more on the 'After' text, #endregion is moved back down onto its own line. Then a further call to NormalizeWhitespace moves it back up again. What is going on?



via Chebli Mohamed

Total time in python's line profiler is strange

This is my insertion.py:

import random

#@profile
def insertion_sort(l):
    for j in range(1, len(l)):
        k = l[j]
        i = j - 1
        while i >= 0 and l[i] > k:
            l[i + 1] = l[i]
            i -= 1
        l[i + 1] = k


if __name__ == '__main__':
    l = range(5000)
    random.shuffle(l)
    insertion_sort(l)

When I run time python insertion.py, I get:

real    0m0.823s
user    0m0.818s
sys     0m0.004s

But when I uncomment the profile decorator and run: kernprof -l -v insertion.py, I get:

Wrote profile results to insertion.py.lprof
Timer unit: 1e-06 s

Total time: 7.25971 s
File: insertion.py
Function: insertion_sort at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
 4                                           @profile
 5                                           def insertion_sort(l):
 6      5000         2110      0.4      0.0      for j in range(1, len(l)):
 7      4999         1929      0.4      0.0          k = l[j]
 8      4999         1719      0.3      0.0          i = j - 1
 9   6211255      2695158      0.4     37.1          while i >= 0 and l[i] > k:
10   6206256      2396675      0.4     33.0              l[i + 1] = l[i] 
11   6206256      2160158      0.3     29.8              i -= 1
12      4999         1959      0.4      0.0          l[i + 1] = k

My question is why total time of line profiler is much greater than the system time? I thought "Total time" of line profiler was describing how much time the function decorated with @profile was running. In my head, the output from time should be greater or at least close to line profiler. Am I interpreting the results wrong? Is line profiler adding its own time to "Total time"?



via Chebli Mohamed

Flattening an array recursively (withoout looping) javascript

I'm practicing recursion and am trying to flatten an array without looping (recursion only). As a first step I did the iterative approach and it worked, but am stuck on the pure recursion version:

function flattenRecursive(arr) {
    if (arr.length === 1) {
        return arr;
    }

    return Array.isArray(arr) ? arr = arr.concat(flattenRecursive(arr)) : flattenRecursive(arr.slice(1))
}

console.log(flattenRecursive([
    [2, 7],
    [8, 3],
    [1, 4], 7
])) //should return [2,7,8,3,1,4,7] but isn't - maximum call stack error


//working version (thanks @Dave!):

function flattenRecursive(arr) {
    if (arr.length === 1) {
        return arr;
    }

    return arr[0].concat(Array.isArray(arr) ? flattenRecursive(arr.slice(1)) : arr);
}

console.log(flattenRecursive([
    [2, 7],
    [8, 3],
    [1, 4], 7
]))

//returns [ 2, 7, 8, 3, 1, 4, 7 ]



via Chebli Mohamed

Insert data to MySQL database - iOS

I'm trying to insert data to table in MySQL database but it's not working. Code in .php file is correct but I think is something wrong with my app in objective-c. Problem is the data is not insert to database. Could you help me how can I insert data?

This is .php file:

<?php

    if (isset ($_POST["name"]) && isset ($_POST["age"])){
        $name = $_POST["name"];
        $age = $_POST["age"];
    }
    else {
        $name = "";
        $age = "";
    }

try {

    $con = new PDO("my domain without http://", "login", "password");
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "INSERT INTO NameOfDatabase.NameOfTable (NameOfColumn1, NameOfColumn2) VALUES ('$name', '$age')";
    // use exec() because no results are returned
    $con->exec($sql);
    echo "New record created successfully";
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}

$con = null;

?>

and this is code in app (objective-c):

NSString *strURL = [NSString stringWithFormat:@"my domain without http://?name=%@&age=%@", self.name.text, self.age.text];
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
    NSLog(@"%@", strResult);



via Chebli Mohamed

Are Grails getDirtyPropertyNames and getPersistentValue supported by MongDB?

I am using Grails version 2.4.2 and MongoDB 2.6 Created a Domain class Foo

class Foo {
  String slug
  String name
  String toString(){
    "${name}"
  }
  static constraints = {
    name blank: false
  }
  @Override
  def beforeUpdate(){
  if(isDirty("slug"){
    println "beforeUpdate() current value is  " +  this.slug
    println "original property names that were changed = " +     this.getDirtyPropertyNames()
    println "original value = " + this.getPersistentValue("slug")
  } 
 }
}

I created a FooController with scaffolding

class FooController{
  static scaffold = true
}

I run the app and create a new foo enter a name field and a slug field value then update the slug field

Are these methods supported by MongoDB? getPersistentValue getDirtyPropertyNames



via Chebli Mohamed

What really happens on inheritance in Java?

Suppose I have two classes Parent and Child, and Child inherits from Parent. I have three methods in Parent, out of which two are public and one is private.

Normally we say that all the non-private methods are inherited into the Child class, but I'm confused about exactly what happens. Does Java make a copy of the methods in the Child class, or does it use some kind of reference to maintain the relationship?

class Parent{
    // Private method
    private void method1(){
        System.out.println("In private method of Parent class");
    }
    void method2(){
    // calling private method
        method1();
    }
    void method3(){
    // calling private method
        method1();
    }
}

class Child extends Parent{

}

class MainClass{
   public static void main(String[] args){
       Child child = new Child();
       // calling non-private method which internally calls the private method
       child.method2();
   }
}



via Chebli Mohamed

How do I configure django-money to output GBP in British format?

I'm using django-money to handle money amounts in GBP (Pounds Sterling), but they are being output as GB£20.00, rather than £20.00. This is despite settings.LANGUAGE_CODE being "en-GB" and settings.USE_L10N being True.

What am I doing wrong?



via Chebli Mohamed

Using Linked List into OSP 2 TaskCB

I am learning OSP 2 and how to use to implement method in the TaskCB, as well as an implementation of a Linked List. So I got my TaskCB class work fine, but when I create a Linked List it gives me errors such as

Possible cause: Failed to add/remove a thread to/from task

Image of output

Anybody can help me to point out what I am missing or any suggest would be great! Thank you!

Here is my TaskCB and Linked Like code so far.

import osp.FileSys.*;
import osp.Hardware.*;
import osp.IFLModules.*;
import osp.Memory.*;
import osp.Ports.*;
import osp.Threads.*;

/**
 * The student module dealing with the creation and killing of tasks. A task
 * acts primarily as a container for threads and as a holder of resources.
 * Execution is associated entirely with threads. The primary methods that the
 * student will implement are do_create(TaskCB) and do_kill(TaskCB). The student
 * can choose how to keep track of which threads are part of a task. In this
 * implementation, an array is used.
 * 
 * @OSPProject Tasks
 */
public class TaskCB extends IflTaskCB {
    /**
     * The task constructor. Must have
     * 
     * super();
     * 
     * as its first statement.
     * 
     * @OSPProject Tasks
     */

    private LinkedList<ThreadCB> threadList;
    private LinkedList<PortCB> portList;
    private LinkedList<OpenFile> openFilesTable;

    private static int virtureMemorySize = (int) Math.pow(2,
        MMU.getVirtualAddressBits());

    public TaskCB() {

        super();
    }

    /**
     * This method is called once at the beginning of the simulation. Can be
     * used to initialize static variables.
     * 
     * @OSPProject Tasks
     */
    public static void init() {
        // your code goes here

    }

    /**
     * Sets the properties of a new task, passed as an argument.
     * 
     * Creates a new thread list, sets TaskLive status and creation time,
     * creates and opens the task's swap file of the size equal to the size (in
     * bytes) of the addressable virtual memory.
     * 
     * @return task or null
     * 
     * @OSPProject Tasks
     */
    static public TaskCB do_create() {

        TaskCB theTask = new TaskCB();
        PageTable pagTable = new PageTable(theTask);
        theTask.setPageTable(pagTable);

        theTask.threadList = new LinkedList<ThreadCB>();
        theTask.portList = new LinkedList<PortCB>();
        theTask.openFilesTable = new LinkedList<OpenFile>();

        theTask.setCreationTime(HClock.get());
        theTask.setStatus(TaskLive);
        theTask.setPriority(0);

        FileSys.create(SwapDeviceMountPoint + theTask.getID(),
            virtureMemorySize);
        OpenFile swapFile = OpenFile.open(SwapDeviceMountPoint + theTask.getID(),
            theTask);

        if ( swapFile == null ) {
            ThreadCB.dispatch();
//            theTask.do_kill();
            return null;
        }

        theTask.setSwapFile(swapFile);
        ThreadCB.create(theTask);

        return theTask;

    }

    /**
     * Kills the specified task and all of it threads.
     * 
     * Sets the status TaskTerm, frees all memory frames (reserved frames may
     * not be unreserved, but must be marked free), deletes the task's swap
     * file.
     * 
     * @OSPProject Tasks
     */
    public void do_kill() {

        for ( int i = threadList.size() - 1; i >= 0; i-- ) {
            ((ThreadCB) this.threadList.get(i)).kill();
        }

        for ( int i = this.portList.size() - 1; i >= 0; i-- ) {
            ((PortCB) this.portList.get(i)).destroy();
        }

        this.setStatus(TaskTerm);
        this.getPageTable().deallocateMemory();

        for ( int i = openFilesTable.size() - 1; i >= 0; i-- ) {
            OpenFile swapFile = (OpenFile) openFilesTable.get(i);
            if ( swapFile != this.getSwapFile() ) {
                swapFile.close();
            }
        }

        this.getSwapFile().close();
        FileSys.delete(SwapDeviceMountPoint + this.getID());

    }

    /**
     * Returns a count of the number of threads in this task.
     * 
     * @OSPProject Tasks
     */
    public int do_getThreadCount() {
        return threadList.size();
    }

    /**
     * Adds the specified thread to this task.
     * 
     * @return FAILURE, if the number of threads exceeds MaxThreadsPerTask;
     *         SUCCESS otherwise.
     * 
     * @OSPProject Tasks
     */
    public int do_addThread(ThreadCB thread) {
        if ( threadList.size() >= ThreadCB.MaxThreadsPerTask ) {
            return TaskCB.FAILURE;
        }
        threadList.addFirst(thread);
        return TaskCB.SUCCESS;
    }

    /**
     * Removes the specified thread from this task.
     * 
     * @OSPProject Tasks
     */
    public int do_removeThread(ThreadCB thread) {
        if ( this.threadList.contains(thread) ) {
            this.threadList.remove(thread);
            return TaskCB.SUCCESS;
        }
        else
            return TaskCB.FAILURE;
    }

    /**
     * Return number of ports currently owned by this task.
     * 
     * @OSPProject Tasks
     */
    public int do_getPortCount() {
        return portList.size();
    }

    /**
     * Add the port to the list of ports owned by this task.
     * 
     * @OSPProject Tasks
     */
    public int do_addPort(PortCB newPort) {
        if ( portList.size() >= PortCB.MaxPortsPerTask ) {
            return TaskCB.FAILURE;
        }
        portList.addFirst(newPort);
        return TaskCB.SUCCESS;
    }

    /**
     * Remove the port from the list of ports owned by this task.
     * 
     * @OSPProject Tasks
     */
    public int do_removePort(PortCB oldPort) {
        if ( this.portList.contains(oldPort) ) {
            portList.remove(oldPort);
            return TaskCB.SUCCESS;
        }

        return TaskCB.FAILURE;
    }

    /**
     * Insert file into the open files table of the task.
     * 
     * @OSPProject Tasks
     */
    public void do_addFile(OpenFile file) {
        this.openFilesTable.addLast(file);

    }

    /**
     * Remove file from the task's open files table.
     * 
     * @OSPProject Tasks
     */
    public int do_removeFile(OpenFile file) {
        if ( file.getTask() != this )
            return TaskCB.FAILURE;
        openFilesTable.remove(file);
        return TaskCB.SUCCESS;
    }




import java.util.*;

public class LinkedList<V> implements Iterable<V>
{
   private Node<V> head;
   private int count = 0;

 /**
   *  Constructs an empty list
   */
   public LinkedList()
   {
      head = null;
   }
 /**
   *  Returns true if the list is empty
   *
   */
   public boolean isEmpty()
   {
      return head == null;
   }

   public int size() {
       return count;
   }
 /**
   *  Inserts a new node at the beginning of this list.
   *
   */
   public void addFirst(V item)
   {
      head = new Node<V>(item, head);
   }
 /**
   *  Returns the first element in the list.
   *
   */
   public V getFirst()
   {
      if(head == null) throw new NoSuchElementException();

      return head.data;
   }
 /**
   *  Removes the first element in the list.
   *
   */
   public V removeFirst()
   {
      V tmp = getFirst();
      head = head.next;
      return tmp;
   }
 /**
   *  Inserts a new node to the end of this list.
   *
   */
   public void addLast(V item)
   {
      if( head == null)
         addFirst(item);
      else
      {
         Node<V> tmp = head;
         while(tmp.next != null) tmp = tmp.next;

         tmp.next = new Node<V>(item, null);
      }
   }
 /**
   *  Returns the last element in the list.
   *
   */
   public V getLast()
   {
      if(head == null) throw new NoSuchElementException();

      Node<V> tmp = head;
      while(tmp.next != null) tmp = tmp.next;

      return tmp.data;
   }
 /**
   *  Removes all nodes from the list.
   *
   */
   public void clear()
   {
      head = null;
   }
 /**
   *  Returns true if this list contains the specified element.
   *
   */
   public boolean contains(V x)
   {
      for(V tmp : this)
         if(tmp.equals(x)) return true;

      return false;
   }
 /**
   *  Returns the data at the specified position in the list.
   *
   */
   public V get(int pos)
   {
      if (head == null) throw new IndexOutOfBoundsException();

      Node<V> tmp = head;
      for (int k = 0; k < pos; k++) tmp = tmp.next;

      if( tmp == null) throw new IndexOutOfBoundsException();

      return tmp.data;
   }
 /**
   *  Returns a string representation
   *
   */
   public String toString()
   {
      StringBuffer result = new StringBuffer();
      for(Object x : this)
        result.append(x + " ");

      return result.toString();
   }
 /**
   *  Inserts a new node after a node containing the key.
   *
   */
   public void insertAfter(V key, V toInsert)
   {
      Node<V> tmp = head;

      while(tmp != null && !tmp.data.equals(key)) tmp = tmp.next;

      if(tmp != null)
         tmp.next = new Node<V>(toInsert, tmp.next);
   }
 /**
   *  Inserts a new node before a node containing the key.
   *
   */
   public void insertBefore(V key, V toInsert)
   {
      if(head == null) return;

      if(head.data.equals(key))
      {
         addFirst(toInsert);
         return;
      }

      Node<V> prev = null;
      Node<V> cur = head;

      while(cur != null && !cur.data.equals(key))
      {
         prev = cur;
         cur = cur.next;
      }
      //insert between cur and prev
      if(cur != null)
         prev.next = new Node<V>(toInsert, cur);
   }
 /**
   *  Removes the first occurrence of the specified element in this list.
   *
   */
   public void remove(V key)
   {
      if(head == null)
         throw new RuntimeException("cannot delete");

      if( head.data.equals(key) )
      {
         head = head.next;
         return;
      }

      Node<V> cur  = head;
      Node<V> prev = null;

      while(cur != null && !cur.data.equals(key) )
      {
         prev = cur;
         cur = cur.next;
      }

      if(cur == null)
         throw new RuntimeException("cannot delete");

      //delete cur node
      prev.next = cur.next;
   }

 /*******************************************************
 *
 *  The Node class
 *
 ********************************************************/
   private static class Node<AnyType>
   {
      private AnyType data;
      private Node<AnyType> next;

      public Node(AnyType data, Node<AnyType> next)
      {
         this.data = data;
         this.next = next;
      }
   }

 /*******************************************************
 *
 *  The Iterator class
 *
 ********************************************************/

   public Iterator<V> iterator()
   {
      return new LinkedListIterator();
   }

   private class LinkedListIterator  implements Iterator<V>
   {
      private Node<V> nextNode;

      public LinkedListIterator()
      {
         nextNode = head;
      }

      public boolean hasNext()
      {
         return nextNode != null;
      }

      public V next()
      {
         if (!hasNext()) throw new NoSuchElementException();
         V res = nextNode.data;
         nextNode = nextNode.next;
         return res;
      }

      public void remove() { throw new UnsupportedOperationException(); }
   }
}



via Chebli Mohamed

Visual studios c#, trying to add objects every click of a button

I'm trying to add a circle every click on button1. For some reason after adding the first circle, I can't add a second. Please help, it's for a school project... Here's the code: http://ift.tt/1FBNY2q



via Chebli Mohamed

Transfer artifact via SFTP using Maven

I'm attempting to add a build task into a Maven pom file so that I can transfer a jar file as well as some xml files to an SFTP server (it's a VM with Tomcat installed) but I have been unable to so far.

I've had a look at a few links, but they either don't quite match the requirements, have missing steps, or don't work. I'm basically a beginner with Maven so I'm not sure if I'm doing it correctly.

The requirement is that I want to invoke a Maven build, with command line arguments for the hostname, username, and password (which I have working) which then will upload a jar file and the xml files to a VM with Tomcat running in it via SFTP (FTP doesn't work, and I don't think SCP will work as I don't have a passfile). I also don't want to mess with the main Maven settings.xml file to add the connection details in, which some of the links I found seem to be reliant upon.

I have the following profile so far, using FTP, but it doesn't work due to not using SFTP.

<profiles>
    <profile>
        <!-- maven antrun:run -Pdeploy -->
        <id>deploy</id>
        <build>
            <plugins>
                <plugin>
                    <inherited>false</inherited>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-antrun-plugin</artifactId>
                    <version>1.6</version>
                    <configuration>
                        <target>
                            <!-- <loadproperties srcFile="deploy.properties" /> -->

                            <ftp action="send" server="${server-url}"
                                remotedir="/usr/share/myappserver/webapps/myapp/WEB-INF/lib"
                                userid="${user-id}" password="${user-password}" depends="no"
                                verbose="yes" binary="yes">
                                <fileset dir="target">
                                    <include name="artifact.jar" />
                                </fileset>
                            </ftp>

                            <ftp action="send" server="${server-url}"
                                remotedir="/var/lib/myappserver/myapp/spring"
                                userid="${user-id}" password="${user-password}" depends="no"
                                verbose="yes" binary="yes">
                                <fileset dir="src/main/resource/spring">
                                    <include name="*.xml" />
                                </fileset>
                            </ftp>

                            <!-- calls deploy script -->
                            <!-- <sshexec host="host" trust="yes" username="usr" password="pw" 
                                command="sh /my/script.sh" /> -->

                            <!-- SSH -->
                            <taskdef name="sshexec" classname="org.apache.tools.ant.taskdefs.optional.ssh.SSHExec" 
                                classpathref="maven.plugin.classpath" />
                            <taskdef name="ftp"
                                classname="org.apache.tools.ant.taskdefs.optional.net.FTP"
                                classpathref="maven.plugin.classpath" />
                        </target>

                    </configuration>
                    <dependencies>
                        <dependency>
                            <groupId>commons-net</groupId>
                            <artifactId>commons-net</artifactId>
                            <version>1.4.1</version>
                        </dependency>
                        <dependency>
                            <groupId>ant</groupId>
                            <artifactId>ant-commons-net</artifactId>
                            <version>1.6.5</version>
                        </dependency>
                        <dependency>
                            <groupId>ant</groupId>
                            <artifactId>ant-jsch</artifactId>
                            <version>1.6.5</version>
                        </dependency>
                        <dependency>
                            <groupId>jsch</groupId>
                            <artifactId>jsch</artifactId>
                            <version>0.1.29</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

I tried swapping ftp for sftp, and using org.apache.tools.ant.taskdefs.optional.ssh.SFTP instead, but it didn't seem to work.

So to summarize, the SFTP config needs to be self contained within the pom file as much as possible, with stuff like the host url, username and password being passed in when invoked.



via Chebli Mohamed

Call function inside bxslider callback

I am trying to call a custom function inside a bxslider callback but the function doesn't get recorgnized (aka: Uncaught Reference Error: nextSlideCustom() is not a function)

my current code looks like

    var slider=$('#slider1').bxSlider({
         pager: 'true',
         onSlideNext: nextSlideHandle()
    });

and in a different js file I am defining this function:

function nextSlideHandle(){
    console.log("huhu");
}

so what's the problem with my code, or is it mory likely a wrong configuration of the slider or something?

thanks in advance!



via Chebli Mohamed

How to disable browser auto filling username and password

How to disable browser auto filling form username and password fields. I have already tried autocomplete="off". It's not working for me. Please find the form below. And help me to solve this.



via Chebli Mohamed

MySQL - Check if two values are equal or both NULL?

If I want to compare two values, I can write:

SELECT * FROM table1
JOIN table2 ON table1.col = table2.col;

I've noticed that this does not work if both table1.col and table2.col are NULL. So my corrected query looks like this:

SELECT * FROM table1
JOIN table2 ON 
  (table1.col = table2.col)
  OR
  (table1.col IS NULL AND table2.col IS NULL);

Is this the correct way to compare two values? Is there a way to say two values are equal if they are both NULL?



via Chebli Mohamed

Opening a file in C

I looked at many examples before I wrote this, and I know many languages and clearly understand the syntax and what is going on in the code I listed below, however, when I compile my program for example:

gcc -o /sbin/"name" readfile.c

I get the following error:

enter image description here

This makes no since to me since my code clearly includes #include <stdio.h> which defines the FILE as referenced here ---- stdio.h.

//PROGRAM (readfile.c)

#include <stdio.h>

int main(){
    FILE *fp;
    fp = fopen("dummy.txt","w");
    fprint(fp, "testing...\n");
    fclose(fp);
}

//FILE (dummy.txt) *is in the same directory

Hello World



via Chebli Mohamed

Setting up a Ground node using SpriteKit?

I've been designing a game where I want the game to stop as soon as the ball makes contact with the ground. My function below is intended to set up the ground.

class GameScene: SKScene, SKPhysicsContactDelegate {

 var ground = SKNode() 

 let groundCategory: UInt32 = 0x1 << 0
 let ballCategory: UInt32 = 0x1 << 1

 func setUpGround() -> Void {
        self.ground.position = CGPointMake(0, self.frame.size.height)
        self.ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, self.frame.size.height)) //Experiment with this
        self.ground.physicsBody?.dynamic = false

        self.ground.physicsBody?.categoryBitMask = groundCategory    //Assigns the bit mask category for ground
        self.ball.physicsBody?.contactTestBitMask = ballCategory  //Assigns the contacts that we care about for the ground

        self.addChild(self.ground)
    } 
}

The problem I am noticing is that when I run the iOS Simulator, the Ground node is not being detected. What am I doing wrong in this case?



via Chebli Mohamed

Return the row of first non-blank cell in Excel

Let's say I have the array A1:A5 in excel:

    A  
1    
2  
3  'test'  
4  
5  'test2'

How can I return "3"? I'm looking for something in Excel formulas. The blanks are genuine blanks.



via Chebli Mohamed

SQL connection error from PHP after many operations

I'm currently looping to create a MBTiles map, and add information to my database each time. Here's how I configured my connection and execute actions during the loop:

if ($pdo_mbtiles == null) {
    echo "Opening new database connection".PHP_EOL;
    $pdo_mbtiles = new PDO('sqlite:'.$filename,
            '',
            '',
            array(
                PDO::ATTR_PERSISTENT => true
                )
            );
}
$pdo_mbtiles->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo_mbtiles->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q = $pdo_mbtiles->prepare("INSERT INTO tiles (zoom_level, tile_column, tile_row,tile_data) VALUES (:zoom_level, :tile_column, :tile_rowTMS, :tile_data)");
$q->bindParam(':zoom_level', $zoom_level);
$q->bindParam(':tile_column', $tile_column);
$q->bindParam(':tile_rowTMS', $tile_rowTMS);
$q->bindParam(':tile_data', $tile_data, PDO::PARAM_LOB);
$q->execute();

After 1018 times looping (this number doesn't change no matter how many times I try), I get this error message:

SQLSTATE[HY000]: General error: 14 unable to open database file

I checked the solution written here: How to prevent SQLITE SQLSTATE[HY000] [14]? but the echoed message only appears at the first time of the loop, so I assume the PDO connection isn't closed.

I didn't find other documentation relevant to this error code.

What could possibly go wrong here?



via Chebli Mohamed

How to compute for the mean and sd

I need help on 4b please

  1. ‘Warpbreaks’ is a built-in dataset in R. Load it using the function data(warpbreaks). It consists of the number of warp breaks per loom, where a loom corresponds to a fixed length of yarn. It has three variables namely, breaks, wool, and tension.

    b. For the ‘AM.warpbreaks’ dataset, compute for the mean and the standard deviation of the breaks variable for those observations with breaks value not exceeding 30.

    data(warpbreaks)
    warpbreaks <- data.frame(warpbreaks)
    AM.warpbreaks <- subset(warpbreaks, wool=="A" & tension=="M")
    
    mean(AM.warpbreaks<=30)
    sd(AM.warpbreaks<=30)
    
    

This is what I understood this problem and typed the code as in the last two lines. However, I wasn't able to run the last two lines while the first 3 lines ran successfully. Can anybody tell me what is the error here? Thanks! :)



via Chebli Mohamed

Select all span elements except those which class contains the word icon

I'm implementing the following CSS Selector

Select all span elements except those which class contains the word icon

So the following seems to be working:

.music-site-refresh span:not([class*="icon"]) {
  font-family:Montserrat, sans-serif;
}

But I thought it should be like this:

.music-site-refresh span:not(span[class*="icon"]) {
  font-family:Montserrat, sans-serif;
}

But the second one doesn't work in my testbed.

Could anyone explain me which one is correct and why?



via Chebli Mohamed

C programming - While loop and scanf

Could anyone advise why my scanf function only works once and it ends in a continuous loop.

#include <stdio.h>
#include <conio.h>

int main(void)
{
    int accno;
    float bbal, charge, rebate, limit, balance;

    printf("Enter account number (-1 to end):");
    scanf("%d", &accno);

    while (accno != -1) // User input phase
    {
        printf("Enter beginning balance:"); // User input phase
        scanf(" %.2f ", &bbal); // leave space after scanf(" 

        printf("Enter total charges:");
        scanf(" %.2f ", &charge);

        printf("Enter total rebates:");
        scanf(" %.2f ", &rebate);

        printf("Enter credit limit:");
        scanf(" %.2f ", &limit);

        balance = bbal - charge + rebate;

        // credit limit exceeded phase
        if (balance > limit)
        {
            printf("Account: %u", accno);
            printf("Credit limit: %.2f", limit);

            balance = bbal - charge + rebate;

            printf("Balance: %.2f", balance);
            printf("Credit limit exceeded!");
        }
        printf("Enter account number (-1 to end):");
        scanf("%d", &accno);
    }

    getch();
}



via Chebli Mohamed

dynamically create div and into a static div

On click of button i am trying to create one div and try to append static div into that and this is giving error.

Uncaught TypeError: elm.appendChild is not a function.

    <script>
        function s()
        {
            var elm = '<div' +
                'style="background-color:orange;height:125px;width:75px;"'+
                '</div>';           
            var x=document.getElementById("ss")         
            elm.appendChild(x);         
        }
    </script>       

    <div id="ss">
        <ul>
            <li style="background-color:grey;">
                <h2 class="wheater_CityName">Mumbai</h2><br><br>
                    <div style= 
                        "margin-left: 30%;
                        margin-top: -21%;"
                    >
                    </div>
                    <hr style= "margin-top: -83px; ">                   
            </li>
            <li>sad</li>
            <li>as</li>             
        </ul>
    </div>    
    <input type="button" value="ss" onclick="s()"/>



via Chebli Mohamed

ActionScript: using variables w/E4X descendant accessor (..)

I'm using a descendant accessor like so:

var myxml:XMLList = new XMLList;

...

myxml..node

and would like to replace it w/

const sNode:String = 'node';
myxml..[{sNode}]

This sort of thing has worked before.

const sAttrib:String = 'attrib';
myxml.@[{sAttrib}]

works, but trying the same sort of thing w/a descendant accessor causes a compiler error.

Yes, I could do

myxml.descendants(sNode)

but I'd rather do it w/operators, if I can.

The XML might be something like:

<map>
    <node>
       <node />
    </node>
</map>



via Chebli Mohamed

Unable to implement user subscription based Push Notifications when implemented with Adapter based authentication

I have defined an Adapter based as authentication.

Doing a custom security test which works successfully.

But when I wanted to implement User Subscription based Push Notifications and added a mobile security test in authentication Config.XML I am facing lot of issues.

As I'm trying to deploy the app and test in android device. I have also included the mobile security test in android tag of application-descriptor.xml. But facing lot of issues to deploy the adapter itself after this.

Can anyone guide me on this please?

Please refer to the below code snippets which I am using

authenticationConfig.xml

    <mobileSecurityTest name="MST1">
        <testUser realm="AdapterAuthRealm"/>
        <testDeviceId provisioningType="none"/>
    </mobileSecurityTest>

    <webSecurityTest name="WST1">
        <testUser realm="AdapterAuthRealm"/>
    </webSecurityTest>

    <customSecurityTest name="Master-Password">
        <test realm="AdapterAuthRealm" isInternalUserID="true"/>
    </customSecurityTest>

Authentication was running fine till I had only the customSecurityTest being defined.

After adding web and mobile security test, there is no response when I give the credentials and click login neither from GUI side nor from the console logs side.

I have also added security test in android tag in application-descriptor.xml as below

<android securityTest="MST1" version="1.0"> 
    <worklightSettings include="false"/>        
    <pushSender key="xxxxxxxxxxx" senderId="xxxxxxxxxxxxxxx"/>

    <security>
        <encryptWebResources enabled="false"/>
        <testWebResourcesChecksum enabled="false" ignoreFileExtensions="png, jpg, jpeg, gif, mp4, mp3"/>
        <publicSigningKey/>
        <packageName/>
    </security>
</android>



via Chebli Mohamed

Angularjs recursive directive

I am trying to write a recursive directive. I have seen this thread: Recursion in Angular directives

It works when you put the recursive directive under ul-li but goes into infinite loop with a table-tr

<table> 
  <tr>
    <td>{{ family.name  }}</td>
  </tr>
  <tr ng-repeat="child in family.children">
    <tree family="child"></tree>
  </tr>
</table>

Here is a plunker : http://ift.tt/1LnI4Uo

EDIT: I am not trying to build a tree directive.In my recursive directive I have to use table and tr tags.



via Chebli Mohamed

Linux Kernel Generic Netlink - Is it concurrent?

Say that i have registered a generic netlink interface using genl_register_family_with_ops with multiple callbacks.

I don't see any warnings about it and I assume the callbacks are serially called but there is no information about how the callbacks are called neither.

Is it possible that multiple callbacks are called concurrently on the same generic netlink interface I have registered? Do I need any synchronization between the callbacks?

To make the question simpler:

Can a single netlink callback be preempted or concurrently run in two cores?



via Chebli Mohamed

Android - API key for GoogleMaps API V2 for release

I have trouble with GoogleAPI in my app. I use Google Maps and Places - both needs API key. Everything works fine, until I upload my signed app to Google Play. From what I know and from what I read so far, the API key has to have the same fingerprint as my signed app to work properly from app downloaded from GP. So I created a new API key, add two fingerprints with package name to this key. First with fingerprint from debug.keystore and second from fingerprint from my keystore which I'm using for singning app when I do release build (I'm using android studio ->generate signed apk). This way I assumed that this will work for debug and release, but it work only for debug. To be sure that fingerprint of my app is the same as I have under Google API key I have implemented method which extract fingreprint of my app on runtime. They are match - when I do debug release I see fingerpring "A", when I do it for release I see "B" and I have both of then are the same as fingerprints which I have under API key (section Restrict usage to your Android apps). Note that package name is also correct.

Summary I don't know what I'm missing, or why this is not working when fingerprints are matched - result after release build is that Places api indicates KEY_INVALID and maps is gray, without titles.



via Chebli Mohamed

gender related translations with transchoice and lingohub

I have been trying to find a solution for this but have not found the answer that works for me. Basically what I want are gender specific translations in Symfony2 using twig and the service lingohub.

Our translations files for English look like this:

<trans-unit id="1234" resname="some_key">
  <source xml:lang="en">My text goes here </source>
  <target xml:lang="en">My text goes here </target>
</trans-unit>

for another language it would look like this:

<trans-unit id="2345" resname="some_key">
  <source xml:lang="en">My text goes here </source>
  <target xml:lang="es">My text in Spanish goes here</target>
</trans-unit>

what I now want is a gender specific translation. I would love to use transchoice and use the translations from my files

On the Symfony doc I can only find the example with static text.

Question is what do I have to put in twig and what into the translations files?

I tried to put the choices in twig but then it does not translate at all. I also tried to put one key and the choices in the translation file but this also does not work. It selects always the second option and also prints the text as it is (including {f} for female)

What I want is something like:

{% transchoice gender with {'%lastname%': user.lastname}  %}
  {f} key_for_female |{m} key_for_male | {u} key_for_unknown
{% endtranschoice %}

which will be replaced by translations like

<trans-unit id="1234" resname="key_for_female">
  <source xml:lang="en">Hello Ms %lastname% </source>
  <target xml:lang="en">Hello Ms %lastname%  </target>
</trans-unit>

so that the output is in the end "Hello Ms Doe". What is the correct syntax? ;)



via Chebli Mohamed

project folder, that contains sub-folder with .git folder seems issue

all the files in the folder are adding except the following one, i dont know what the issue, i guess there is a .git folder is that something related.

enter image description here

enter image description here

There are files and folders in the dompdf-module, need to be added to the repo.

enter image description here

These was the response after i add the files from the folder dino/dompdf-module

enter image description here



via Chebli Mohamed

ExtJs put a tooltip to the horizontal scroll controls Tab Panel

I have a tab panel with some items inside them, when I add many elements the panel puts a horizontal movement controlers, how can i do to put a tooltip in this controls?

Tab Panel

This is the definition of my tab Panel:

        var tabPanel = Ext.create('Ext.tab.Panel',{
        id: 'tabTabla',
        items: [{
            title: 'list1',
            tooltip: 'list1',
            items:[tree]
        }, {
            title: 'list2',
            tooltip: 'list2',
            autoWidth : true,
            autoHeight : true,
            plain : true,
            defaults : {
                autoScroll : true,
                bodyPadding : 0
            },
            items: [{
                xtype : 'label',
                text : 'list description.',
            },
            gridV]
        },{
            title: 'list3',
            tooltip: 'list3',
            autoWidth : true,
            autoHeight : true,
            plain : true,
            defaults : {
                autoScroll : true,
                bodyPadding : 0
            },
            items: [
                    gridC
                    ]
        }]
    });

In this tab Panel I add more panels:

    Ext.apply(this, {
        title: 'TITLE',
        constrain: true,
        header : {
            titlePosition : 2,
            titleAlign : 'center'
        },
        closable : false,
        x : 20,
        y : 270,
        layout : 'fit',
        animCollapse : true,
        collapsible : true,
        collapseDirection : Ext.Component.DIRECTION_LEFT,
        items: [tabPanel]
    });



via Chebli Mohamed

How to get raw User Timings data using Google Analytics Core Reporting API

I'm using User Timings to measure how long something takes, by doing e.g. ga('send', 'timing', 'jQuery', 'Load Library', 20, 'Google CDN');

In Google Analytics web interface at Behavior > Site Speed > User Timings I can see both an average and an histogram (by clicking the tab Distribution).

Using the Analytics Core Reporting API I'm able to retrieve the average user timing by querying on the metric ga:avgUserTimingValue. I was wondering if it's possible to retrieve the histogram or the raw data itself. I'm specifically looking to create a box plot using the user timings data.



via Chebli Mohamed

Decimal to Binary Java

I want convert just 256 numbers to binary without using if, while, etc., just by using the ? operator and four binary operators.

My programs works well for numbers 1 to 64, but after 64 it does not work! How can I do this? I must store all results in the variable b.

public class NaarBinair {
    public static int g=1,b=0;

    public static void main(String[] args){
        int r1 = g % 2 ;        
        int q1 = g / 2 ;
        int r2 = q1 % 2 ;
        int q2 = q1 / 2 ;
        int r3 = q2 % 2 ;       
        int q3 = q2 / 2 ;
        int r4 = q3 % 2 ;       
        int q4 = q3 / 2 ;
        int r5 = q4 % 2 ;       
        int q5 = q4 / 2 ;
        int r6 = q5 % 2 ;       
        int q6 = r5 / 2 ;
        int r7 = q6 % 2 ;       
        int q7 = r6 / 2 ;

        String s1 =  String.valueOf(r1) ;           
        String s2 =  String.valueOf(r2) ;
        String s3 =  String.valueOf(r3) ;
        String s4 =  String.valueOf(r4) ;       
        String s5 =  String.valueOf(r5) ;
        String s6 =  String.valueOf(r6) ;
        String s7 =  String.valueOf(r7) ;

        b = Integer.parseInt( s7 + s6 + s5 + s4 + s3 + s2 + s1 ) ;
        System.out.println(b);
    }
}



via Chebli Mohamed

Complex Join with AutoMapper and EF 6

I have a complex database Model with joins. I don't want to use store procedure so I want to use AutoMapper to flatten it so I can query it. I can't seem to figure out how to flatten it using AutoMapper and structuremap. Below are my classes generated from the Entity Framework using code first from existing database. I am using an Interface and Implementing a class to query the objects. I need to get users who has permissions to a contract.

[Table("Contract")] public class Contract { public Contract() { CDRLs = new HashSet(); ContractDocuments = new HashSet(); WDTOes = new HashSet(); }

[Table("PMO")]
public class PMO
{         
    public PMO()
    {
        Contracts = new HashSet<Contract>();
        Products = new HashSet<Product>();
        USERS = new HashSet<USER>();
    }

     [Table("USERS")]
public class USER
{

    public USER()
    {
        Organizations = new HashSet<Organization>();
        Organizations1 = new HashSet<Organization>();
        Products = new HashSet<Product>();
        Products1 = new HashSet<Product>();
        Programs = new HashSet<Program>();
        Programs1 = new HashSet<Program>();
        PMOes = new HashSet<PMO>();
        ROLES = new HashSet<ROLE>();
    }


    [Table("ROLES")]
public class ROLE
{

    public ROLE()
    {
        PERMISSIONS = new HashSet<PERMISSION>();
        USERS = new HashSet<USER>();
        LastModified = DateTime.Now;
        InsertDate = DateTime.Now;
    }

[Table("PERMISSIONS")] public class PERMISSION {

    public PERMISSION()
    {
        ROLES = new HashSet<ROLE>();
    }



via Chebli Mohamed

mardi 4 août 2015

Spring 4 response to form submission dosent go thru view resolver. Gives back return string in response

I inherited a spring 4 web project at work which is configured with Tiles view framework, Spring framework for dispatcher servlet and IOC.

I am trying to build a reset password functionality which has three screens with three forms.

1)reset form. Takes the user's email and controller method sends an email with a temp password.

<form:form class="form-horizontal" action="/NCHP/reset.htm" method="post" id="resetForm">
                                    <fieldset>
                                        <legend>Enter your registered email address</legend>
                                        <div class="form-group">
                                            <div class="col-sm-12">
                                                <input id="resetEmail" name="email" class="form-control" placeholder="Email" required="required" tabindex="1" type="email">
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                                    <button type="reset" class="btn btn-default" data-dismiss="modal">Back</button>
                                                    <button type="submit" class="btn btn-primary" >Submit</button>
                                                </span>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form:form>

2) Form to enter temp pwd:

<form:form class="form-horizontal" name="verify" method="POST" id='verifyform'>

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-user form-control-feedback"></i>
                                            <input type="text" id="inputEmailVerify" name="userNameVerify" placeholder="User Name" class="form-control" autofocus="autofocus">
                                        </div>

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" name="passwordVerify" id="inputPasswordVerify" placeholder="Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group" id="verify-btn">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                                <input type="submit" formaction="/NCHP/resetVerify.htm" value="Verify" class="btn btn-primary btn-block">
                                                </span>
                                            </div>
                                        </div>
                                    </form:form>

3) form to enter new password:

<form:form class="form-horizontal" name="resetPass" method="POST" id='resetPassForm' >

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" id="newpass" name="newpass" placeholder="new Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" name="newpass2" id="newpass2" placeholder="re enter Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group" id="new-login-btn">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                        <input type="submit" formaction="/NCHP/changePass.htm" value="Save Password" onsubmit="modaljay();" class="btn btn-info btn-block">
                                        <div class="modaljay"><!-- Place at bottom of page --></div>
                                        </span>
                                        </div>
                                        </div>
                                    </form:form>

The first two forms i do an ajax submit and get back just the data without a view like below with jquery $.ajax()

$('#resetForm').submit(function(event) {
                                        $("#verifyModal").hide();
                                        $("passModal").hide();
                                        var resetmail = $('#resetEmail').val();
                                        console.log(resetmail);
                                        var json = {
                                            "email" : resetmail
                                        };

                                        $.ajax({
                                                    url : "http://localhost:8080/NCHP/reset.htm",
                                                    data : json,
                                                    dataType : 'text json',
                                                    type : "POST",

                                                    success : function(e) {
                                                        $('#resetModal').modal('hide');
                                                        $("#verifyModal").modal('show');
                                                        console.log(e);
                                                    },
                                                    error : function(e) {
                                                        console.log(e);
                                                        if (e.responseText == "email sent") {
                                                            $('#resetModal').modal('hide');
                                                            $("#verifyModal").modal('show');
                                                        } else if (e.responseText == "email not sent. UNAUTHORIZED") {
                                                            $("#emailResponce").html("there was an error. We could not process your request at this time. Please contact support@nexiscard.com");
                                                        }
                                                    }
                                                });

                                        event.preventDefault();
                                    });

The third form is a regular form submission and no ajax submission. because i want the user to be forwarded to their home page after they login with temp and set new password.

Below are the controller mappings for first two forms.

@Controller
public class UserLoginreset
{
@Autowired
public UserDao userDao;
@Autowired
public BCryptPasswordEncoder encoder;
@Autowired
public SecureServiceClient serviceClient;

@RequestMapping(value = "/reset", method = RequestMethod.POST)

public @ResponseBody String  reset( @RequestBody(required=true) String email, 
                                            HttpServletRequest request) 
{
    String mail="";
    try{
            mail = java.net.URLDecoder.decode(email, "UTF-8").replace("email=", "");
        }
    catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    User user =userDao.findUserByemail(mail);
    request.getSession().setAttribute("user",user);
    String resetPwd= encoder.encode("xxxx");

    if(user!=null && email!=null){
        userDao.resetPass(user.getUser_name(), resetPwd);
        return (String) serviceClient.returnRestTemplate("email", mail);//"home";
    } else {
        return "login";//"index";
    }
}

@RequestMapping(value = "/resetVerify", method = RequestMethod.POST)
public @ResponseBody String  resetVerify( @RequestParam(value="user",required=true) String user,@RequestParam(value="pass",required=true) String pass, 
                                            HttpServletRequest request) 
{
    User user1 =userDao.findUserByName(user);
    if(user1!=null && pass.matches("xxxx")){
        return "success";//"home";
    } else {
        return "unauthorised";//"index";
    }

}

}

and third form.

@RequestMapping(value = "/changePass", method = RequestMethod.POST)
public @ResponseBody String  resetPass( @RequestParam(value="newpass", required=true) String newpass, @RequestParam(value="newpass2", required=true) String newpass2,
                                            HttpServletRequest request, Model model, HttpServletResponse httpServletResponse) 
{
    User user = (User)request.getSession(false).getAttribute("user");
    if(user.getUser_name()!=null && newpass.matches(newpass2)){
        userDao.resetPass(user.getUser_name(), encoder.encode(newpass));
        String news = userDao.getDynamicNewsByUser(user.getUser_name());
        model.addAttribute("user",user);
        model.addAttribute("news", news);
        return "MainLayout_Jay";//"home";

    } else {
        return "login";//"index";
    }

}

And below is my spring config

<bean id="annotationResolver" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.nexis.cardholder" />
<mvc:annotation-driven >
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:interceptors>
    <bean class="com.nexis.cardholder.session.interceptors.URLInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/Pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
    <property name="order" value="1" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" >
    <property name="order" value="2" />
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
    <property name="order" value="0" />
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/views.xml</value>
        </list>
    </property>
</bean>

I have two issues. 1) The last form submission dosent return a view with the data in it. It just returns an empty page with controller method's return string in it.

2) I configured my home page in both tiles.xml and put it in /web-inf/pages folder. so if tiles view resolver could not find it, regular resolver should have. i doubt if its treating this request as a ajax request and skipping the model-view mapping part totally. how do i figure out the root cause.

2.5)if i want to parse ajax requests as Json, should i use @restcontroller and will it automatically send the responce as json? i tried using MappingJackson2HttpMessageConverter but didnt see any difference in debug mode?? did it even get used?