问:
Is there possible to directly save html as pdf instead of opening print preview and save as pdf?
I have a printable version of html, i want it to save as pdf instead ask user to print.

```<code>window.print();
</code>```

Right now, i am using Google chrome. When every time want to save the html as pdf, need change "destination" to Microsoft Print to PDF. I want skip these steps and directly save as PDF. Is there possible to do this?

答:
```<code><form class="form" style="max-width: none; width: 1005px;">

        <h2 style="color: #0094ff">Hello</h2>
         <table>
            <tbody>
                <tr>
                    <th>Company</th>
                    <th>Contact</th>
                    <th>Country</th>
                </tr>
                <tr>
                    <td>Alfreds Futterkiste</td>
                    <td>Maria Anders</td>
                    <td>Germany</td>
                </tr>
                <tr>
                    <td>Centro comercial Moctezuma</td>
                    <td>Francisco Chang</td>
                    <td>Mexico</td>
                </tr>
                <tr>
                    <td>Ernst Handel</td>
                    <td>Roland Mendel</td>
                    <td>Austria</td>
                </tr>
                <tr>
                    <td>Island Trading</td>
                    <td>Helen Bennett</td>
                    <td>UK</td>
                </tr>
                <tr>
                    <td>Laughing Bacchus Winecellars</td>
                    <td>Yoshi Tannamuri</td>
                    <td>Canada</td>
                </tr>
                <tr>
                    <td>Magazzini Alimentari Riuniti</td>
                    <td>Giovanni Rovelli</td>
                    <td>Italy</td>
                </tr>
            </tbody>
        </table>

    </form>
   <style type="text/css">
      table {
            font-family: arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        td, th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }

        tr:nth-child(even) {
            background-color: #dddddd;
        }
   </style>
      <input type="button" id="create_pdf" value="Generate PDF">
      <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>

   <script>
    (function () {
        var
         form = $('.form'),
         cache_width = form.width(),
         a4 = [595.28, 841.89]; // for a4 size paper width and height

        $('#create_pdf').on('click', function () {
            $('body').scrollTop(0);
            createPDF();
        });
        //create pdf
        function createPDF() {
            getCanvas().then(function (canvas) {
                var
                 img = canvas.toDataURL("image/png"),
                 doc = new jsPDF({
                     unit: 'px',
                     format: 'a4'
                 });
                doc.addImage(img, 'JPEG', 20, 20);
           //   doc.save('Bhavdip-html-to-pdf.pdf');
            //window.open();

            doc.output('datauristring');        //returns the data uri string
            //opens the data uri in current window
            var blob = doc.output("blob");
            window.open(URL.createObjectURL(blob));
           // doc.output('dataurlnewwindow');

                form.width(cache_width);
            });
        }

        // create canvas object
        function getCanvas() {
            form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
            return html2canvas(form, {
                imageTimeout: 2000,
                removeContainer: true
            });
        }

    }());
</script>
<script>
    /*
 * jQuery helper plugin for examples and tests
 */
    (function ($) {
        $.fn.html2canvas = function (options) {
            var date = new Date(),
            $message = null,
            timeoutTimer = false,
            timer = date.getTime();
            html2canvas.logging = options && options.logging;
            html2canvas.Preload(this[0], $.extend({
                complete: function (images) {
                    var queue = html2canvas.Parse(this[0], images, options),
                    $canvas = $(html2canvas.Renderer(queue, options)),
                    finishTime = new Date();

                    $canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
                    $canvas.siblings().toggle();

                    $(window).click(function () {
                        if (!$canvas.is(':visible')) {
                            $canvas.toggle().siblings().toggle();
                            throwMessage("Canvas Render visible");
                        } else {
                            $canvas.siblings().toggle();
                            $canvas.toggle();
                            throwMessage("Canvas Render hidden");
                        }
                    });
                    throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
                }
            }, options));

            function throwMessage(msg, duration) {
                window.clearTimeout(timeoutTimer);
                timeoutTimer = window.setTimeout(function () {
                    $message.fadeOut(function () {
                        $message.remove();
                    });
                }, duration || 2000);
                if ($message)
                    $message.remove();
                $message = $('<div ></div>').html(msg).css({
                    margin: 0,
                    padding: 10,
                    background: "#000",
                    opacity: 0.7,
                    position: "fixed",
                    top: 10,
                    right: 10,
                    fontFamily: 'Tahoma',
                    color: '#fff',
                    fontSize: 12,
                    borderRadius: 12,
                    width: 'auto',
                    height: 'auto',
                    textAlign: 'center',
                    textDecoration: 'none'
                }).hide().fadeIn().appendTo('body');
            }
        };
    })(jQuery);

</script>
</code>```

Body:
I have a printable version of html, i want it to save as pdf instead ask user to print.

window.print();

Right now, i am using Google chrome. When every time want to save the html as pdf, need change "destination" to Microsoft Print to PDF. I want skip these steps and directly save as PDF. Is there possible to do this?


来源: stackexchange

问:
How to write an ex script that searches for text and deletes the next n lines?
I want to write an ex script that searches for text and then deletes 23 lines. I created an exscript file that contains:

```<code>/block_2/
23d
w
</code>```

I then tried $ ex - index.html < exscript, but it makes wrong, unpredictable edits.

Those commands work when opening the file in ex, but not with the script. How can I fix it? I don't want to use line numbers, since I have to run the script on hundreds of files, and the line numbers will be different.

答:
I figured it out:

Script:

```<code>g/block_2/ .,+22 d
x
</code>```

Then:

