问:
Change multiple button text when onclick
I have attempted to toggle the button text once it's onclick here. I have use different ID for another button but it doesn't seem to work.
How do I use the same function for multiple buttons?

  function buttonToggle() {
                var change = document.getElementById("btnAdd");
                if (change.innerHTML == "ADD")
                {
                    change.innerHTML = "ADDED"
                }
                else {
                    change.innerHTML = "ADD"
                }
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">
    <link rel="stylesheet" href="../../css/activity-registration.css">

       <!-- jQuery first, then Tether, then Bootstrap JS. -->
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <div class="col">
      <button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle()">
     <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
       </button>
        </div>

<br>
<br>

<div class="col">
   <button type="button" class="btn btn-primary btn-lg" id="btnAdd3" onclick="buttonToggle()">
       <span><i class="fa fa-plus" aria-hidden="true"></i></span> <b>ADD</b>
    </button>
       </div></code>```

答:
Pass parameter in you toggle function

```<code> function buttonToggle(ButtonID) {
            var change = document.getElementById(ButtonID);
            if (change.innerHTML == "ADD")
            {
                change.innerHTML = "ADDED"
            }
            else {
                change.innerHTML = "ADD"
            }
        }
</code>```

And call it like

For button one :

```<code><button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle('btnAdd')">
</code>```

For button two :

```<code><button type="button" class="btn btn-primary btn-lg" id="btnAdd2" onclick="buttonToggle('btnAdd2')">
</code>```

function buttonToggle(ButtonID) {
            var change = document.getElementById(ButtonID);
            if (change.innerHTML == "ADD")
            {
                change.innerHTML = "ADDED"
            }
            else {
                change.innerHTML = "ADD"
            }
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">
    <link rel="stylesheet" href="../../css/activity-registration.css">

       <!-- jQuery first, then Tether, then Bootstrap JS. -->
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <div class="col">
      <button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle('btnAdd')">
     <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
       </button>
        </div>

<br>
<br>

<div class="col">
   <button type="button" class="btn btn-primary btn-lg" id="btnAdd2" onclick="buttonToggle('btnAdd2')">
       <span><i class="fa fa-plus" aria-hidden="true"></i></span> <b>ADD</b>
    </button>
       </div></code>```

Body:
I have attempted to toggle the button text once it's onclick here. I have use different ID for another button but it doesn't seem to work.
How do I use the same function for multiple buttons?

  function buttonToggle() {
                var change = document.getElementById("btnAdd");
                if (change.innerHTML == "ADD")
                {
                    change.innerHTML = "ADDED"
                }
                else {
                    change.innerHTML = "ADD"
                }
            }

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">
    <link rel="stylesheet" href="../../css/activity-registration.css">

      <button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle()">
      ADD
       </button>

   <button type="button" class="btn btn-primary btn-lg" id="btnAdd3" onclick="buttonToggle()">
        ADD
    </button>

Body:
Pass parameter in you toggle function

 function buttonToggle(ButtonID) {
            var change = document.getElementById(ButtonID);
            if (change.innerHTML == "ADD")
            {
                change.innerHTML = "ADDED"
            }
            else {
                change.innerHTML = "ADD"
            }
        }

And call it like

For button one :

<button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle('btnAdd')">

For button two :

<button type="button" class="btn btn-primary btn-lg" id="btnAdd2" onclick="buttonToggle('btnAdd2')">

function buttonToggle(ButtonID) {
            var change = document.getElementById(ButtonID);
            if (change.innerHTML == "ADD")
            {
                change.innerHTML = "ADDED"
            }
            else {
                change.innerHTML = "ADD"
            }
        }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">
    <link rel="stylesheet" href="../../css/activity-registration.css">

       <!-- jQuery first, then Tether, then Bootstrap JS. -->
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <div class="col">
      <button type="button" class="btn btn-primary btn-lg" id="btnAdd" onclick="buttonToggle('btnAdd')">
     <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
       </button>
        </div>

<br>
<br>

<div class="col">
   <button type="button" class="btn btn-primary btn-lg" id="btnAdd2" onclick="buttonToggle('btnAdd2')">
       <span><i class="fa fa-plus" aria-hidden="true"></i></span> <b>ADD</b>
    </button>
       </div>


来源: stackexchange

问:
Vue.js dynamic
```

答:
CSS
```
<p>Note: Only the latest browsers support <em>CSS variables</em>.</p>
<p>If you still see any issues with the <code>:style</code> in the template then try this,</p>
```

```

ContentLicense: CC BY-SA 4.0

Title: Vue.js dynamic <style> with variables

Body:
Is it possible to add the dynamic variable in style?

I mean something like:

Body:
CSS <style> is static. I don't think you can do that... you might have to look for a different approach.

You can try using CSS variables. For example, (the code below is not tested)

<template>
    <div class="class_name" :style="{'--bkgImage': 'url(' + project.background + ')', '--bkgImageMobile': 'url(' + project.backgroundRetina + ')'}">
    </div>
</template>

<style>
    .class_name{
        background-image: var(--bkgImage);
    }
    @media all and (-webkit-min-device-pixel-ratio : 1.5),
        all and (-o-min-device-pixel-ratio: 3/2),
        all and (min--moz-device-pixel-ratio: 1.5),
        all and (min-device-pixel-ratio: 1.5) {
            .class_name {
                background-image: var(--bkgImageMobile);
            }
        }
</style>

Note: Only the latest browsers support CSS variables.

If you still see any issues with the :style in the template then try this,

<div :style="'--bkgImage: url(' + project.background + '); --bkgImageMobile: url(' + project.backgroundRetina + ')'">
</div>


问:
how to re-arrange divs
```<code><div class="row">
  <div class="pimage clr">
    <img src="./images/portfolio/1.jpg" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">Onet</div>
    </div>
  </div>
  <div class="pvideo">
    <img src="./images/portfolio/2.jpg" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">two</div>
    </div>
  </div>
  <div class="pimage">
    <img src="./images/portfolio/3.jpg" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">three</div>
    </div>
  </div>
</div>
</div>
</code>```

in larger display  i want this to display in the same order, but for tablet i want to display one and three together and two below them.

答:
Usually element written in the fashion in html appears in the same order. So if you want to change the order of elements , you can either use duplicates and hide the one not requried.

```<code>    <div class="row">
      <div class="pimage clr">
        <img src="./images/portfolio/1.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">Onet</div>
        </div>
      </div>
      <div class="pvideo hide-sm">
        <img src="./images/portfolio/2.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">two</div>
        </div>
      </div>
      <div class="pimage">
        <img src="./images/portfolio/3.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">three</div>
        </div>
      </div>
     <div class="pvideo hidden show-sm">
        <img src="./images/portfolio/2.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">two</div>
        </div>
      </div>
    </div>
</code>```

`

Add this style to hide/show when the screen size changes

```<code>    <style>
        .hidden{
    visibility:hidden;
    }
//change the max-width accordingly

    @media(max-width:400px){
        .show-xs{
        visibility:visible;
        }
    .hide-sm{
        visibility:hidden;
        }
    }
    .hidden{
       visibility:hidden;
    }
    </style>
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to re-arrange divs

Body:
Onet

two

three

in larger display  i want this to display in the same order, but for tablet i want to display one and three together and two below them.

Body:
Usually element written in the fashion in html appears in the same order. So if you want to change the order of elements , you can either use duplicates and hide the one not requried.

    <div class="row">
      <div class="pimage clr">
        <img src="./images/portfolio/1.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">Onet</div>
        </div>
      </div>
      <div class="pvideo hide-sm">
        <img src="./images/portfolio/2.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">two</div>
        </div>
      </div>
      <div class="pimage">
        <img src="./images/portfolio/3.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">three</div>
        </div>
      </div>
     <div class="pvideo hidden show-sm">
        <img src="./images/portfolio/2.jpg" alt="Avatar" class="image" style="width:100%">
        <div class="middle">
          <div class="text">two</div>
        </div>
      </div>
    </div>

`

Add this style to hide/show when the screen size changes

    <style>
        .hidden{
    visibility:hidden;
    }
//change the max-width accordingly

    @media(max-width:400px){
        .show-xs{
        visibility:visible;
        }
    .hide-sm{
        visibility:hidden;
        }
    }
    .hidden{
       visibility:hidden;
    }
    </style>


问:
Recyclerview inside Nested Scrollview scroll but does not fast scroll like normal Recyclerview or Nested Scrollview
I am using RecyclerView inside NestedScrollView and it works. But when I use RecyclerView inside LinearLayout or something, it scroll in various speed depending on gesture. The scroll listen to gesture and if I slide up only a bit, then it scroll a little bit while if I slide up really fast, then it scroll really fast. Now my problem is that RecyclerView inside NestedScrollView certainly scroll but fast scroll does not work. However I slide up fast or slow, RecyclerView or NestedScrollView only scroll a little bit.

How can I make my NestedScrollView or RecyclerView inside that scroll view scroll in various speed?

答:
```<code>recyclerView.setNestedScrollingEnabled(false);
</code>```

Will be useful sometimes.But it is not advisable for all the times.because it disables view recycling feature in recylcer view.

Alternatives:

Try CollapsiveToolbarLayout with Recycler view.
put other views in collapsiveTollbar layout.

Body:
recyclerView.setNestedScrollingEnabled(false);

Will be useful sometimes.But it is not advisable for all the times.because it disables view recycling feature in recylcer view.

Alternatives:

Try CollapsiveToolbarLayout with Recycler view.
put other views in collapsiveTollbar layout.


问:
Oracle Function Select * from Query Not giving any Results
The following is the function definition I am using:

```<code>CREATE OR REPLACE FUNCTION MA_FACTSET.totalCustomers
RETURN number as
    total INTEGER := 0;
    FID VARCHAR2(30) := 'NT33H0-S-US';
    stmt varchar2(1000);

BEGIN
    execute immediate 'TRUNCATE TABLE MovingAverage';
    execute immediate 'DROP TABLE MovingAverage';
    execute immediate 'CREATE GLOBAL TEMPORARY TABLE MovingAverage
    (ID INTEGER,
     PDATE DATE,
     PPRICE FLOAT,
     MA1 FLOAT) ON COMMIT PRESERVE ROWS';

    stmt := 'INSERT INTO  MovingAverage (ID,PDATE,PPRICE) SELECT
    ROWNUM,"DATE",P_PRICE FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = ''NT33H0-S-US''';
    DBMS_OUTPUT.PUT_LINE(stmt);
    execute immediate stmt;
    dbms_output.put_line(SQL%ROWCOUNT);
    commit;

    execute immediate 'UPDATE  MovingAverage A SET MA1 =(SELECT AVG(PPRICE)
    FROM MovingAverage WHERE ID>=A.ID-5 AND ID<A.ID )' ;
    dbms_output.put_line(SQL%ROWCOUNT);
    commit;

    execute immediate 'SELECT * FROM MovingAverage ORDER BY ID ASC';
    dbms_output.put_line(SQL%ROWCOUNT);
    commit;

    dbms_output.put_line(total);
    RETURN total;
END;
/
</code>```

I have applied some checks to see whether the function is running properly or not, like getting SQL%ROWCOUNT.

The following is the DBMS output of the function:

```<code>INSERT INTO  MovingAverage (ID,PDATE,PPRICE) SELECT ROWNUM,"DATE",P_PRICE     FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = 'NT33H0-S-US'
4114
4114
0
0
</code>```

I want know why rowcount of "SELECT * FROM MovingAverage ORDER BY ID ASC" is 0. And if there is any way to print complete table in Data Grid. I am using TOAD for Oracle.

答:
I suggest you to rewrite your function removing dynamic sqls where not necessary. Also, If you have DDLs, DMLs don't use PL/SQL function, rather use procedure.

For select Statements in EXECUTE IMMEDIATE, it will work if you use BULK COLLECT INTO

```<code>CREATE OR REPLACE FUNCTION totalCustomers
   RETURN NUMBER
AS
   total   INTEGER := 0;
   FID     VARCHAR2 (30) := 'NT33H0-S-US';
   stmt    VARCHAR2 (1000);

   TYPE mrectype IS TABLE OF MovingAverage%ROWTYPE;

   mrec    mrectype;
BEGIN
   EXECUTE IMMEDIATE 'TRUNCATE TABLE MovingAverage';

   EXECUTE IMMEDIATE 'DROP TABLE MovingAverage';

   EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE MovingAverage
(ID INTEGER,
 PDATE DATE,
 PPRICE FLOAT,
 MA1 FLOAT) ON COMMIT PRESERVE ROWS';

   stmt :=
      'INSERT INTO  MovingAverage (ID,PDATE,PPRICE) SELECT
ROWNUM,"DATE",P_PRICE FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = ''NT33H0-S-US''';
   DBMS_OUTPUT.PUT_LINE (stmt);

   EXECUTE IMMEDIATE stmt;

   DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
   COMMIT;

   EXECUTE IMMEDIATE 'UPDATE  MovingAverage A SET MA1 =(SELECT AVG(PPRICE)
FROM MovingAverage WHERE ID>=A.ID-5 AND ID<A.ID )';

   DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
   COMMIT;

   EXECUTE IMMEDIATE 'SELECT * FROM MovingAverage ORDER BY ID ASC'
      BULK COLLECT INTO mrec;

   DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
   COMMIT;
   DBMS_OUTPUT.put_line (total);
   RETURN total;