```<code>$ ex - index.html < exscript
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to write an ex script that searches for text and then deletes 23 lines. I created an exscript file that contains:

/block_2/
23d
w

I then tried $ ex - index.html < exscript, but it makes wrong, unpredictable edits.

Those commands work when opening the file in ex, but not with the script. How can I fix it? I don't want to use line numbers, since I have to run the script on hundreds of files, and the line numbers will be different.

Body:
I figured it out:

Script:

g/block_2/ .,+22 d
x

Then:

$ ex - index.html < exscript


问:
How to check java version at linux (RedHat6)
 I am trying to check what java version I have installed in my linux machine, I have tried:

```<code>which java
</code>```

and I get:

```<code>/usr/bin/java
</code>```

but when I type:

```<code>java -version
</code>```

the console is returning nothing and getting stuck in a "java mode" , feels like the command called java and its waiting for my inputs, any thing I type then returns nothing... until I type crt+C it exits the mode...

答:
To check which version of Java is installed, follow this procedure:
-Open a Linux command prompt.
-Enter the command java -version.

-If Java version is installed on your system, you see a Java installed response. Check the version number in the message.

-If Java is not installed on your system, or the version of Java is earlier than 1.6, use the Linux Yellowdog Update, Modified (yum) utility to install a compatible version. If the 64-bit version of Java V1.6 is not installed, the installation does not complete successfully.

https://www.ibm.com/support/knowledgecenter/en/SS88XH_1.6.1/iva/install_mils_linux_java.html

Body:
 I am trying to check what java version I have installed in my linux machine, I have tried:

which java

and I get:

/usr/bin/java

but when I type:

java -version

the console is returning nothing and getting stuck in a "java mode" , feels like the command called java and its waiting for my inputs, any thing I type then returns nothing... until I type crt+C it exits the mode...


问:
fullcalendar, How to get the time down the calender side
I would like to know how to get the time down the side of the calender in 30 minute periods in the week and day views.

I have the following code.

```<code> $('#calendar').fullCalendar({
            header: {
                left: 'prev,next, today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            defaultView:'basicWeek',
            axisFormat:'h(:mm)tt',
            slotMinutes:'30',
            firstHour:'6',
            minTime:'6',
            maxTime:'22',
            theme: true,
            weekMode:'variable',
            editable: false,
            selectable: true,
            selectHelper: true,
            incrementDate: date,
            events: function(start, end, callback) {
                $.ajax({

                   Ajax stuff

                });
            }, //end event
            eventClick: function(calEvent, jsEvent, view) {
                click event stuff
            }//end eventClick
        });
</code>```

But the time does not display down the side of the calender. What options am I missing or can this be done at all.

答:
Change:

```<code>defaultView:'basicWeek'
</code>```

To

```<code>defaultView:'agendaWeek'
</code>```

Probably want to change your buttons also. (Use agendaWeek and/or AgendaDay)

ContentLicense: CC BY-SA 2.5

Body:
I would like to know how to get the time down the side of the calender in 30 minute periods in the week and day views.

I have the following code.

 $('#calendar').fullCalendar({
            header: {
                left: 'prev,next, today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            defaultView:'basicWeek',
            axisFormat:'h(:mm)tt',
            slotMinutes:'30',
            firstHour:'6',
            minTime:'6',
            maxTime:'22',
            theme: true,
            weekMode:'variable',
            editable: false,
            selectable: true,
            selectHelper: true,
            incrementDate: date,
            events: function(start, end, callback) {
                $.ajax({

                   Ajax stuff

                });
            }, //end event
            eventClick: function(calEvent, jsEvent, view) {
                click event stuff
            }//end eventClick
        });

But the time does not display down the side of the calender. What options am I missing or can this be done at all.

Body:
Change:

defaultView:'basicWeek'

To

defaultView:'agendaWeek'

Probably want to change your buttons also. (Use agendaWeek and/or AgendaDay)


问:
Codeigniter : source code top white space
I am working on codeigniter application.

screen shot
  https://i.stack.imgur.com/lEs13.jpg

please check above image for source code.

here top of page i am getting empty space and 15 line coding has been starting

Please any once can suggest, how my code start with 1 st line.

答:
The white space lines must be removed from the header template view where your header view is attached to body view.

Check the Controller first, then find which header is rendered for that page where you see the empty lines.

I hope it will help!


问:
outline half behind background-color half not
So I have some outlines on my divs which involves a mask. but for some reason half the outline is behind the background-color, while other half isn't (see by clicking the second row).

fiddle: https://jsfiddle.net/p08bc2bj/

HTML (ignore the vue stuff):

```<code><div class='wrapper'>
     <div v-for="(card, index) in deck" class="row" @click="cardClicked(card)" tabindex="0">
        <div class="mana key">
            1
        </div>
        <div class="coin key">
            1
        </div>
        <div class="name">
            test
        </div>
        <div class="count">
            1
        </div>
        <div class=mask></div>
    </div>
    <div v-for="(card, index) in deck" class="row" @click="cardClicked(card)" tabindex="0">
        <div class="mana key">
            1
        </div>
        <div class="coin key">
            1
        </div>
        <div class="name">
            test
        </div>
        <div class="count">
            1
        </div>
        <div class=mask></div>
    </div>
    <div v-for="(card, index) in deck" class="row" @click="cardClicked(card)" tabindex="0">
        <div class="mana key">
            1
        </div>
        <div class="coin key">
            1
        </div>
        <div class="name">
            test
        </div>
        <div class="count">
            1
        </div>
        <div class=mask></div>
    </div>
    <div v-for="(card, index) in deck" class="row" @click="cardClicked(card)" tabindex="0">
        <div class="mana key">
            1
        </div>
        <div class="coin key">
            1
        </div>
        <div class="name">
            test
        </div>
        <div class="count">
            1
        </div>
    </div>
    <div v-for="(card, index) in deck" class="row" @click="cardClicked(card)" tabindex="0">
        <div class="mana key">
            2
        </div>
        <div class="coin key">
            2
        </div>
        <div class="name">
            test
        </div>
        <div class="count">
            2
        </div>
    </div>
</div>
</code>```

css:

```<code>.mask {
    background-color: rgba(0,0,0,0.6);
    height: 100%;
    position: absolute;
    width: 100%;
}

.row {
    box-sizing: border-box;
    cursor: pointer;
    display: flex;
    position: relative;

    &:focus {
        outline: red solid thick;
    }

    .name {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: keep-all;
        white-space: nowrap;
    }
    .key {
        display: inline-block;
        position: relative;
        text-align: center;
        width: 1.5em;
        &.coin {
            background-color: yellow;
        }
        &.mana {
            background-color: lightblue;
        }
    }

    &.used {
        background-color: rgba(0, 0, 0, 0.3);
    }
}

.wrapper {
    max-height: 100vh;
    overflow: auto;
}
</code>```

答:
If you want to see red line under mask, z-index:100; in mask.
If else, z-index:100; in focus.

Body:
So I have some outlines on my divs which involves a mask. but for some reason half the outline is behind the background-color, while other half isn't (see by clicking the second row).

fiddle: https://jsfiddle.net/p08bc2bj/

HTML (ignore the vue stuff):

            1

            1

            test

            1

            1

            1

            test

            1

            1

            1

            test

            1

            1

            1

            test

            1

            2

            2

            test

            2

css:

.mask {
    background-color: rgba(0,0,0,0.6);
    height: 100%;
    position: absolute;
    width: 100%;
}

.row {
    box-sizing: border-box;
    cursor: pointer;
    display: flex;
    position: relative;

    &:focus {
        outline: red solid thick;
    }

    .name {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: keep-all;
        white-space: nowrap;
    }
    .key {
        display: inline-block;
        position: relative;
        text-align: center;
        width: 1.5em;
        &.coin {
            background-color: yellow;
        }
        &.mana {
            background-color: lightblue;
        }
    }

    &.used {
        background-color: rgba(0, 0, 0, 0.3);
    }
}

.wrapper {
    max-height: 100vh;
    overflow: auto;
}


问:
SQL Server 2008 R2: Get first not null values from column
I have following tables to display the expected result.

Table:

```<code>CREATE TABLE Family
(
    ID int,
    Name varchar(20),
    Gender char(1)
);

INSERT INTO Family VALUES
(1,'Ram','M'),
(2,'Suraj','M'),
(3,'Sunitha','F'),
(4,'Deepika','F'),
(5,'Minakshi','F'),
(6,'Somu','M');

CREATE TABLE Child_parent
(
    Child_ID int,
    Parent_ID int
);

INSERT INTO Child_parent VALUES
(1,2),
(1,3),
(4,5),
(4,6);
</code>```

Expected Result:

```<code>Child_ID    ChildName   FatherName  MotherName
-----------------------------------------------
1           Ram         Suraj       Sunitha
4           Deepika     Somu        Minakshi
</code>```

My try:

```<code>SELECT  cp.Child_ID,
        f1.Name as ChildName,
        CASE WHEN f2.Gender = 'M' THEN f2.Name END FatherName,
        CASE WHEN f2.Gender = 'F' THEN f2.Name END MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID
</code>```

But getting result shows:

```<code>Child_ID    ChildName   FatherName  MotherName
----------------------------------------------
1           Ram         Suraj       NULL
1           Ram         NULL        Sunitha
4           Deepika     NULL        Minakshi
4           Deepika     Somu        NULL
</code>```

答:
try this</p>

```<code>SELECT  cp.Child_ID,
        f1.Name as ChildName,
        max(CASE WHEN f2.Gender = 'M' THEN f2.Name END) FatherName,
        max(CASE WHEN f2.Gender = 'F' THEN f2.Name END) MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID
group by cp.Child_ID,
        f1.Name
 order by cp.Child_ID
</code>```

Body:
I have following tables to display the expected result.

Table:

CREATE TABLE Family
(
    ID int,
    Name varchar(20),
    Gender char(1)
);

INSERT INTO Family VALUES
(1,'Ram','M'),
(2,'Suraj','M'),
(3,'Sunitha','F'),
(4,'Deepika','F'),
(5,'Minakshi','F'),
(6,'Somu','M');

CREATE TABLE Child_parent
(
    Child_ID int,
    Parent_ID int
);

INSERT INTO Child_parent VALUES
(1,2),
(1,3),
(4,5),
(4,6);

Expected Result:

Child_ID    ChildName   FatherName  MotherName
-----------------------------------------------
1           Ram         Suraj       Sunitha
4           Deepika     Somu        Minakshi

My try:

SELECT  cp.Child_ID,
        f1.Name as ChildName,
        CASE WHEN f2.Gender = 'M' THEN f2.Name END FatherName,
        CASE WHEN f2.Gender = 'F' THEN f2.Name END MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID

But getting result shows:

Child_ID    ChildName   FatherName  MotherName
----------------------------------------------
1           Ram         Suraj       NULL
1           Ram         NULL        Sunitha
4           Deepika     NULL        Minakshi
4           Deepika     Somu        NULL

Body:
try this

SELECT  cp.Child_ID,
        f1.Name as ChildName,
        max(CASE WHEN f2.Gender = 'M' THEN f2.Name END) FatherName,
        max(CASE WHEN f2.Gender = 'F' THEN f2.Name END) MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID
group by cp.Child_ID,
        f1.Name
 order by cp.Child_ID


问:
How to validate single date in javascript?
My requirement is below. Can someone suggest how to validate the given dates below ?

Valid dates :
1/1/2017
01/1/2017
1/01/2017
01/01/2017

Invalid dates :
13/12/2017
13/13/2017
12/35/2017
13/13/2017

答:
function validateDate(dateStr) {
   const regExp = /^(\d\d?)\/(\d\d?)\/(\d{4})$/;
   let matches = dateStr.match(regExp);
   let isValid = matches;
   let maxDate = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

   if (matches) {
     const month = parseInt(matches[1]);
     const date = parseInt(matches[2]);
     const year = parseInt(matches[3]);

     isValid = month <= 12 && month > 0;
     isValid &= date <= maxDate[month] && date > 0;

     const leapYear = (year % 400 == 0)
        || (year % 4 == 0 && year % 100 != 0);
     isValid &= month != 2 || leapYear || date <= 28;
   }

   return isValid
}

console.log(['1/1/2017', '01/1/2017', '1/01/2017', '01/01/2017', '13/12/2017', '13/13/2017', '12/35/2017'].map(validateDate));```

My previous answer is not working on Edge.

Body:
function validateDate(dateStr) {
   const regExp = /^(\d\d?)\/(\d\d?)\/(\d{4})$/;
   let matches = dateStr.match(regExp);
   let isValid = matches;
   let maxDate = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

   if (matches) {
     const month = parseInt(matches[1]);
     const date = parseInt(matches[2]);
     const year = parseInt(matches[3]);

     isValid = month <= 12 && month > 0;
     isValid &= date <= maxDate[month] && date > 0;

     const leapYear = (year % 400 == 0)
        || (year % 4 == 0 && year % 100 != 0);
     isValid &= month != 2 || leapYear || date <= 28;
   }

   return isValid
}

console.log(['1/1/2017', '01/1/2017', '1/01/2017', '01/01/2017', '13/12/2017', '13/13/2017', '12/35/2017'].map(validateDate));

My previous answer is not working on Edge.


问:
docker swarm with compose file does not recognize "links"
docker-compose.yml

```<code>version: '3.3'

services:

  hello:
    image: dockercloud/hello-world

  service_auth:
    image: beevelop/nginx-basic-auth
    ports:
      - 8080:80
    links:
      - hello:web
    environment:
      HTPASSWD: 'foo:$apr1$odHl5EJN$KbxMfo86Qdve2FH4owePn.'
</code>```

docker --version

```<code>Docker version 17.09.0-ce, build afdb6d4
</code>```

docker stack deploy -c docker-compose.yml auth

```<code>Ignoring unsupported options: links
</code>```

Why is links not supported?

答:
The official documentation does list what is not supported for compose and stack, and that includes links.

Links are not required to enable services to communicate - by default, any service can reach any other service at that service’s name. (See also, the Links topic in Networking in Compose.)

Hence that option is ignored when deploying a stack in swarm mode with a (version 3) Compose file.

```<code>$ docker stack deploy --compose-file docker-compose.yml vossibility

Ignoring unsupported options: links
</code>```

So: why the option is not supported?

Because links are not needed in a compose scenario, since all services can already communicate one with another (being in the same network set up by compose).

Body:
docker-compose.yml

version: '3.3'

services:

  hello:
    image: dockercloud/hello-world

  service_auth:
    image: beevelop/nginx-basic-auth
    ports:
      - 8080:80
    links:
      - hello:web
    environment:
      HTPASSWD: 'foo:$apr1$odHl5EJN$KbxMfo86Qdve2FH4owePn.'

docker --version

Docker version 17.09.0-ce, build afdb6d4

docker stack deploy -c docker-compose.yml auth

Ignoring unsupported options: links

Why is links not supported?

Body:
The official documentation does list what is not supported for compose and stack, and that includes links.

Links are not required to enable services to communicate - by default, any service can reach any other service at that service’s name. (See also, the Links topic in Networking in Compose.)

Hence that option is ignored when deploying a stack in swarm mode with a (version 3) Compose file.

$ docker stack deploy --compose-file docker-compose.yml vossibility

Ignoring unsupported options: links

So: why the option is not supported?

Because links are not needed in a compose scenario, since all services can already communicate one with another (being in the same network set up by compose).

ContentLicense: CC BY-SA 4.0


问:
Find a same column in different table in sql
I have a small problem, I have four table, I'm using mysql database

Survey Table Here all survey will be created.

```<code>╔══════════╤════════╗
║ SurveyId │ Name   ║
╠══════════╪════════╣
║ 1        │ First  ║
╟──────────┼────────╢
║ 2        │ Second ║
╚══════════╧════════╝
</code>```

Gauge category table

```<code>╔════════════╤═════════════╗
║ CategoryId │ Title       ║
╠════════════╪═════════════╣
║ 1          │ Stress      ║
╟────────────┼─────────────╢
║ 2          │ Environment ║
╟────────────┼─────────────╢
║ 3          │ Health      ║
╚════════════╧═════════════╝
</code>```

To connect both Gauge Category table with Survey table,

I use another table called Title table

Title table

Here title1,title2 and title3 are foreign keys of Gauge Category table, and surveyId is foreign key of Survey table

```<code>╔══════════════╤════════╤════════╤════════╤══════════╗
║ GaugeTitleId │ title1 │ title2 │ title3 │ surveyId ║
╠══════════════╪════════╪════════╪════════╪══════════╣
║ 1            │ 2      │ 3      │ 1      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 2            │ 1      │ 3      │ 2      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 3            │ 3      │ 1      │ 2      │ 2        ║
╚══════════════╧════════╧════════╧════════╧══════════╝
</code>```

Another table called called Average_values which has respective value of Title table

Average_values table

```<code>╔═════════╤════════╤════════╤════════╤══════════╤══════════════╗
║ GaugeID │ Gauge1 │ Guage2 │ Gauge3 │ SurveyId │ GaugeTitleId ║
╠═════════╪════════╪════════╪════════╪══════════╪══════════════╣
║ 1       │ 34     │ 76     │ 23     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 2       │ 56     │ 23     │ 67     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 3       │ 14     │ 28     │ 56     │ 1        │ 2            ║
╚═════════╧════════╧════════╧════════╧══════════╧══════════════╝
</code>```

My problem is, If I want to get the Stress values from Average_values table, how can I get it? Because the foreign keys are not in order. The output should be 23,56,28 . Is there any way to get it? I have another alternative idea, that modify the Average_values Table to

```<code>╔═════════╤════════╤════════════╤══════════╗
║ GuageId │ values │ CategoryId │ SurveyId ║
╚═════════╧════════╧════════════╧══════════╝
</code>```

and put the values one by one, Here CategoryId and SurveyID are in foreign key relationship of Gauge category table and Survey Table respectively. But I feel, it won't be an efficient table. Because a lot of data wants to be processed dynamically.

答:
If gauge1, gauge2, gauge3 rapresent the same concept, there is no reason to create multiple fields.

That is an “error” in database design.

You should normalize your table and have one row for every value.
 Relational databases engines are designed to work in that way.
Take a look at relational DB normalization over the internet to learn more.

Body:
I have a small problem, I have four table, I'm using mysql database

Survey Table Here all survey will be created.

╔══════════╤════════╗
║ SurveyId │ Name   ║
╠══════════╪════════╣
║ 1        │ First  ║
╟──────────┼────────╢
║ 2        │ Second ║
╚══════════╧════════╝

Gauge category table

╔════════════╤═════════════╗
║ CategoryId │ Title       ║
╠════════════╪═════════════╣
║ 1          │ Stress      ║
╟────────────┼─────────────╢
║ 2          │ Environment ║
╟────────────┼─────────────╢
║ 3          │ Health      ║
╚════════════╧═════════════╝

To connect both Gauge Category table with Survey table,

I use another table called Title table

Title table

Here title1,title2 and title3 are foreign keys of Gauge Category table, and surveyId is foreign key of Survey table

╔══════════════╤════════╤════════╤════════╤══════════╗
║ GaugeTitleId │ title1 │ title2 │ title3 │ surveyId ║
╠══════════════╪════════╪════════╪════════╪══════════╣
║ 1            │ 2      │ 3      │ 1      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 2            │ 1      │ 3      │ 2      │ 1        ║
╟──────────────┼────────┼────────┼────────┼──────────╢
║ 3            │ 3      │ 1      │ 2      │ 2        ║
╚══════════════╧════════╧════════╧════════╧══════════╝

Another table called called Average_values which has respective value of Title table

Average_values table

╔═════════╤════════╤════════╤════════╤══════════╤══════════════╗
║ GaugeID │ Gauge1 │ Guage2 │ Gauge3 │ SurveyId │ GaugeTitleId ║
╠═════════╪════════╪════════╪════════╪══════════╪══════════════╣
║ 1       │ 34     │ 76     │ 23     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 2       │ 56     │ 23     │ 67     │ 1        │ 1            ║
╟─────────┼────────┼────────┼────────┼──────────┼──────────────╢
║ 3       │ 14     │ 28     │ 56     │ 1        │ 2            ║
╚═════════╧════════╧════════╧════════╧══════════╧══════════════╝

My problem is, If I want to get the Stress values from Average_values table, how can I get it? Because the foreign keys are not in order. The output should be 23,56,28 . Is there any way to get it? I have another alternative idea, that modify the Average_values Table to

╔═════════╤════════╤════════════╤══════════╗
║ GuageId │ values │ CategoryId │ SurveyId ║
╚═════════╧════════╧════════════╧══════════╝

and put the values one by one, Here CategoryId and SurveyID are in foreign key relationship of Gauge category table and Survey Table respectively. But I feel, it won't be an efficient table. Because a lot of data wants to be processed dynamically.


问:
how to include ID in selenium
my selenium script show only find_element_by_css_selector

how to include find_element_by_id

it throws attribute error

```<code>from selenium import webdriver
import os
import shutil
import sys
import time
import selenium
from selenium.webdriver.common.keys import Keys
import random

options = webdriver.ChromeOptions()
br = webdriver.Chrome(chrome_options=options)

login=br.find_element_by_css_selector('body > div > div > newpage > submitbtn') login.click()

new=br.find_element_by_id('buttonname') new.click()
</code>```

答:
As you dont share the HTML it is quite difficult ot answer but you have to use id using find_element_by_id

```<code>login=br.find_element_by_id('value of id button') login.click()
</code>```

Title: how to include ID in selenium

Body:
my selenium script show only find_element_by_css_selector

how to include find_element_by_id

it throws attribute error

from selenium import webdriver
import os
import shutil
import sys
import time
import selenium
from selenium.webdriver.common.keys import Keys
import random

options = webdriver.ChromeOptions()
br = webdriver.Chrome(chrome_options=options)

login=br.find_element_by_css_selector('body > div > div > newpage > submitbtn') login.click()

new=br.find_element_by_id('buttonname') new.click()

Body:
As you dont share the HTML it is quite difficult ot answer but you have to use id using find_element_by_id

login=br.find_element_by_id('value of id button') login.click()


问:
JTextField doesn't seem to fire PropertyChangeEvent
I am trying to create a swing form where the text fields are connected to a bean using the bensbindings framework. I have set this up in the Netbeans matisse editor. However, changing the content of a JTextField doesn't seem to update the bean.

Trying just a simple case of a JTextField with a PropertyChangeListener, there never occurs any property change events as text is input. When are these events fired? Or is it only possible to bind from a bean to the text field and not the other way?

What is the prefered way of getting the content of a JTextField to update a Bean? IS it doing it manually when a button is pressed?

I am pretty new to swing, and I want to learn how to use beansbindings and the Better Swing Application Framework to build an application.

答:
As specified by JTextComponent#setText:

Note that text is not a bound property, so no PropertyChangeEvent is fired when it changes. To listen for changes to the text, use DocumentListener.


问:
ng-hide and ng-show for current row
I have one table.In than am doing row hide and show using angular for edit and save purpose.
It's working fine.

```<code>$scope.init=function(){
    $scope.editable=true;
}
</code>```

Now when I click on edit button in  table row ,edit button will be hided and save button will be shown.

```<code>$scope.editRow = function(id){
    console.log(id);\\row id will be displayed here
    $scope.editable=false;
}
</code>```

Here am facing one problem ,if I click edit on second row ,only second row should be editable.
I know we can do this easily using row id in jquery.But here I don't know how to do this in angular for ng-hide and ng-show.

Any Help?Thanks!!

code:

```<code><table>
<thead>
<tr>
    <th>Qualification</th>
    <th>Course</th>
    <th>Grade Attained</th>
    <th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="detail in educationDetails">
    <td>
        <span ng-show="editable">{{detail.qualification}}</span>
        <input type="text" ng-model="detail.qualification" ng-hide="editable"/>
    </td>
    <td>
        <span ng-show="editable">{{detail.education_type}}</span>
        <input type="text" ng-model="detail.education_type" ng-hide="editable"/>
    </td>
    <td>
        <span ng-show="editable">{{detail.grade}}</span>
        <input type="text" ng-model="detail.grade" ng-hide="editable"/>
    </td>
    <td>
        <div ng-show="editable">
            <span><i class='fa fa-trash-o' ng-click="deleteEducationDetail(detail)"></i></span>
            <span><i class='fa fa-pencil' ng-click="editEducationDetail(detail)"></i></span>
        </div>
        <div ng-hide="editable">
            <span><i class='fa fa-floppy-o' ng-click="updateEducationDetail(detail)"></i></span>
            <span><i class='fa fa-times' ng-click="cancelEducationDetail(detail)"></i></span>
        </div>
    </td>
</tr>

</tbody>
</table>

$scope.init = function () {
$scope.editable = true;
}
$scope.editEducationDetail = function (detail) {
detail.editable = false;
}
</code>```

答:
In order to make each row editable, you can pass the row object inside the function and make editable true as follows,

```<code> $scope.editRow = function(rowobject){
    rowobject.editable=true;
 }
</code>```

code:

```<code><table>
<thead>
<tr>
    <th>Qualification</th>
    <th>Course</th>
    <th>Grade Attained</th>
    <th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="detail in educationDetails">
    <td>
        <span ng-show="editable">{{detail.qualification}}</span>
        <input type="text" ng-model="detail.qualification" ng-hide="editable"/>
    </td>
    <td>
        <span ng-show="editable">{{detail.education_type}}</span>
        <input type="text" ng-model="detail.education_type" ng-hide="editable"/>
    </td>
    <td>
        <span ng-show="editable">{{detail.grade}}</span>
        <input type="text" ng-model="detail.grade" ng-hide="editable"/>
    </td>
    <td>
        <div ng-show="editable">
            <span><i class='fa fa-trash-o' ng-click="deleteEducationDetail(detail)"></i></span>
            <span><i class='fa fa-pencil' ng-click="editEducationDetail(detail)"></i></span>
        </div>
        <div ng-hide="editable">
            <span><i class='fa fa-floppy-o' ng-click="updateEducationDetail(detail)"></i></span>
            <span><i class='fa fa-times' ng-click="cancelEducationDetail(detail)"></i></span>
        </div>
    </td>
</tr>

</tbody>
</table>

$scope.init = function () {
$scope.editable = true;
}
$scope.editEducationDetail = function (detail) {
detail.editable = false;
}
</code>```

Title: ng-hide and ng-show for current row

Body:
I have one table.In than am doing row hide and show using angular for edit and save purpose.
It's working fine.

$scope.init=function(){
    $scope.editable=true;
}

Now when I click on edit button in  table row ,edit button will be hided and save button will be shown.

$scope.editRow = function(id){
    console.log(id);\\row id will be displayed here
    $scope.editable=false;
}

Here am facing one problem ,if I click edit on second row ,only second row should be editable.
I know we can do this easily using row id in jquery.But here I don't know how to do this in angular for ng-hide and ng-show.

Any Help?Thanks!!

code:

    Qualification
    Course
    Grade Attained
    Action

        {{detail.qualification}}
        <input type="text" ng-model="detail.qualification" ng-hide="editable"/>

        {{detail.education_type}}
        <input type="text" ng-model="detail.education_type" ng-hide="editable"/>

        {{detail.grade}}
        <input type="text" ng-model="detail.grade" ng-hide="editable"/>

$scope.init = function () {
$scope.editable = true;
}
$scope.editEducationDetail = function (detail) {
detail.editable = false;
}

Body:
In order to make each row editable, you can pass the row object inside the function and make editable true as follows,

 $scope.editRow = function(rowobject){
    rowobject.editable=true;
 }

code:

<table>
<thead>
<tr>
    <th>Qualification</th>
    <th>Course</th>
    <th>Grade Attained</th>
    <th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="detail in educationDetails">
    <td>
        <span ng-show="editable">{{detail.qualification}}</span>
        <input type="text" ng-model="detail.qualification" ng-hide="editable"/>
    </td>
    <td>
        <span ng-show="editable">{{detail.education_type}}</span>
        <input type="text" ng-model="detail.education_type" ng-hide="editable"/>
    </td>
    <td>
        <span ng-show="editable">{{detail.grade}}</span>
        <input type="text" ng-model="detail.grade" ng-hide="editable"/>
    </td>
    <td>
        <div ng-show="editable">
            <span><i class='fa fa-trash-o' ng-click="deleteEducationDetail(detail)"></i></span>
            <span><i class='fa fa-pencil' ng-click="editEducationDetail(detail)"></i></span>
        </div>
        <div ng-hide="editable">
            <span><i class='fa fa-floppy-o' ng-click="updateEducationDetail(detail)"></i></span>
            <span><i class='fa fa-times' ng-click="cancelEducationDetail(detail)"></i></span>
        </div>
    </td>
</tr>

</tbody>
</table>

$scope.init = function () {
$scope.editable = true;
}
$scope.editEducationDetail = function (detail) {
detail.editable = false;
}


问:
How to get values out of promises?

I have been smashing my head against this problem for a very long time; far too long for what it, almost certainly trivial.

I want to get a specific value, as if it were returned by a function. Promises are supposed to be placeholders for values and onAuthRequired takes a function that returns a blocking response object:

```<code>{
  authCredentials: {
    username: "..."
    password: "..."
  }
}
</code>```

So I need to create a function that returns that structure and does so asynchronously. So I put in the async keyword, meaning I can await the resolution of the promise ... I think.
But before I can build that structure, I have to do an asynchronous operation on the nativeMessaging API ... which doesn't return a promise ... I think.
So I have to wrap it, somehow, in a promise ...

Edit:
I have updated the code below to reflect the current state, an amalgam of all the great responses thus far.

```<code>async function get_data() {
  return new Promise((resolve, reject) => {
    var data = chrome.runtime.sendNativeMessage('Host', {text:'Ready'},
      function(response) {
        resolve(response);
      }
    };
  })
};

async function get_creds() {
  var data = await get_data();
  if (null != data) {
    creds = JSON.parse(data);
    return {
      authCredentials: {
        username: creds.username,
        password: creds.password
      }
    };
  }
};

chrome.webRequest.onAuthRequired.addListener(
  function(details, get_creds),
  {urls: ["<all_urls>"]},
  ['blocking']
);
</code>```

I experimented with the following code:

```<code>chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    var creds = await get_data(); // Uncaught SyntaxError: unexpected identifier
    creds = JSON.parse(creds);
    return {
      authCredentials: {
        username: creds.username,
        password: creds.password
      }
    };
  },
  {urls:["<all_urls>"]},
  ['asyncBlocking']
);
</code>```

It called get_data() directly but had an unexpected identifier error.

If I removed the await keyword it "worked" ... that is, it tried to do something on the event ... but it didn't pass the object back. What it did is set a message in the bottom left of the screen "waiting on extension ... " and call the get_data() function about 3 times.

If I change ['asyncBlocking'] to ['blocking'], it fails to call get_data() at all.

I have no idea what's happening here.

So this should pass the value returned by the Native Messaging Host back via these weird promises and then plug right in to where onAuthRequired expects its JSON structure to be returned ...

Edit:
I expect the object returned by get_creds() to be passed to onAuthRequired.
At this present point, there's an 'unexpected token' token on function(details, get_creds) ... so that's obviously wrong.
I suspect that I might need to use another promise in get_creds() which will fill in for the authCredentials object ...

Aside from all the unexpected identifiers whose origin I can't fathom, I've a sense that I'm doing this whole thing backwards.

Welcome to my wit's end ... and thanks for any light you can shed on my ignorance.

答:
To answer the question "How do I get values out of promises?" I was informed by all 3 provided examples. No one had the full solution, however.

Edit:

Full solution to my specific problem (as it happens, it used callbacks, not promises) is here.

Caveat - While I have managed to have an object passed back to onAuthRequest by passing values back through promises, there is some issue with the object, such that it's not having the desired effect.

Firstly, get_data() needed to be changed.

```<code>async function get_data() {
  return new Promise((resolve, reject) => {
    const data = chrome.runtime.sendNativeMessage(
      'host',
      {text: "Ready"},
      function(response){
        resolve(response);
      }
    );
  });
});
</code>```

Next, I was returning a promise on get_creds() (now get_data() ) ... but I wasn't doing anything with it.
I needed to use promiseFunction.then(function(response){ ... }) in order to move the resolved value of the promise out. This was helpful, too.

```<code>chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    get_data().then(function(response) {
      // --> result's value is available in here
      return {
        authCredentials: {
          username: response.username,
          password: response.password
        }
      };
    });
  },
  {urls: ["<all_urls>"]},
  ['asyncBlocking'] // --> not just 'Blocking'
);
</code>```

Additionally, I needed to return an object - which is done via the callback:

```<code>chrome.webRequest.onAuthRequired.addListener(
  function handler(details){ // --> callback
    ...
      return {  // --> an object
        authCredentials: {
          username: response.username,
          password: response.password
        }
    ...
  },
  {urls: ["<all_urls>"]},
  ['asyncBlocking'] // --> not just 'Blocking'
);
</code>```

Finally, there needs to be a modification of the callback to allow the promise.then() to output something ...
Found here

```<code>chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    get_data().then(function(response) {
... )
</code>```

becomes:

```<code>chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    return get_data().then(function(response) {
... )
</code>```

So that's how to get the value out of that promise and into the callback function... I have more work to do to get the desired result, however.

Title: How to get values out of promises?

Body:
I have been smashing my head against this problem for a very long time; far too long for what it, almost certainly trivial.

I want to get a specific value, as if it were returned by a function. Promises are supposed to be placeholders for values and onAuthRequired takes a function that returns a blocking response object:

{
  authCredentials: {
    username: "..."
    password: "..."
  }
}

So I need to create a function that returns that structure and does so asynchronously. So I put in the async keyword, meaning I can await the resolution of the promise ... I think.
But before I can build that structure, I have to do an asynchronous operation on the nativeMessaging API ... which doesn't return a promise ... I think.
So I have to wrap it, somehow, in a promise ...

Edit:
I have updated the code below to reflect the current state, an amalgam of all the great responses thus far.

async function get_data() {
  return new Promise((resolve, reject) => {
    var data = chrome.runtime.sendNativeMessage('Host', {text:'Ready'},
      function(response) {
        resolve(response);
      }
    };
  })
};

async function get_creds() {
  var data = await get_data();
  if (null != data) {
    creds = JSON.parse(data);
    return {
      authCredentials: {
        username: creds.username,
        password: creds.password
      }
    };
  }
};

chrome.webRequest.onAuthRequired.addListener(
  function(details, get_creds),
  {urls: ["<all_urls>"]},
  ['blocking']
);

I experimented with the following code:

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    var creds = await get_data(); // Uncaught SyntaxError: unexpected identifier
    creds = JSON.parse(creds);
    return {
      authCredentials: {
        username: creds.username,
        password: creds.password
      }
    };
  },
  {urls:["<all_urls>"]},
  ['asyncBlocking']
);

It called get_data() directly but had an unexpected identifier error.

If I removed the await keyword it "worked" ... that is, it tried to do something on the event ... but it didn't pass the object back. What it did is set a message in the bottom left of the screen "waiting on extension ... " and call the get_data() function about 3 times.

If I change ['asyncBlocking'] to ['blocking'], it fails to call get_data() at all.

I have no idea what's happening here.

So this should pass the value returned by the Native Messaging Host back via these weird promises and then plug right in to where onAuthRequired expects its JSON structure to be returned ...

Edit:
I expect the object returned by get_creds() to be passed to onAuthRequired.
At this present point, there's an 'unexpected token' token on function(details, get_creds) ... so that's obviously wrong.
I suspect that I might need to use another promise in get_creds() which will fill in for the authCredentials object ...

Aside from all the unexpected identifiers whose origin I can't fathom, I've a sense that I'm doing this whole thing backwards.

Welcome to my wit's end ... and thanks for any light you can shed on my ignorance.

Body:
To answer the question "How do I get values out of promises?" I was informed by all 3 provided examples. No one had the full solution, however.

Edit:

Full solution to my specific problem (as it happens, it used callbacks, not promises) is here.

Caveat - While I have managed to have an object passed back to onAuthRequest by passing values back through promises, there is some issue with the object, such that it's not having the desired effect.