END;
/
</code>```

Call this function like this.

```<code>SET SERVEROUTPUT ON
DECLARE
x NUMBER;
BEGIN
x := totalCustomers;
END;
/
</code>```

You cannot call the function in SQL select

Body:
The following is the function definition I am using:

CREATE OR REPLACE FUNCTION MA_FACTSET.totalCustomers
RETURN number as
    total INTEGER := 0;
    FID VARCHAR2(30) := 'NT33H0-S-US';
    stmt varchar2(1000);

BEGIN
    execute immediate 'TRUNCATE TABLE MovingAverage';
    execute immediate 'DROP TABLE MovingAverage';
    execute immediate 'CREATE GLOBAL TEMPORARY TABLE MovingAverage
    (ID INTEGER,
     PDATE DATE,
     PPRICE FLOAT,
     MA1 FLOAT) ON COMMIT PRESERVE ROWS';

    stmt := 'INSERT INTO  MovingAverage (ID,PDATE,PPRICE) SELECT
    ROWNUM,"DATE",P_PRICE FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = ''NT33H0-S-US''';
    DBMS_OUTPUT.PUT_LINE(stmt);
    execute immediate stmt;
    dbms_output.put_line(SQL%ROWCOUNT);
    commit;

    execute immediate 'UPDATE  MovingAverage A SET MA1 =(SELECT AVG(PPRICE)
    FROM MovingAverage WHERE ID>=A.ID-5 AND ID<A.ID )' ;
    dbms_output.put_line(SQL%ROWCOUNT);
    commit;

    execute immediate 'SELECT * FROM MovingAverage ORDER BY ID ASC';
    dbms_output.put_line(SQL%ROWCOUNT);
    commit;

    dbms_output.put_line(total);
    RETURN total;
END;
/

I have applied some checks to see whether the function is running properly or not, like getting SQL%ROWCOUNT.

The following is the DBMS output of the function:

INSERT INTO  MovingAverage (ID,PDATE,PPRICE) SELECT ROWNUM,"DATE",P_PRICE     FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = 'NT33H0-S-US'
4114
4114
0
0

I want know why rowcount of "SELECT * FROM MovingAverage ORDER BY ID ASC" is 0. And if there is any way to print complete table in Data Grid. I am using TOAD for Oracle.

Body:
I suggest you to rewrite your function removing dynamic sqls where not necessary. Also, If you have DDLs, DMLs don't use PL/SQL function, rather use procedure.

For select Statements in EXECUTE IMMEDIATE, it will work if you use BULK COLLECT INTO

CREATE OR REPLACE FUNCTION totalCustomers
   RETURN NUMBER
AS
   total   INTEGER := 0;
   FID     VARCHAR2 (30) := 'NT33H0-S-US';
   stmt    VARCHAR2 (1000);

   TYPE mrectype IS TABLE OF MovingAverage%ROWTYPE;

   mrec    mrectype;
BEGIN
   EXECUTE IMMEDIATE 'TRUNCATE TABLE MovingAverage';

   EXECUTE IMMEDIATE 'DROP TABLE MovingAverage';

   EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE MovingAverage
(ID INTEGER,
 PDATE DATE,
 PPRICE FLOAT,
 MA1 FLOAT) ON COMMIT PRESERVE ROWS';

   stmt :=
      'INSERT INTO  MovingAverage (ID,PDATE,PPRICE) SELECT
ROWNUM,"DATE",P_PRICE FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = ''NT33H0-S-US''';
   DBMS_OUTPUT.PUT_LINE (stmt);

   EXECUTE IMMEDIATE stmt;

   DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
   COMMIT;

   EXECUTE IMMEDIATE 'UPDATE  MovingAverage A SET MA1 =(SELECT AVG(PPRICE)
FROM MovingAverage WHERE ID>=A.ID-5 AND ID<A.ID )';

   DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
   COMMIT;

   EXECUTE IMMEDIATE 'SELECT * FROM MovingAverage ORDER BY ID ASC'
      BULK COLLECT INTO mrec;

   DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
   COMMIT;
   DBMS_OUTPUT.put_line (total);
   RETURN total;
END;
/

Call this function like this.

SET SERVEROUTPUT ON
DECLARE
x NUMBER;
BEGIN
x := totalCustomers;
END;
/

You cannot call the function in SQL select


问:
How to find xpath without firepath into firefox version 57.0
Facing difficulty to find xpath without firepath in new Firefox version 57.0.

In the new Firefox version, firepath is not supported.

Can anyone please suggest a new way for using xpath?

答:
Step 1: Right click on the web page and click on Inspect Element or Ctrl+Shift+Q
How to inspect element

Step 2: Click on inspector Inspector image

Step 3: Verify in console


问:
Uncaught TypeError in Chrome and Not a Function in FireFox
I want to set the variable zoom as the map.GetZoom() but I have been getting the following error in both Chrome and Firefox:

Chrome

Uncaught TypeError: Object # has no method 'getZoom'

Firefox

gmap.getZoom is not a function

zoom = gmap.getZoom();

First question What error did I make in my codes?

default.js

```<code>window.gmap = {
 zoom_Changed: function() {

 zoom = gmap.getZoom();

 if(zoom > 15) {
  document.write("hello");
 } else {
 }
 }
};
</code>```

Edit: Gmap is defined in my views.py and the zoom_Changed function is for the event listener in my views.py.

views.py

```<code>maps.event.addListener(gmap, 'zoom_changed', 'gmap.zoom_Changed');
</code>```

答: Instead of zoom = gmap.getZoom();, it should be zoom = this.getZoom();.

Body:
I want to set the variable zoom as the map.GetZoom() but I have been getting the following error in both Chrome and Firefox:

Chrome

Uncaught TypeError: Object # has no method 'getZoom'

Firefox

gmap.getZoom is not a function

zoom = gmap.getZoom();

First question What error did I make in my codes?

default.js

window.gmap = {
 zoom_Changed: function() {

 zoom = gmap.getZoom();

 if(zoom > 15) {
  document.write("hello");
 } else {
 }
 }
};

Edit: Gmap is defined in my views.py and the zoom_Changed function is for the event listener in my views.py.

views.py

maps.event.addListener(gmap, 'zoom_changed', 'gmap.zoom_Changed');

ContentLicense: CC BY-SA 2.5


问:
Unable to merge 2 JSON results and get response from a PHP script
I am trying to fetch a result from my select statement, I am using 2 statements and want a JDON response of the 2 outputs. That's all.

Problem: I am testing from Chrome Postman, it is showing result

```<code>[
null,
null
]
</code>```

Below is my php code; where am I going wrong?

```<code><?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
    header('Cache-Control: max-age=900');
    header("Content-Type: application/json"); // tell client that we are sending json data

    define("DB_USR","erSKJV");
    define("DB_PsAS","T");
    define("DB","ipaddress/orcl.profits");
    $conn = oci_connect(DB_USR,DB_PAS,DB);

    if (!$conn)
    {
        $e = oci_error();
        $result["message"] = $e['message'];
        echo json_encode($result);
        exit(1);
    }

        $loggedinuser = $_POST['loggedinuser'];

        $stmt = "select count(*) as taskgiven from admtask where CLOSE_DT is null and primary='".$loggedinuser."' ";

        $stmt1 = "select count(*) as mytask from admtask where CLOSE_DT is null and entusr='".$loggedinuser."' ";

        $result=oci_parse($conn,$stmt);
        $ex2=oci_execute($result);

        while ($row=oci_fetch_assoc($result))
        {
          $stmta[] = $row;
        }
         json_encode($stmta);

        $result1=oci_parse($conn,$stmt1);
        $ex2=oci_execute($result1);

        while ($row1=oci_fetch_assoc($result1))
        {
          $stmtb[] = $row1;
        }
         json_encode($stmtb);

        $final[] = json_decode($stmta,true);
        $final[] = json_decode($stmtb,true);
        $json_merge = json_encode($final);

        echo json_encode($json_merge);