Firstly, get_data() needed to be changed.

async function get_data() {
  return new Promise((resolve, reject) => {
    const data = chrome.runtime.sendNativeMessage(
      'host',
      {text: "Ready"},
      function(response){
        resolve(response);
      }
    );
  });
});

Next, I was returning a promise on get_creds() (now get_data() ) ... but I wasn't doing anything with it.
I needed to use promiseFunction.then(function(response){ ... }) in order to move the resolved value of the promise out. This was helpful, too.

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    get_data().then(function(response) {
      // --> result's value is available in here
      return {
        authCredentials: {
          username: response.username,
          password: response.password
        }
      };
    });
  },
  {urls: ["<all_urls>"]},
  ['asyncBlocking'] // --> not just 'Blocking'
);

Additionally, I needed to return an object - which is done via the callback:

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){ // --> callback
    ...
      return {  // --> an object
        authCredentials: {
          username: response.username,
          password: response.password
        }
    ...
  },
  {urls: ["<all_urls>"]},
  ['asyncBlocking'] // --> not just 'Blocking'
);

Finally, there needs to be a modification of the callback to allow the promise.then() to output something ...
Found here

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    get_data().then(function(response) {
... )

becomes:

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    return get_data().then(function(response) {
... )

So that's how to get the value out of that promise and into the callback function... I have more work to do to get the desired result, however.


问:
null response usin Retrofit Library in android
Here is my JSONArray Response from Web service:

And Class Java :

```<code>public class Product {

  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  @SerializedName("products")
  private List<Product> products;

  public Product()
  {

  }

}
</code>```

response is null

答:
You should use it like that

=>Main API Model Class

```<code> public class APIResult {
        @SerializedName("products")
        private ProductModelClass products;

        public ProductModelClass getProducts() {
            return products;
        }

        public void setProducts(ProductModelClass products) {
            this.products = products;
        }
    }
</code>```

=>For data and current page  model class

```<code>public class ProductModelClass {

    @SerializedName("current_page")
    private int current_page;

    @SerializedName("data")
    private ArrayList<ProductDataModel> data;

    public int getCurrent_page() {
        return current_page;
    }

    public void setCurrent_page(int current_page) {
        this.current_page = current_page;
    }

    public ArrayList<ProductDataModel> getData() {
        return data;
    }

    public void setData(ArrayList<ProductDataModel> data) {
        this.data = data;
    }
}
</code>```

=>For Details of products Data

```<code>public class ProductDataModel {

    @SerializedName("id")
    private int id;

    @SerializedName("name")
    private String name;

    @SerializedName("image")
    private String image;

    @SerializedName("description")
    private String description;

    @SerializedName("price")
    private int price;

    @SerializedName("discount")
    private int discount;

    @SerializedName("shop_id")
    private int shop_id;

    @SerializedName("discount_type")
    private String discount_type;

    @SerializedName("discount_exp")
    private String discount_exp;

    @SerializedName("discount_limit")
    private String discount_limit;

    @SerializedName("vote_id")
    private String vote_id;

    @SerializedName("video_id")
    private String video_id;

    @SerializedName("status")
    private String status;

    @SerializedName("created_at")
    private String created_at;

    @SerializedName("updated_at")
    private String updated_at;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(int discount) {
        this.discount = discount;
    }

    public int getShop_id() {
        return shop_id;
    }

    public void setShop_id(int shop_id) {
        this.shop_id = shop_id;
    }

    public String getDiscount_type() {
        return discount_type;
    }

    public void setDiscount_type(String discount_type) {
        this.discount_type = discount_type;
    }

    public String getDiscount_exp() {
        return discount_exp;
    }

    public void setDiscount_exp(String discount_exp) {
        this.discount_exp = discount_exp;
    }

    public String getDiscount_limit() {
        return discount_limit;
    }

    public void setDiscount_limit(String discount_limit) {
        this.discount_limit = discount_limit;
    }

    public String getVote_id() {
        return vote_id;
    }

    public void setVote_id(String vote_id) {
        this.vote_id = vote_id;
    }

    public String getVideo_id() {
        return video_id;
    }

    public void setVideo_id(String video_id) {
        this.video_id = video_id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }
}
</code>```

Body:
Here is my JSONArray Response from Web service:

And Class Java :

public class Product {

  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  @SerializedName("products")
  private List<Product> products;

  public Product()
  {

  }

}

response is null

Body:
You should use it like that

=>Main API Model Class

 public class APIResult {
        @SerializedName("products")
        private ProductModelClass products;

        public ProductModelClass getProducts() {
            return products;
        }

        public void setProducts(ProductModelClass products) {
            this.products = products;
        }
    }

=>For data and current page  model class

public class ProductModelClass {

    @SerializedName("current_page")
    private int current_page;

    @SerializedName("data")
    private ArrayList<ProductDataModel> data;

    public int getCurrent_page() {
        return current_page;
    }

    public void setCurrent_page(int current_page) {
        this.current_page = current_page;
    }

    public ArrayList<ProductDataModel> getData() {
        return data;
    }

    public void setData(ArrayList<ProductDataModel> data) {
        this.data = data;
    }
}

=>For Details of products Data

public class ProductDataModel {

    @SerializedName("id")
    private int id;

    @SerializedName("name")
    private String name;

    @SerializedName("image")
    private String image;

    @SerializedName("description")
    private String description;

    @SerializedName("price")
    private int price;

    @SerializedName("discount")
    private int discount;

    @SerializedName("shop_id")
    private int shop_id;

    @SerializedName("discount_type")
    private String discount_type;

    @SerializedName("discount_exp")
    private String discount_exp;

    @SerializedName("discount_limit")
    private String discount_limit;

    @SerializedName("vote_id")
    private String vote_id;

    @SerializedName("video_id")
    private String video_id;

    @SerializedName("status")
    private String status;

    @SerializedName("created_at")
    private String created_at;

    @SerializedName("updated_at")
    private String updated_at;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(int discount) {
        this.discount = discount;
    }

    public int getShop_id() {
        return shop_id;
    }

    public void setShop_id(int shop_id) {
        this.shop_id = shop_id;
    }

    public String getDiscount_type() {
        return discount_type;
    }

    public void setDiscount_type(String discount_type) {
        this.discount_type = discount_type;
    }

    public String getDiscount_exp() {
        return discount_exp;
    }

    public void setDiscount_exp(String discount_exp) {
        this.discount_exp = discount_exp;
    }

    public String getDiscount_limit() {
        return discount_limit;
    }

    public void setDiscount_limit(String discount_limit) {
        this.discount_limit = discount_limit;
    }

    public String getVote_id() {
        return vote_id;
    }

    public void setVote_id(String vote_id) {
        this.vote_id = vote_id;
    }

    public String getVideo_id() {
        return video_id;
    }

    public void setVideo_id(String video_id) {
        this.video_id = video_id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }
}


问:
escaping CRLF in HTTP multipart/form-data content type (iOS)
I'm trying to post a file using the multipart/form-data content type, and I got this question:

Shouldn't I escape CRLFs when I write the content of a file? I got a code piece on the web and I think it might be wrong:

```<code>NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: url];
[req setHTTPMethod: @"POST"];

NSString* contentType = @"multipart/form-data, boundary=AaB03x";
[req setValue:contentType forHTTPHeaderField: @"Content-type"];

NSData* boundary = [@"\r\n--AaB03x\r\n" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData: boundary];
[postBody appendData: [@"Content-Disposition: form-data; name=\"datafile\"; filename=\"t.jpg\"" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData: [@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData: imageData];
[postBody appendData: boundary];
[req setHTTPBody:postBody];
</code>```

This is wrong because imageData might contain \r\n sequences, right? If so, is there a way to escape CRLFs in raw data? Or am I missing something?

Thanks in advance!

答:
This is an interesting question.  Looking at the multipart media type RFC it appears that it is up to the composing agent to make sure that the boundary does not appear in the encapsulated data. In addition, it states the following:

NOTE:  Because boundary delimiters must not appear in the body parts
     being encapsulated, a user agent must exercise care to choose a
     unique boundary parameter value.  The boundary parameter value in the
     example above could have been the result of an algorithm designed to
     produce boundary delimiters with a very low probability of already
     existing in the data to be encapsulated without having to prescan the
     data.

I interpret this to mean that in order to be sure that the boundary value doesn't appear in the encapsulated data, you would have to scan the data for the boundary value.  Because this is an unacceptably expensive operation in most cases, it's expected that user agents will simply choose a value that has a very low probability of occurring in the data.

Consider the probability of the boundary in your example occurring in a random string of bytes (which for the sake of argument, we will assume represents a JPEG image).  The full string that would need to be matched in order to end your image data early would be "\r\n--AaB03x" - 10 bytes, or 80 bits.  Starting from any bit, the chance that the next 10 bytes are that sequence is one in 2^80.  In a 1MB JPEG file, there are 2^23 bits.  This means that the chance of a JPEG file containing the sequence is less than 2^23/2^80, or one in 2^57 (more than one hundred quadrillion).

So, I think the answer is that to be 100% sure, you would have to check the data for the boundary sequence, and then use a different one if that boundary sequence exists in the data.  But in practice, the chances of the boundary sequence occurring are small enough that it's not worth it.

Body:
I'm trying to post a file using the multipart/form-data content type, and I got this question:

Shouldn't I escape CRLFs when I write the content of a file? I got a code piece on the web and I think it might be wrong:

NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: url];
[req setHTTPMethod: @"POST"];

NSString* contentType = @"multipart/form-data, boundary=AaB03x";
[req setValue:contentType forHTTPHeaderField: @"Content-type"];

NSData* boundary = [@"\r\n--AaB03x\r\n" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData: boundary];
[postBody appendData: [@"Content-Disposition: form-data; name=\"datafile\"; filename=\"t.jpg\"" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData: [@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData: imageData];
[postBody appendData: boundary];
[req setHTTPBody:postBody];

This is wrong because imageData might contain \r\n sequences, right? If so, is there a way to escape CRLFs in raw data? Or am I missing something?

Thanks in advance!


问:
if user is login to login page it comes error and it is not login
i am new to php coding

i created login page with user name and password,the login web page is showing, when i am entering user and password it's getting error,i find many ways but i did not find any solution, it's not working,

this is my error where i did mistake

this is login code

```<code><?php include('server.php');?>)
<!DOCTYPE html>
<html>
<head>
<title> user registration system using php</title>
<link rel ="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class ="header">
        <h2> login</h2>
    </div>
    <form method="post" action="login.php">
    <?php include('errors.php'); ?>
        <div class ="input-group">
            <label>Username</label>
            <input type = "text" name = "Username">
        </div>

        <div class ="input-group">
            <label>password</label>
            <input type = "text" name = "password">
        </div>
        <div class ="input-group">
            <button type ="submit" name ="register" class="btn">login</button>
            </div>
            <p>
                not yet a member? <a href="register.php">sign up</a>
            </p>
    </form>
    </body>
    </html>
</code>```

servercode :

```<code><?php
session_start();
$username = "";
$email = "";
$errors = array();
$db = mysqli_connect('localhost','root','','registration');
//print_r(!empty($_POST['registration']));exit;

if (empty($_POST['registration'])){

    $username = ($_POST['username']);
    $email = ($_POST['email']);
    $password = ($_POST['password']);
    //echo 'Hi';
if (empty($username)) {
    array_push($errors, "username is required");
}
if (empty($email)) {
    array_push($errors, "email is required");
}
if (empty($password)) {
    array_push($errors, "password is required");

}

if (count($errors) == 0) {

    $sql = "INSERT INTO users (username,email,password) VALUES('$username','$email','$password')";
mysqli_query($db,$sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "you are now logged in";
header('location: index.php');

}
}

if(isset($_POST['login'])) {
    $username = ($_POST['username']);

    $password = ($_POST['password']);
    //echo 'Hi';
if (empty($username)) {
    array_push($errors, "username is required");
}

if (empty($password)) {
    array_push($errors, "password is required");

}
if (count($errors)==0) {
    $query = "SELECT * FROM users where username = '$username' AND password ='$password'";
    $result = mysqli_query($db,$query);
    if(mysqli_num_rows($result) == 1) {

        $_SESSION['username'] = $username;
$_SESSION['success'] = "you are now logged in";
header('location: index.php');
}else{
    array_push($errors, "wrong username/password combination");
        header('location: login.php');
}
    }
}

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location: login.php');
}
?>
</code>```

答:
Check in Html form you given name as Username and at server side you fetching value with username. There are issue with caps and small letter.
remove caps of U in username in html form and replace with u.</p>

Body:
i am new to php coding

i created login page with user name and password,the login web page is showing, when i am entering user and password it's getting error,i find many ways but i did not find any solution, it's not working,

this is my error where i did mistake

this is login code

<?php include('server.php');?>)
<!DOCTYPE html>

<title> user registration system using php</title>
<link rel ="stylesheet" type="text/css" href="style.css">

 login

    <form method="post" action="login.php">
    <?php include('errors.php'); ?>

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

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

            <button type ="submit" name ="register" class="btn">login</button>

                not yet a member? sign up

    </form>

servercode :

<?php
session_start();
$username = "";
$email = "";
$errors = array();
$db = mysqli_connect('localhost','root','','registration');
//print_r(!empty($_POST['registration']));exit;

if (empty($_POST['registration'])){

    $username = ($_POST['username']);
    $email = ($_POST['email']);
    $password = ($_POST['password']);
    //echo 'Hi';
if (empty($username)) {
    array_push($errors, "username is required");
}
if (empty($email)) {
    array_push($errors, "email is required");
}
if (empty($password)) {
    array_push($errors, "password is required");

}

if (count($errors) == 0) {

    $sql = "INSERT INTO users (username,email,password) VALUES('$username','$email','$password')";
mysqli_query($db,$sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "you are now logged in";
header('location: index.php');

}
}

if(isset($_POST['login'])) {
    $username = ($_POST['username']);

    $password = ($_POST['password']);
    //echo 'Hi';
if (empty($username)) {
    array_push($errors, "username is required");
}

if (empty($password)) {
    array_push($errors, "password is required");

}
if (count($errors)==0) {
    $query = "SELECT * FROM users where username = '$username' AND password ='$password'";
    $result = mysqli_query($db,$query);
    if(mysqli_num_rows($result) == 1) {

        $_SESSION['username'] = $username;
$_SESSION['success'] = "you are now logged in";
header('location: index.php');
}else{
    array_push($errors, "wrong username/password combination");
        header('location: login.php');
}
    }
}

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location: login.php');
}
?>


问:
Animate objects in Swift?
In swift, I am transitioning an object in to the view, and I need it to slide in, or fade in. How can I obtain this type of animation in my program?

I have all my view elements made programmatically without IB (Interface Builder)

Is there documentation I can look at for reference? I could not find any.

答:
Swift 3 & 4
 Please Add necessary objects like tableView </p>

```<code>import UIKit

class SecondViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet var tabl: UITableView!
    var name = ["tony","abu"]
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSections(in tableView: UITableView) -> Int {
     return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return name.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = name[indexPath.row]
        return cell
    }
    override func viewWillAppear(_ animated: Bool) {

        tabl.center.x = self.view.frame.width/5

        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity:0.45, options: [], animations: ({
            self.tabl.center.x = self.view.frame.width/3
            //self.buttonAction.center.x = self.view.frame.width/2
        }), completion: nil)

    }

}
</code>```

Title: Animate objects in Swift?

Body:
Swift 3 & 4
 Please Add necessary objects like tableView

import UIKit

class SecondViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet var tabl: UITableView!
    var name = ["tony","abu"]
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSections(in tableView: UITableView) -> Int {
     return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return name.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = name[indexPath.row]
        return cell
    }
    override func viewWillAppear(_ animated: Bool) {

        tabl.center.x = self.view.frame.width/5

        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity:0.45, options: [], animations: ({
            self.tabl.center.x = self.view.frame.width/3
            //self.buttonAction.center.x = self.view.frame.width/2
        }), completion: nil)

    }

}