?>
</code>```

You need to concentrate on stmta , stmtb and finally json_merge

答:
json_encode returns the string for the json. You need to assign that to a variable during the first two encodings.</p>

```<code>while ($row=oci_fetch_assoc($result))
    {
      $stmta[] = $row;
    }
    $stmta =  json_encode($stmta);

    $result1=oci_parse($conn,$stmt1);
    $ex2=oci_execute($result1);

    while ($row1=oci_fetch_assoc($result1))
    {
      $stmtb[] = $row1;
    }
     $stmtb = json_encode($stmtb);
</code>```

Body:
I am trying to fetch a result from my select statement, I am using 2 statements and want a JDON response of the 2 outputs. That's all.

Problem: I am testing from Chrome Postman, it is showing result

[
null,
null
]

Below is my php code; where am I going wrong?

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
    header('Cache-Control: max-age=900');
    header("Content-Type: application/json"); // tell client that we are sending json data

    define("DB_USR","erSKJV");
    define("DB_PsAS","T");
    define("DB","ipaddress/orcl.profits");
    $conn = oci_connect(DB_USR,DB_PAS,DB);

    if (!$conn)
    {
        $e = oci_error();
        $result["message"] = $e['message'];
        echo json_encode($result);
        exit(1);
    }

        $loggedinuser = $_POST['loggedinuser'];

        $stmt = "select count(*) as taskgiven from admtask where CLOSE_DT is null and primary='".$loggedinuser."' ";

        $stmt1 = "select count(*) as mytask from admtask where CLOSE_DT is null and entusr='".$loggedinuser."' ";

        $result=oci_parse($conn,$stmt);
        $ex2=oci_execute($result);

        while ($row=oci_fetch_assoc($result))
        {
          $stmta[] = $row;
        }
         json_encode($stmta);

        $result1=oci_parse($conn,$stmt1);
        $ex2=oci_execute($result1);

        while ($row1=oci_fetch_assoc($result1))
        {
          $stmtb[] = $row1;
        }
         json_encode($stmtb);

        $final[] = json_decode($stmta,true);
        $final[] = json_decode($stmtb,true);
        $json_merge = json_encode($final);

        echo json_encode($json_merge);

?>

You need to concentrate on stmta , stmtb and finally json_merge

Body:
json_encode returns the string for the json. You need to assign that to a variable during the first two encodings.

while ($row=oci_fetch_assoc($result))
    {
      $stmta[] = $row;
    }
    $stmta =  json_encode($stmta);

    $result1=oci_parse($conn,$stmt1);
    $ex2=oci_execute($result1);

    while ($row1=oci_fetch_assoc($result1))
    {
      $stmtb[] = $row1;
    }
     $stmtb = json_encode($stmtb);


问:
Array Doesn't Push Elements Node.js
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

```<code>    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }
</code>```

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.

答:
To persist data, You could save the data in localStorage.

Here is how you could do it.

```<code>  /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }

   onSubmit = function() {
        //localStorage.setItem('key', 'value');
        localStorage.setItem('myList', JSON.stringify(list));
   }

   getList = function() {
        //localStorage.getItem('key');
        list = JSON.parse(localStorage.getItem('myList'));
   }
</code>```

Title: Array Doesn't Push Elements Node.js

Body:
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.

Body:
To persist data, You could save the data in localStorage.

Here is how you could do it.

  /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }

   onSubmit = function() {
        //localStorage.setItem('key', 'value');
        localStorage.setItem('myList', JSON.stringify(list));
   }

   getList = function() {
        //localStorage.getItem('key');
        list = JSON.parse(localStorage.getItem('myList'));
   }


问:
Checking total lines read by QTextStream without using a dedicated counter
I'm currently working on code for parsing a file with an unknown number of lines. The format is roughly like this:

```<code>ShapeId: 1
ShapeType: Line
ShapeDimensions: 20, 90, 100, 20
PenColor: blue
PenWidth: 2
PenStyle: DashDotLine
PenCapStyle: FlatCap
PenJoinStyle: MiterJoin

// and so on and so forth; formats vary slightly depending on the entry
</code>```

Being a text file, obviously we'll want to check for errors. Currently, I am doing this by throwing an exceptions with (fairly) informative messages.

However, my exception messages cannot be too specific, because many of my functions which help parse the file are too generic to have specific messages. Given the sheer diversity of the lines, it's impractical to have custom-written messages for each kind of line.

As I mentioned in the title, I am using QTextStream. I am using readLine to read the each line, and then doing stuff with that line. I am also using skipWhiteSpace to skip the gaps between the blocks of data.

I was hoping QTextStream would come with this functionality, but it doesn't. The closest thing I could find is pos. This is better than nothing, but it's not nearly as useful as a line number.

I could add an integer counter to count up as I step through each line. However, this is impractical in the context of my program, where I have many helper functions that will read lines. Also, skipWhiteSpace can skip multiple lines, so I couldn't use this if I were manually counting.

Unfortunately, I haven't been able to find a good solution. The closest would be something like this, but that's assuming we're already stepping through the file, one line at a time, within a simple loop. Again, that's too impractical in this situation.

So...I guess my question is: is there an elegant way of checking the line number which a QTextStream is pointing to without relying on any previous code? Am I missing something obvious?

(I would rather avoid using on libraries other than Qt and the basic C++ libraries for this.)

答:
I think the answer is NO. If you look in QTextStreamPrivate there are no member fields that contain line count. The class itself do not need it.

You can also look at the scan() method, that is used to read lines, for hints.

Body:
I'm currently working on code for parsing a file with an unknown number of lines. The format is roughly like this:

ShapeId: 1
ShapeType: Line
ShapeDimensions: 20, 90, 100, 20
PenColor: blue
PenWidth: 2
PenStyle: DashDotLine
PenCapStyle: FlatCap
PenJoinStyle: MiterJoin

// and so on and so forth; formats vary slightly depending on the entry

Being a text file, obviously we'll want to check for errors. Currently, I am doing this by throwing an exceptions with (fairly) informative messages.

However, my exception messages cannot be too specific, because many of my functions which help parse the file are too generic to have specific messages. Given the sheer diversity of the lines, it's impractical to have custom-written messages for each kind of line.

As I mentioned in the title, I am using QTextStream. I am using readLine to read the each line, and then doing stuff with that line. I am also using skipWhiteSpace to skip the gaps between the blocks of data.

I was hoping QTextStream would come with this functionality, but it doesn't. The closest thing I could find is pos. This is better than nothing, but it's not nearly as useful as a line number.

I could add an integer counter to count up as I step through each line. However, this is impractical in the context of my program, where I have many helper functions that will read lines. Also, skipWhiteSpace can skip multiple lines, so I couldn't use this if I were manually counting.

Unfortunately, I haven't been able to find a good solution. The closest would be something like this, but that's assuming we're already stepping through the file, one line at a time, within a simple loop. Again, that's too impractical in this situation.

So...I guess my question is: is there an elegant way of checking the line number which a QTextStream is pointing to without relying on any previous code? Am I missing something obvious?

(I would rather avoid using on libraries other than Qt and the basic C++ libraries for this.)


问:
After find span in UI grid and click got failed: Element is no longer valid
I run function on UI-grid that all element in the grid are clickable.

```<code>it('Test1', function() {
    element.all(by.css('span.ft-grid-click')).each(function(elmt) {
            elmt.getText().then(function(txt) {
                if (txt == 'ORO_B_IN_002') {
                    elmt.click();
                    return;
                }
            })
        })
});
</code>```

On screen the element clicked but I got this error:

Failed: Element is no longer valid (WARNING: The server did not provide any stacktrace information).

Help please.
Thanks!

答:
There is a much better way to find an element by text Content: cssContainingText()

Here is, how it will look in your code:

```<code>it('Test1', function() {
    element(by.cssContainingText('span.ft-grid-click', 'ORO_B_IN_002')).click();
});
</code>```

This should work for you.

Body:
I run function on UI-grid that all element in the grid are clickable.

it('Test1', function() {
    element.all(by.css('span.ft-grid-click')).each(function(elmt) {
            elmt.getText().then(function(txt) {
                if (txt == 'ORO_B_IN_002') {
                    elmt.click();
                    return;
                }
            })
        })
});

On screen the element clicked but I got this error:

Failed: Element is no longer valid (WARNING: The server did not provide any stacktrace information).

Help please.
Thanks!

Body:
There is a much better way to find an element by text Content: cssContainingText()

Here is, how it will look in your code:

it('Test1', function() {
    element(by.cssContainingText('span.ft-grid-click', 'ORO_B_IN_002')).click();
});

This should work for you.


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答: Go with the name, you get better error messages :)</p>

OwnerDisplayName: tpower

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

OwnerDisplayName: Jan Bannister


问:
PHP/Javascript - Instant search, but different?
I have a page with a blank search bar, and then a bunch on contacts below it in a table. Each contact is one div.

I want to be able to filter the contact table as text is entered into the search bar. (So, for instance, if "Fran" was typed in to the search bar, you'd only see contacts with "Fran" in their name. And then all would go back to default if "Fran" was deleted.)

Is this possible? How? (I found an instant search diy guide, but it only worked the way Google does, with a dropdown beneath the search bar.)

答:
The following contains the basic logic you need although it's the reverse - it hides content that it finds and only for exact matches.  Also, it's an on keypress event so it only hides the divs after you hit space after typing the name so you'll need to tweak that too.
To look for matches within a long string of text, you will need to use some regex to test against the search string.</p>

```<code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Search</title>
    <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
    <script>
        $(document).ready(function(){
                $(".searchbox").keypress(function(){
                      $("div").each(function(){
                    if($(this).text() == $(".searchbox").val()){
                        $(this).hide("fast");
                    };
                      });
                });
            });
    </script>
    </head>
    <body>
    <form><input type="text" class="searchbox"></form>
        <div>Susan</div>
        <div>Fran</div>
        <div>Dave</div>
    </body>
    </head>