问:
Testing the results of executeBlocking
I have a vertx handler code where I do an executeBlocking but for it to work I need to put in a Thread.sleep() in order for the code in the blocking code to fully execute to the point that I can check the results.

Is there a better way around this so I don't do a Thread.sleep?

My handler code the following is the portion where I only kept the relevant components.

```<code>    try (final VertxHttpResponse response = new VertxHttpResponse(context)) {
        context.vertx().executeBlocking(
            future -> {
                ...
                try {
                    dispatcher.invokePropagateNotFound(request,
                        response);
                    future.complete();
                } finally {
                    ...
                }
            }, false,
            res -> {
                if (res.failed()) {
                    context.fail(wae);
                } else {
                    if (!context.response().ended()) {
                        context.response().end();
                    }
                }
            });
    } catch (final IOException e) {
        throw new UncheckedIOException(e);
    }
</code>```

}

My test and the relevant parts

```<code>@Test
public void test(final TestContext testContext) throws Exception {

    final Router router = Router.router(rule.vertx());
    final SpringJaxRsHandler handler = SpringJaxRsHandler.registerToRouter(router, MyApp.class);
    final RoutingContext routingContext = mock(RoutingContext.class);
    when(routingContext.currentRoute()).thenReturn(router.get("/api/hello"));
    when(routingContext.vertx()).thenReturn(rule.vertx());

    final HttpServerRequest serverRequest = mock(HttpServerRequest.class);
    when(serverRequest.absoluteURI()).thenReturn("/api/hello");
    when(serverRequest.isEnded()).thenReturn(true);
    when(serverRequest.method()).thenReturn(HttpMethod.GET);
    when(routingContext.request()).thenReturn(serverRequest);

    final HttpServerResponse response = mock(HttpServerResponse.class);
    when(response.putHeader(anyString(), anyString())).thenReturn(response);
    when(response.headers()).thenReturn(new VertxHttpHeaders());

    when(routingContext.response()).thenReturn(response);

    handler.handle(routingContext);
    Thread.sleep(1000);
    // fails without the sleep above
    verify(response, times(1)).setStatusCode(200);

}
</code>```

I tried

```<code>testContext.assertTrue(routingContext.response().ended());
</code>```

But that returned false.

答:
I refactored the code a bit so I don't use routingContext directly but the concept is still the same.  I use Async in combination of a when->then(Answer) and have the async.complete() be called in the Answer.  Once that is done do an async.await() to wait for the thread to finish.

```<code>    final Async async = testContext.async();
    when(response.write(Matchers.any(Buffer.class))).then(invocation -> {

        try {
            return response;
        } finally {
            async.complete();
        }
    });
    when(serverRequest.response()).thenReturn(response);

    router.accept(serverRequest);
    async.await();
</code>```

Title: Testing the results of executeBlocking

Body:
I have a vertx handler code where I do an executeBlocking but for it to work I need to put in a Thread.sleep() in order for the code in the blocking code to fully execute to the point that I can check the results.

Is there a better way around this so I don't do a Thread.sleep?

My handler code the following is the portion where I only kept the relevant components.

    try (final VertxHttpResponse response = new VertxHttpResponse(context)) {
        context.vertx().executeBlocking(
            future -> {
                ...
                try {
                    dispatcher.invokePropagateNotFound(request,
                        response);
                    future.complete();
                } finally {
                    ...
                }
            }, false,
            res -> {
                if (res.failed()) {
                    context.fail(wae);
                } else {
                    if (!context.response().ended()) {
                        context.response().end();
                    }
                }
            });
    } catch (final IOException e) {
        throw new UncheckedIOException(e);
    }

}