</html>
</code>```

Body:
The following contains the basic logic you need although it's the reverse - it hides content that it finds and only for exact matches.  Also, it's an on keypress event so it only hides the divs after you hit space after typing the name so you'll need to tweak that too.
To look for matches within a long string of text, you will need to use some regex to test against the search string.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Search</title>
    <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
    <script>
        $(document).ready(function(){
                $(".searchbox").keypress(function(){
                      $("div").each(function(){
                    if($(this).text() == $(".searchbox").val()){
                        $(this).hide("fast");
                    };
                      });
                });
            });
    </script>
    </head>
    <body>
    <form><input type="text" class="searchbox"></form>
        <div>Susan</div>
        <div>Fran</div>
        <div>Dave</div>
    </body>
    </head>
</html>


问:
Custom pagination view in Laravel 5
Laravel 4.2 has the option to specify a custom view in app/config/view.php such as:

```<code>/*
|--------------------------------------------------------------------------
| Pagination View
|--------------------------------------------------------------------------
|
| This view will be used to render the pagination link output, and can
| be easily customized here to show any view you like. A clean view
| compatible with Twitter's Bootstrap is given to you by default.
|
*/
'pagination' => 'pagination_slider-alt'
</code>```

This is gone in Laravel 5 at least regarding view.php.

Is there a way to replicate this behavior in Laravel 5?

答:
if you want to beautify the appearance of your pagination, I use the class from bootstrap to make it more simple and easy</p>

```<code> @if ($students->lastPage() > 1)
        <ul class="pagination ml-auto">
            <li class="{{ ($students->currentPage() == 1) ? ' disabled' : '' }} page-item">
                <a class=" page-link " href="{{ $students->url(1) }}" aria-label="Previous">
                    <span aria-hidden="true">«</span>
                    <span class="sr-only">Previous</span>
                </a>
            </li>
            @for ($i = 1; $i <= $students->lastPage(); $i++)
                <li class="{{ ($students->currentPage() == $i) ? ' active' : '' }} page-item">
                    <a class=" page-link " href="{{ $students->url($i) }}">{{ $i }}</a>
                </li>
            @endfor
            <li class="{{ ($students->currentPage() == $students->lastPage()) ? ' disabled' : '' }} page-item">
                <a href="{{ $students->url($students->currentPage()+1) }}" class="page-link" aria-label="Next">
                    <span aria-hidden="true">»</span>
                    <span class="sr-only">Next</span>
                </a>
            </li>
        </ul>
@endif
</code>```

Title: Custom pagination view in Laravel 5

Body:
Laravel 4.2 has the option to specify a custom view in app/config/view.php such as:

/*
|--------------------------------------------------------------------------
| Pagination View
|--------------------------------------------------------------------------
|
| This view will be used to render the pagination link output, and can
| be easily customized here to show any view you like. A clean view
| compatible with Twitter's Bootstrap is given to you by default.
|
*/
'pagination' => 'pagination_slider-alt'

This is gone in Laravel 5 at least regarding view.php.

Is there a way to replicate this behavior in Laravel 5?

Body:
if you want to beautify the appearance of your pagination, I use the class from bootstrap to make it more simple and easy

 @if ($students->lastPage() > 1)
        <ul class="pagination ml-auto">
            <li class="{{ ($students->currentPage() == 1) ? ' disabled' : '' }} page-item">
                <a class=" page-link " href="{{ $students->url(1) }}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                    <span class="sr-only">Previous</span>
                </a>
            </li>
            @for ($i = 1; $i <= $students->lastPage(); $i++)
                <li class="{{ ($students->currentPage() == $i) ? ' active' : '' }} page-item">
                    <a class=" page-link " href="{{ $students->url($i) }}">{{ $i }}</a>
                </li>
            @endfor
            <li class="{{ ($students->currentPage() == $students->lastPage()) ? ' disabled' : '' }} page-item">
                <a href="{{ $students->url($students->currentPage()+1) }}" class="page-link" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                    <span class="sr-only">Next</span>
                </a>
            </li>
        </ul>
@endif


问:
SBT: How to package an instance of a class as a JAR?
I have code which essentially looks like this:

```<code>class FoodTrainer(images: S3Path) { // data is >100GB file living in S3
  def train(): FoodClassifier       // Very expensive - takes ~5 hours!
}

class FoodClassifier {          // Light-weight API class
  def isHotDog(input: Image): Boolean
}
</code>```

I want to at JAR-assembly (sbt assembly) time, invoke val classifier = new FoodTrainer(s3Dir).train() and publish the JAR which has the classifier instance instantly available to downstream library users.

What is the easiest way to do this? What are some established paradigms for this? I know its a fairly common idiom in ML projects to publish trained models e.g. http://nlp.stanford.edu/software/stanford-corenlp-models-current.jar

How do I do this using sbt assembly where I do not have to check in a large model class or data file into my version control?

答:
The steps are as follows.

During the resource generation phase of build:

Generate model during resource generation phase of build.

Serialize the contents of the model to a file in a managed resources folder.

```
resourceGenerators in Compile += Def.task {
  val classifier = new FoodTrainer(s3Dir).train()
  val contents = FoodClassifier.serialize(classifier)
  val file = (resourceManaged in Compile).value / "mypackage" / "food-classifier.model"
  IO.write(file, contents)
  Seq(file)
}.taskValue
```

The resource will be included in jar file automatically and it won't appear in source tree.

To load the model just add code that reads resource and parses the model.

```
object FoodClassifierModel {
  lazy val classifier = readResource("/mypackage/food-classifier.model")
  def readResource(resourceName: String): FoodClassifier = {
    val stream = getClass.getResourceAsStream(resourceName)
    val lines = scala.io.Source.fromInputStream( stream ).getLines
    val contents = lines.mkString("\n")
    FoodClassifier.parse(contents)
  }
}
object FoodClassifier {
  def parse(content: String): FoodClassifier
  def serialize(classfier: FoodClassifier): String
}
```

Of course, as your data is rather big, you'll need to use streaming serializers and parsers to not overload java heap space. The above just shows how to package resource at build time.

See http://www.scala-sbt.org/1.x/docs/Howto-Generating-Files.html

Body:
I have code which essentially looks like this:

class FoodTrainer(images: S3Path) { // data is >100GB file living in S3
  def train(): FoodClassifier       // Very expensive - takes ~5 hours!
}

class FoodClassifier {          // Light-weight API class
  def isHotDog(input: Image): Boolean
}

I want to at JAR-assembly (sbt assembly) time, invoke val classifier = new FoodTrainer(s3Dir).train() and publish the JAR which has the classifier instance instantly available to downstream library users.

What is the easiest way to do this? What are some established paradigms for this? I know its a fairly common idiom in ML projects to publish trained models e.g. http://nlp.stanford.edu/software/stanford-corenlp-models-current.jar

How do I do this using sbt assembly where I do not have to check in a large model class or data file into my version control?

Body:
The steps are as follows.

During the resource generation phase of build:

Generate model during resource generation phase of build.

Serialize the contents of the model to a file in a managed resources folder.

resourceGenerators in Compile += Def.task {
  val classifier = new FoodTrainer(s3Dir).train()
  val contents = FoodClassifier.serialize(classifier)
  val file = (resourceManaged in Compile).value / "mypackage" / "food-classifier.model"
  IO.write(file, contents)
  Seq(file)
}.taskValue

The resource will be included in jar file automatically and it won't appear in source tree.

To load the model just add code that reads resource and parses the model.

object FoodClassifierModel {
  lazy val classifier = readResource("/mypackage/food-classifier.model")
  def readResource(resourceName: String): FoodClassifier = {
    val stream = getClass.getResourceAsStream(resourceName)
    val lines = scala.io.Source.fromInputStream( stream ).getLines
    val contents = lines.mkString("\n")
    FoodClassifier.parse(contents)
  }
}
object FoodClassifier {
  def parse(content: String): FoodClassifier
  def serialize(classfier: FoodClassifier): String
}

Of course, as your data is rather big, you'll need to use streaming serializers and parsers to not overload java heap space. The above just shows how to package resource at build time.

See http://www.scala-sbt.org/1.x/docs/Howto-Generating-Files.html


问:
getText() method doesn't work with integers
```<code>textfield2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actionevent)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017-input));
    }
});