My test and the relevant parts

@Test
public void test(final TestContext testContext) throws Exception {

    final Router router = Router.router(rule.vertx());
    final SpringJaxRsHandler handler = SpringJaxRsHandler.registerToRouter(router, MyApp.class);
    final RoutingContext routingContext = mock(RoutingContext.class);
    when(routingContext.currentRoute()).thenReturn(router.get("/api/hello"));
    when(routingContext.vertx()).thenReturn(rule.vertx());

    final HttpServerRequest serverRequest = mock(HttpServerRequest.class);
    when(serverRequest.absoluteURI()).thenReturn("/api/hello");
    when(serverRequest.isEnded()).thenReturn(true);
    when(serverRequest.method()).thenReturn(HttpMethod.GET);
    when(routingContext.request()).thenReturn(serverRequest);

    final HttpServerResponse response = mock(HttpServerResponse.class);
    when(response.putHeader(anyString(), anyString())).thenReturn(response);
    when(response.headers()).thenReturn(new VertxHttpHeaders());

    when(routingContext.response()).thenReturn(response);

    handler.handle(routingContext);
    Thread.sleep(1000);
    // fails without the sleep above
    verify(response, times(1)).setStatusCode(200);

}

I tried

testContext.assertTrue(routingContext.response().ended());

But that returned false.

Body:
I refactored the code a bit so I don't use routingContext directly but the concept is still the same.  I use Async in combination of a when->then(Answer) and have the async.complete() be called in the Answer.  Once that is done do an async.await() to wait for the thread to finish.

    final Async async = testContext.async();
    when(response.write(Matchers.any(Buffer.class))).then(invocation -> {

        try {
            return response;
        } finally {
            async.complete();
        }
    });
    when(serverRequest.response()).thenReturn(response);

    router.accept(serverRequest);
    async.await();


问:
How to run jquery validate() while using form wizard?
I am using the jQuery Form Wizard 3.0.4 plugin for a multistep registration process. It uses the jQuery validator plugin built in, which is working fine when going from step to step. EDIT: This means I am already using validationEnabled: true, formOptions,  and validationOptions, and these are working. I need to run this same validation outside of the regular functionality.

The problem is that I need to run the validator and show errors manually at two points. For a special field I have, and before an AJAX submission. I've tried the following, which does nothing:

```<code>$("#registrationForm").validate();
</code>```

The form wizard script (jquery.form.wizard-3.0.4.js) appears to be doing this when going to the next step:

```<code>this.element.validate().focusInvalid();
</code>```

So I tried this, which also does nothing:

```<code>$("#registrationForm").element.validate().focusInvalid();
</code>```

Any ideas?

How do I run the same validation that occurs when I click next step?

How would I call a function that validates and shows errors for a specific field?

答:
Have you looked at the plugin's documentation? There's a simple switch in the setup that will enable you to do that kind of validation when you're defining your form wizard.

http://thecodemine.org/#_demoForm=first

Then click on "Options" and look at the 'validationEnabled' to enable validation and then look at 'validationOptions' to setup your options.

Body:
I am using the jQuery Form Wizard 3.0.4 plugin for a multistep registration process. It uses the jQuery validator plugin built in, which is working fine when going from step to step. EDIT: This means I am already using validationEnabled: true, formOptions,  and validationOptions, and these are working. I need to run this same validation outside of the regular functionality.

The problem is that I need to run the validator and show errors manually at two points. For a special field I have, and before an AJAX submission. I've tried the following, which does nothing:

$("#registrationForm").validate();

The form wizard script (jquery.form.wizard-3.0.4.js) appears to be doing this when going to the next step:

this.element.validate().focusInvalid();

So I tried this, which also does nothing:

$("#registrationForm").element.validate().focusInvalid();

Any ideas?

How do I run the same validation that occurs when I click next step?

How would I call a function that validates and shows errors for a specific field?


问:
Node js App stoping When Console is closed
Am new to node , created my first express based app and deployed in my development server.

```<code>node app.js
</code>```

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.

答: That's because your session will be terminated. All you need is a session handler. It depends on your OS. You can use screenrc on linux -> https://wiki.ubuntuusers.de/Screen/.</p>

Body:
Am new to node , created my first express based app and deployed in my development server.

node app.js

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.


问:
Retrive records of a table with out related tables' records by Entity Framework?
When I get records of a table by EF such as

```<code>db.cities.Tolist();
</code>```

returns all records of the City table and related tables records but I want get city table records only .

Is this possible?

答:
Entity Framework supports 3 ways to load related data - eager loading, lazy loading and explicit loading.

In your case, you can either go for lazy loading or explicit loading.

Lazy Loading is enabled by default, so until you access a related property it's data won't be fetched from the database.

Explicit loading, first you need to disable Lazy loading:

```<code>public class DatabaseContext : DbContext
{
    public DatabaseContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}
</code>```

Then you can load related entities using Load().

```<code>var city = context.cities.FirstOrDefault();
context.Entry(city).Reference(p => p.Buildings).Load();
</code>```

Assuming cities table refers to Buildings table.

Body:
When I get records of a table by EF such as

db.cities.Tolist();

returns all records of the City table and related tables records but I want get city table records only .

Is this possible?

Body:
Entity Framework supports 3 ways to load related data - eager loading, lazy loading and explicit loading.

In your case, you can either go for lazy loading or explicit loading.

Lazy Loading is enabled by default, so until you access a related property it's data won't be fetched from the database.

Explicit loading, first you need to disable Lazy loading:

public class DatabaseContext : DbContext
{
    public DatabaseContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}

Then you can load related entities using Load().

var city = context.cities.FirstOrDefault();
context.Entry(city).Reference(p => p.Buildings).Load();

Assuming cities table refers to Buildings table.


问:
Android Wear: BleLEScan is draining my battery
I am developing an app which needs data from the wear.

One of the type of data is BLE.

I am using BleLeScan:

```<code>BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
    if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .build();
                filters = new ArrayList<ScanFilter>();
            }

mLEScanner.startScan(filters, settings, mScanCallback);
</code>```

BLELeScan is draining my wear's battery. I know this because i tested with BLE scan and without it. The difference is huge, without BLE scan battery consumption per hour is about 3%, whereas with BLE scan it is >16%.

How can I optimize battery consumtion for BLELeScan? I need to run the scan continuously.

答:
Apparently, as pointed out in answers and comments, BLE scan consumes a lot of battery power. How much does it consumes? It will depend on the device.

I optimized battery consumption of the application by running the scan for 12sec/min and then stopping the scan for next 48sec. After 48sec I am restarting the scan.

Note, I am not making any supporting object null, I am just stopping the scan after 12sec.

This approach helped me save battery consumption by more than 50%.

Body:
I am developing an app which needs data from the wear.

One of the type of data is BLE.

I am using BleLeScan:

BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
    if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .build();
                filters = new ArrayList<ScanFilter>();
            }

mLEScanner.startScan(filters, settings, mScanCallback);