button2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actioneven)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017 -input));
    }
});
</code>```

I am trying to get a number from the user (an integer) and subtract that number from 2017. It gives an error saying that it is a String and I can't subtract a number from a String. When I change String input to int input it gives errors again. It says that I can't use getText(). I've tried few ways such as parseInt() and it did not work. How can I fix this problem?

My Question is different from How to convert a String to an int in Java? because I looked at the answers there and they didn't really work with my code.

答:
You must convert the String obtained from the TextField to Integer

You can do that by

Integer.parseInt(string);

Integer.valueOf(string);

In you case you can do like this.

```<code> Output2.setText("Your age is " + (2017 - Integer.parseInt(input)));
</code>```

or

```<code>Output2.setText("Your age is " + (2017 - Integer.valueOf(input)));
</code>```

Body:
textfield2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actionevent)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017-input));
    }
});

button2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actioneven)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017 -input));
    }
});

I am trying to get a number from the user (an integer) and subtract that number from 2017. It gives an error saying that it is a String and I can't subtract a number from a String. When I change String input to int input it gives errors again. It says that I can't use getText(). I've tried few ways such as parseInt() and it did not work. How can I fix this problem?

My Question is different from How to convert a String to an int in Java? because I looked at the answers there and they didn't really work with my code.

Body:
You must convert the String obtained from the TextField to Integer

You can do that by

Integer.parseInt(string);

Integer.valueOf(string);

In you case you can do like this.

 Output2.setText("Your age is " + (2017 - Integer.parseInt(input)));

or

Output2.setText("Your age is " + (2017 - Integer.valueOf(input)));


问:
Response to preflight request doesn't pass access control (Angular 2 - Web Api)
I've several projects that one of them is for Authentication. However I've set CORS configuration, it still returns errors.

Note: Web Api apps work with postman.

Here is what I've done so far:

Startup.cs

```<code>[assembly: OwinStartup(typeof(LabelGenerator.Startup))]
namespace LabelGenerator {
    public partial class Startup {
        public void Configuration(IAppBuilder app) {
            ConfigOAuth(app);
            ConfigWebApi(app);
        }
    }
}
</code>```

Startup.Auth.cs

```<code>namespace LabelGenerator {
    public partial class Startup {
        private void ConfigOAuth(IAppBuilder app) {
            OAuthBearerAuthenticationOptions oAuthServerOptions = new OAuthBearerAuthenticationOptions();
            // Token Generation
            app.UseOAuthBearerAuthentication(oAuthServerOptions);
        }

        private void ConfigWebApi(IAppBuilder app) {
            HttpConfiguration conf = new HttpConfiguration();
            WebApiConfig.Register(conf);
            app.UseWebApi(conf);

            // CORS
            app.UseCors(CorsOptions.AllowAll);
        }
    }
}
</code>```

Web.config

```<code><modules runAllManagedModulesForAllRequests="true">
  <remove name="ApplicationInsightsWebTracking" />
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</code>```

答:
According to this answer I changed this :

```<code>private void ConfigWebApi(IAppBuilder app) {
    HttpConfiguration conf = new HttpConfiguration();
    WebApiConfig.Register(conf);
    app.UseWebApi(conf);

    // CORS
    app.UseCors(CorsOptions.AllowAll);
}
</code>```

to this :

```<code>private void ConfigWebApi(IAppBuilder app) {
    HttpConfiguration conf = new HttpConfiguration();
    WebApiConfig.Register(conf);

    // CORS
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(conf);
}
</code>```

And now CORS is working properly.

Body:
I've several projects that one of them is for Authentication. However I've set CORS configuration, it still returns errors.

Note: Web Api apps work with postman.

Here is what I've done so far:

Startup.cs

[assembly: OwinStartup(typeof(LabelGenerator.Startup))]
namespace LabelGenerator {
    public partial class Startup {
        public void Configuration(IAppBuilder app) {
            ConfigOAuth(app);
            ConfigWebApi(app);
        }
    }
}

Startup.Auth.cs

namespace LabelGenerator {
    public partial class Startup {
        private void ConfigOAuth(IAppBuilder app) {
            OAuthBearerAuthenticationOptions oAuthServerOptions = new OAuthBearerAuthenticationOptions();
            // Token Generation
            app.UseOAuthBearerAuthentication(oAuthServerOptions);
        }

        private void ConfigWebApi(IAppBuilder app) {
            HttpConfiguration conf = new HttpConfiguration();
            WebApiConfig.Register(conf);
            app.UseWebApi(conf);

            // CORS
            app.UseCors(CorsOptions.AllowAll);
        }
    }
}

Web.config

<modules runAllManagedModulesForAllRequests="true">
  <remove name="ApplicationInsightsWebTracking" />
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>

Body:
According to this answer I changed this :

private void ConfigWebApi(IAppBuilder app) {
    HttpConfiguration conf = new HttpConfiguration();
    WebApiConfig.Register(conf);
    app.UseWebApi(conf);

    // CORS
    app.UseCors(CorsOptions.AllowAll);
}

to this :

private void ConfigWebApi(IAppBuilder app) {
    HttpConfiguration conf = new HttpConfiguration();
    WebApiConfig.Register(conf);

    // CORS
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(conf);
}

And now CORS is working properly.


问:
div into a js button
I have a
 that I have formatted very carefully to look nice, and I need to make it have the functionality of a button. How would I go about doing this?

答:
Like if you have div

```<code> <div class="demo" >
    ....
    </div>
</code>```

And If you are using javascript

```<code>document.getElementsByClassName('demo')[0]
        .addEventListener('click', function (event) {
            // do something
    });
</code>```

using jquery u can do like

```<code>$(".demo").click(function(){
//do something
});
</code>```

Title: div into a js button

Body:
Like if you have div

 <div class="demo" >
    ....
    </div>

And If you are using javascript

document.getElementsByClassName('demo')[0]
        .addEventListener('click', function (event) {
            // do something
    });

using jquery u can do like

$(".demo").click(function(){
//do something
});


问:
How to store the content of an InkCanvas in a List
I'm implementing an undo/redo feature to an InkCanvas, so I need to save the content of the InkCanvas in a list (not a file) every time it gets modified. I'm currently saving it in an InMemoryRandomAccessStream but since it needs to be an instance I can't use it in a list. Is there a way I could store more than one content and retrieve when necessary?

答:
According to your requirement of undo/redo feature, you can use AddStroke and DeleteSelected method to add or delete the stroke that you want to undo or redo. Here is my code, you can have a reference.

```<code>private List<InkStroke> undoList = new List<InkStroke>();
private void Undo(object sender, RoutedEventArgs e)
{
    IReadOnlyList<InkStroke> inkList = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
    if (inkList.Count > 0)
    {
        InkStroke undoStroke = inkList[inkList.Count - 1];
        undoStroke.Selected = true;
        undoList.Add(undoStroke.Clone());
        inkCanvas.InkPresenter.StrokeContainer.DeleteSelected();
    }
}

private void Redo(object sender, RoutedEventArgs e)
{
    if (undoList.Count > 0)
    {
        InkStroke redoStroke = undoList[undoList.Count - 1];
        inkCanvas.InkPresenter.StrokeContainer.AddStroke(redoStroke);
        undoList.Remove(redoStroke);
    }
}
</code>```

Body:
According to your requirement of undo/redo feature, you can use AddStroke and DeleteSelected method to add or delete the stroke that you want to undo or redo. Here is my code, you can have a reference.

private List<InkStroke> undoList = new List<InkStroke>();
private void Undo(object sender, RoutedEventArgs e)
{
    IReadOnlyList<InkStroke> inkList = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
    if (inkList.Count > 0)
    {
        InkStroke undoStroke = inkList[inkList.Count - 1];
        undoStroke.Selected = true;
        undoList.Add(undoStroke.Clone());
        inkCanvas.InkPresenter.StrokeContainer.DeleteSelected();
    }
}

private void Redo(object sender, RoutedEventArgs e)
{
    if (undoList.Count > 0)
    {
        InkStroke redoStroke = undoList[undoList.Count - 1];
        inkCanvas.InkPresenter.StrokeContainer.AddStroke(redoStroke);
        undoList.Remove(redoStroke);
    }
}


问:
Spaces vs. Tabs -- Best Practice?
I used to be a tab freak -- I would always use tabs to indent my source code, and if I saw any spaces, I would instantly do a regex search/replace to replace all leading spaces with tabs.

...until I realized that I hadn't noticed the presence of a lot of the spaces in some files, such that they opened up inconsistently in different editors (e.g. Notepad++ vs. Emacs vs. Visual Studio).

What are good reasons for why one is better than the other in general? Is either one generally known as better practice?

答:
With good text editors, it does not really matter. It is just a technical background detail. The UI behavior will be just the same.

The only important thing here is that everyone in a project makes the decision what to use, and that everyone sticks to that. Because, as you discovered, there will be problems if both tabs and spaces are used for indentation inside a file.

UPDATE: When I mean that everyone in a project makes the decision what to use, I of course mean that everyone should agree on the same decision. :D  (This can be the tricky part.)

Title: Spaces vs. Tabs -- Best Practice?


问:
How to convert a float to binary using javascript
Here is the Example:

For example, suppose we have a float 13.4. In binary, it can be written as: 1101.01100110011001100110011001100110011兮.

Suppose the system stores bits up to 10 decimal places. So 13.4 is stored as: 1101.0110011001 (only 10 decimal places now)

Because of this change, if you convert 1101.0110011001 back to base 10, you get 13.399414. In essence 13.399414 is stored rather than 13.4 in this case!

So given a floating point in base 10, an integer n which represents the number of decimal places as defined above, output the stored value of the float to three decimal places.

So How can i convert using javascript:- input 13.4 and output 13.399

答:
You can get a number with a desired number of fractional digits by shifting it to the left by that number of places, dropping the remaining digits on the right by flooring it, and shifting it back right. This works in any base - base 2 in your case:</p>

```<code>Math.floor(13.4 * 2**10) / 2**10
Math.floor(13.4 * Math.pow(2, 10)) / Math.pow(2, 10)
Math.floor(13.4 * (1<<10)) / (1<<10)
</code>```

Body:
You can get a number with a desired number of fractional digits by shifting it to the left by that number of places, dropping the remaining digits on the right by flooring it, and shifting it back right. This works in any base - base 2 in your case:

Math.floor(13.4 * 2**10) / 2**10
Math.floor(13.4 * Math.pow(2, 10)) / Math.pow(2, 10)
Math.floor(13.4 * (1<<10)) / (1<<10)


问:
How to print only specific class value
I have 3 div's in a View. Every div has unique single_value. so when i click on any of that it should alert that data value. For that i used the following script

```<code>  $(document).on('click','.single_school',function(){
      var school = $( ".single_school" ).attr('data-value');
        alert(school)
      });
</code>```

But the problem is i'm only getting the first value whatever div I clicked on. How do i print only the specific div I clicked on.

Here is the View:

```<code><div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="1">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>
        <div class="school_info">
            <p class="school_name">ABC</p>
        </div>
    </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="2">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>
        <div class="school_info">
            <p class="school_name">XYZ</p>
        </div>
    </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="3">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>
        <div class="school_info">
            <p class="school_name">PQR</p>
        </div>
    </div>
</div>
</code>```

答:
```<code>$(document).on('click','.single_school',function(){
  var school = $(this).attr('data-value');
    alert(school)
  });
</code>```

Title: How to print only specific class value

Body:
I have 3 div's in a View. Every div has unique single_value. so when i click on any of that it should alert that data value. For that i used the following script

  $(document).on('click','.single_school',function(){
      var school = $( ".single_school" ).attr('data-value');
        alert(school)
      });

But the problem is i'm only getting the first value whatever div I clicked on. How do i print only the specific div I clicked on.

Here is the View:

ABC

XYZ

PQR


问:
text-overflow: ellipsis not working in  IE9
i have tried the following code to my td, but no good sign.

```<code>.td_class{
max-width:100px;
overflow: hidden;
text-overflow : ellipsis;
-ms-text-overflow : ellipsis;
}
</code>```

any help?

答: If you have set "word-wrap: bread-word" in other style like "*{word-wrap: bread-word}", please change it to "word:wrap: normal". It works for me.

Title: text-overflow: ellipsis not working in <td> IE9

Body:
i have tried the following code to my td, but no good sign.

.td_class{
max-width:100px;
overflow: hidden;
text-overflow : ellipsis;
-ms-text-overflow : ellipsis;
}

any help?