BLELeScan is draining my wear's battery. I know this because i tested with BLE scan and without it. The difference is huge, without BLE scan battery consumption per hour is about 3%, whereas with BLE scan it is >16%.

How can I optimize battery consumtion for BLELeScan? I need to run the scan continuously.


问:
How to host a site in Azure? I can't figure out how to hook it up to my domain
I am using azure and have created a Windows 2016 server VM(not the classic mode). I have installed iis and opened up port 80. I can hit my ip and get the IIS page.

Now I am trying to host one of my very simple sites(per html page, with js/bootstrap).

I put it in IIS and set to an ip address(this was given to me as an option) instead of unassigned and left port 80.

I then went to namecheap and put my public ip from azure as my A record and in Azure I created a DNS Name and used that as the CNAME (for * and www) but I still get "not found" when I got to the domain name.

答:
I did a test in my lab and I could browse the Website from my Azure with my own domain. Steps are below:

After add IIS feature in my VM, I opened 80 port in the NSG;

2. Configure a DNS name and static IP for the VM:

Add A records in my Domain provider:

4.Just wait a moment, I can browse it from my own domian:

Hope this helps!


问:
I get a 400 Bad Request error while using django-piston
I am trying to use Piston to provide REST support to Django.
I have implemented my handlers as per the documentation provided .
The problem is that i can "read" and "delete" my resource but i cannot "create" or "update".
Each time i hit the relevant api i get a 400 Bad request Error.

I have extended the Resource class for csrf by using this commonly available code snippet:

```<code>class CsrfExemptResource(Resource):
    """A Custom Resource that is csrf exempt"""
    def __init__(self, handler, authentication=None):
        super(CsrfExemptResource, self).__init__(handler, authentication)
        self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)
</code>```

My class (code snippet) looks like this:

```<code>user_resource = CsrfExemptResource(User)

class User(BaseHandler):
    allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')

    @require_extended
    def create(self, request):
        email = request.GET['email']
        password = request.GET['password']
        phoneNumber = request.GET['phoneNumber']
        firstName = request.GET['firstName']
        lastName = request.GET['lastName']
        self.createNewUser(self, email,password,phoneNumber,firstName,lastName)
        return rc.CREATED
</code>```

Please let me know how can i get the create method to work using the POST operation?

答:
In utils.py, change this.

```<code>def content_type(self):
    """
    Returns the content type of the request in all cases where it is
    different than a submitted form - application/x-www-form-urlencoded
    """
    type_formencoded = "application/x-www-form-urlencoded"

    ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)

    if ctype.strip().lower().find(type_formencoded) >= 0:
        return None

    return ctype
</code>```

https://bitbucket.org/jespern/django-piston/issue/87/split-charset-encoding-form-content-type

Body:
I am trying to use Piston to provide REST support to Django.
I have implemented my handlers as per the documentation provided .
The problem is that i can "read" and "delete" my resource but i cannot "create" or "update".
Each time i hit the relevant api i get a 400 Bad request Error.

I have extended the Resource class for csrf by using this commonly available code snippet:

class CsrfExemptResource(Resource):
    """A Custom Resource that is csrf exempt"""
    def __init__(self, handler, authentication=None):
        super(CsrfExemptResource, self).__init__(handler, authentication)
        self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)

My class (code snippet) looks like this:

user_resource = CsrfExemptResource(User)

class User(BaseHandler):
    allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')

    @require_extended
    def create(self, request):
        email = request.GET['email']
        password = request.GET['password']
        phoneNumber = request.GET['phoneNumber']
        firstName = request.GET['firstName']
        lastName = request.GET['lastName']
        self.createNewUser(self, email,password,phoneNumber,firstName,lastName)
        return rc.CREATED

Please let me know how can i get the create method to work using the POST operation?

Body:
In utils.py, change this.

def content_type(self):
    """
    Returns the content type of the request in all cases where it is
    different than a submitted form - application/x-www-form-urlencoded
    """
    type_formencoded = "application/x-www-form-urlencoded"

    ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)

    if ctype.strip().lower().find(type_formencoded) >= 0:
        return None

    return ctype

https://bitbucket.org/jespern/django-piston/issue/87/split-charset-encoding-form-content-type


问:
How to add button for each row using for loop in datatables by ajax and jquery
i want to add buttons for each row using ajax function...I code something but is not work well.. Buttons move out of the table and view all buttons in the bottom if the page.I want to add these buttons to datatables row...

I want to add abc buttons one by one to [object Object] feild using for loop

ajax and jquery cord

```<code><script>
        $(document).ready(function () {
            $("#searchArea").hide();
            var uID = $("#userName").val();

            var tableProduct = $('#dataTbl').DataTable({
                "bSort": true
                , "oLanguage": {"sZeroRecords": "", "sEmptyTable": ""}
            });
            $.ajax({
                type: 'GET',
                url: '${pageContext.request.contextPath}/restservice/App50/' + uID,
                success: function (result) {
                    var jString = JSON.stringify(result);
                    var jdata = JSON.parse(jString);

                    for (var x = 0; x < jdata.length; x++) {
                        var pa = $('#aaa');
                        var td1 = jdata[x].snumber;
                        var td2 = jdata[x].date;
                        var td3 = jdata[x].slsNo + " in " + jdata[x].slsiUnit;
                        var td4 = jdata[x].productDesc;
                        var td5 = jdata[x].status;
                        var td6 = pa.append('<input type="button" class="btn btn-success" value="abc">');
                        var td7 = "jdata[x].hsCode";
                        var td8 = "jdata[x].hsCode";
                        tableProduct.row.add([td1, td2, td3, td4, td5, td6, td7, td8]).draw(true);
                    }
                }

            });

        });
    </script>
</code>```

jsp cord

```<code><body>
        <div id="bootstrapCssTest" class="hidden"></div>
        <div id="bootstrapCssTest" class="hidden"></div>

        <div class="container">
            <div class="row headerRow1">
                <div class="col-md-12">
                    <jsp:include page="template/banner.jsp"/>
                </div>
            </div>
            <div class="row">
                <div class="authheader">
                    <%@include file="template/message.jsp" %>
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
                    <jsp:include page="template/header.jsp"/>
                </div>
                <div class="col-xs-12 col-sm-8 col-md-9 col-lg-9">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="well lead">List of Applications</div>
                        </div>
                    </div>
                    <div class="row">
                        <input type="hidden" id="userName" value="${userID}"/>
                        <input type="hidden" id="recentView" value="1"/>
                        <div class="panel panel-default">

                            <div id="ribbon">Search - <p id="viewSearchCategory" style="display: inline-block" >View Recent 50 Applications</p></div>
                            <div id="searchArea" class="well ">
                                <div class="row">
                                    VIEW RECENT
                                    <select id="viewNumbers" name="viewNumbers">
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                        <option value="150">150</option>
                                        <option value="200">200</option>
                                        <option value="500">500</option>
                                        <option value="750">750</option>
                                        <option value="1000">1000</option>
                                    </select>
                                    APPLICATIONS
                                </div>
                            </div>
                            <!-- Default panel contents -->
                            <div style="overflow-x:auto;">
                                <table id="dataTbl" class="table table-bordered table-hover" style="font-size:13px;">
                                    <thead>
                                        <tr>
                                            <th width="10%">SLSI Entry No</th>
                                            <th width="10%">Application Posted in</th>
                                            <th width="30%">SLS No and Unit</th>
                                            <th width="30%">Product Description</th>
                                            <th width="10%">Status</th>
                                            <th class="hidden-print"></th>
                                            <th class="hidden-print"></th>
                                            <th class="hidden-print"></th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                            <p id="aaa"></p>
                        </div>
                    </div>
                </div>
            </div> <jsp:include page="template/footer.jsp"/></div>
    </body>
</code>```

help me someone

答:
The problem in your code is. You append the button to $("#aaa"), which is outside of table.

Change this line

```<code>var td6 = pa.append('<input type="button" class="btn btn-success" value="abc">');
</code>```

To

```<code>var td6 = '<input type="button" class="btn btn-success" value="abc">';
</code>```

And this is some jsfiddle example based on your code : https://jsfiddle.net/synz/zLykna0p/

Body:
i want to add buttons for each row using ajax function...I code something but is not work well.. Buttons move out of the table and view all buttons in the bottom if the page.I want to add these buttons to datatables row...

I want to add abc buttons one by one to [object Object] feild using for loop

ajax and jquery cord

jsp cord

                    <jsp:include page="template/banner.jsp"/>

                    <%@include file="template/message.jsp" %>

                    <jsp:include page="template/header.jsp"/>

List of Applications

                        <input type="hidden" id="userName" value="${userID}"/>
                        <input type="hidden" id="recentView" value="1"/>

Search -
View Recent 50 Applications

                                    VIEW RECENT
                                    <select id="viewNumbers" name="viewNumbers">
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                        <option value="150">150</option>
                                        <option value="200">200</option>
                                        <option value="500">500</option>
                                        <option value="750">750</option>
                                        <option value="1000">1000</option>
                                    </select>
                                    APPLICATIONS

                                            SLSI Entry No
                                            Application Posted in
                                            SLS No and Unit
                                            Product Description
                                            Status

 <jsp:include page="template/footer.jsp"/>

help me someone

Body:
The problem in your code is. You append the button to $("#aaa"), which is outside of table.

Change this line

var td6 = pa.append('<input type="button" class="btn btn-success" value="abc">');

To

var td6 = '<input type="button" class="btn btn-success" value="abc">';

And this is some jsfiddle example based on your code : https://jsfiddle.net/synz/zLykna0p/


答:
The best way to add button is to prepare the button html in the API level at the last field: '${pageContext.request.contextPath}/restservice/App50/' + uID
so that when the datatable does not need to manipulate the returned data from javascript.</p>

Title: How to add button for each row using for loop in datatables by ajax and jquery