问:
How do I get a Uri to an image in my Assets that will work for the SearchManager.SUGGEST_COLUMN_ICON_1 column?
I have successfully integrated my app's country search into the global search facility and now I am trying to display each country's flag next to the search suggestions.  Search inside my app works this way but of course I have control of the list and its view binding myself.  So I know the flags are all there and I can use them in the rest of my app.

The trouble comes when I try to supply a Uri to a .gif file in my Assets.  According to the search documentation the value of the column with the key SearchManager.SUGGEST_COLUMN_ICON_1 should be a Uri to the image.

Below is what the code looks like.  In response to the ContentProvider method public Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) I am creating a MatrixCursor that maps columns from my country database to those required by the search facility.  The country names show up fine and I can select them and correctly respond in my application.

I have tried forming the Uri three different ways:

```<code>//                    String flagUri = "file:///android_asset/" + flagPath;
//                    String flagUri = "file:///assets/" + flagPath;
                    String flagUri = "android.resource://com.lesliesoftware.worldinfo.WorldInfoActivity/assets/" + flagPath;
                    columnValues.add (flagUri);
</code>```

They all lead to the same thing - my application icon next to each suggestion which I can get by using a value of empty string.

Is there a Uri that will work?  How can I get the country flag icon next to the search suggestions?

Thanks Ian

The full source:

```<code>private Cursor search (String query, int limit)  {
    query = query.toLowerCase ();
    String[] requestedColumns = new String[]  {
            BaseColumns._ID,
            SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_ICON_1,
    };
    String[] queryColumns = new String[]  {
            WorldInfoDatabaseAdapter.KEY_ROWID,
            WorldInfoDatabaseAdapter.KEY_COUNTRYNAME,
            WorldInfoDatabaseAdapter.KEY_COUNTRYCODE
    };

    return packageResults (query, requestedColumns, queryColumns, limit);
}

private Cursor packageResults (String query, String[] requestedColumns, String[] queryMappedColumns, int limit)  {
    if (requestedColumns.length != queryMappedColumns.length)
        throw new IllegalArgumentException ("Internal error: requested columns do not map to query columns");

    MatrixCursor results = new MatrixCursor (requestedColumns);

    //  Query the country list returns columns: KEY_ROWID, KEY_COUNTRYNAME, KEY_COUNTRYCODE
    Cursor dbResults = myDbHelper.getCountryList (query);

    //  Verify that the query columns are available
    for (int index = 0; index < queryMappedColumns.length; index++)  {
        int col = dbResults.getColumnIndex (queryMappedColumns[index]);
        if (col == -1)
            throw new IllegalArgumentException ("Internal error: requested column '" +
                    queryMappedColumns[index] + "' was not returned from the database.");
    }

    //  Loop over the database results building up the requested results
    int rowCount = 0;
    while (dbResults.moveToNext ()  &&  rowCount < limit)  {
        Vector<String> columnValues = new Vector<String> ();
        for (int index = 0; index < requestedColumns.length; index++)  {
            if (requestedColumns[index].compareTo (SearchManager.SUGGEST_COLUMN_ICON_1) == 0)  {
                String flagPath = "flags/small/" + dbResults.getString (
                        dbResults.getColumnIndexOrThrow (queryMappedColumns[index]))
                        + "-flag.gif";
//                    String flagUri = "file:///android_asset/" + flagPath;
//                    String flagUri = "file:///assets/" + flagPath;
                String flagUri = "android.resource://com.lesliesoftware.worldinfo.WorldInfoActivity/assets/" + flagPath;
                columnValues.add (flagUri);
            }  else  {
                //  Add the mapped query column values from the database
                String colValue = dbResults.getString (dbResults.getColumnIndexOrThrow (queryMappedColumns[index]));
                columnValues.add (colValue);
            }
        }

        results.addRow (columnValues);
        rowCount++;
    }

    return results;
}
</code>```

EDIT:
I have tried other variations including moving the images from the assets to the raw folder.  Nothing worked.  Here are the uri's I tried:

```<code>flagUriStr = "android.resource://com.lesliesoftware.worldinfo/raw/flags/small/" +
    countryCode + "-flag.gif";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/assets/flags/small/" +
    countryCode + "-flag.gif";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/assets/flags/small/" +
    countryCode + "-flag";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/raw/" +
    countryCode + "-flag.gif";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/raw/" +
    countryCode + "-flag";
</code>```

The only uri that did work was if I moved a test flag into my drawable folder:

```<code>flagUriStr = "android.resource://com.lesliesoftware.worldinfo/" +
    R.drawable.small_ca_flag;
</code>```

答:
Sadly after much searching around I have reached the conclusion that you cannot return a uri to an image asset to the search facility.  What I did instead was move my flag images to the resources (so they do not clutter up my app's resources I created a library for the flag images) and use resource uri's.  So, in my provider I have code that looks like this in the loop that maps database results to search results:

```<code>            if (requestedColumns[index].compareTo (SearchManager.SUGGEST_COLUMN_ICON_1) == 0)  {
                //  Translate the country code into a flag icon uri
                String countryCode = dbResults.getString (
                        dbResults.getColumnIndexOrThrow (queryMappedColumns[index]));

                int flagImageID = FlagLookup.smallFlagResourceID (countryCode);
                String flagUriStr = "android.resource://com.lesliesoftware.worldinfo/" + flagImageID;
                columnValues.add (flagUriStr);
            }
</code>```

and look up code that looks like this:

```<code>static public int smallFlagResourceID (String countryCode)  {
    if (countryCode == null || countryCode.length () == 0)
        return R.drawable.flag_small_none;

    if (countryCode.equalsIgnoreCase ("aa"))
        return R.drawable.flag_small_aa;
    else if (countryCode.equalsIgnoreCase ("ac"))
        return R.drawable.flag_small_ac;
    else if (countryCode.equalsIgnoreCase ("ae"))
        return R.drawable.flag_small_ae;
    ...
</code>```

I will just have to make sure I create a test that verifies that all countries that have flags returns the expected results.

Body:
I have successfully integrated my app's country search into the global search facility and now I am trying to display each country's flag next to the search suggestions.  Search inside my app works this way but of course I have control of the list and its view binding myself.  So I know the flags are all there and I can use them in the rest of my app.

The trouble comes when I try to supply a Uri to a .gif file in my Assets.  According to the search documentation the value of the column with the key SearchManager.SUGGEST_COLUMN_ICON_1 should be a Uri to the image.

Below is what the code looks like.  In response to the ContentProvider method public Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) I am creating a MatrixCursor that maps columns from my country database to those required by the search facility.  The country names show up fine and I can select them and correctly respond in my application.

I have tried forming the Uri three different ways:

//                    String flagUri = "file:///android_asset/" + flagPath;
//                    String flagUri = "file:///assets/" + flagPath;
                    String flagUri = "android.resource://com.lesliesoftware.worldinfo.WorldInfoActivity/assets/" + flagPath;
                    columnValues.add (flagUri);

They all lead to the same thing - my application icon next to each suggestion which I can get by using a value of empty string.

Is there a Uri that will work?  How can I get the country flag icon next to the search suggestions?

Thanks Ian

The full source:

private Cursor search (String query, int limit)  {
    query = query.toLowerCase ();
    String[] requestedColumns = new String[]  {
            BaseColumns._ID,
            SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_ICON_1,
    };
    String[] queryColumns = new String[]  {
            WorldInfoDatabaseAdapter.KEY_ROWID,
            WorldInfoDatabaseAdapter.KEY_COUNTRYNAME,
            WorldInfoDatabaseAdapter.KEY_COUNTRYCODE
    };

    return packageResults (query, requestedColumns, queryColumns, limit);
}

private Cursor packageResults (String query, String[] requestedColumns, String[] queryMappedColumns, int limit)  {
    if (requestedColumns.length != queryMappedColumns.length)
        throw new IllegalArgumentException ("Internal error: requested columns do not map to query columns");

    MatrixCursor results = new MatrixCursor (requestedColumns);

    //  Query the country list returns columns: KEY_ROWID, KEY_COUNTRYNAME, KEY_COUNTRYCODE
    Cursor dbResults = myDbHelper.getCountryList (query);

    //  Verify that the query columns are available
    for (int index = 0; index < queryMappedColumns.length; index++)  {
        int col = dbResults.getColumnIndex (queryMappedColumns[index]);
        if (col == -1)
            throw new IllegalArgumentException ("Internal error: requested column '" +
                    queryMappedColumns[index] + "' was not returned from the database.");
    }

    //  Loop over the database results building up the requested results
    int rowCount = 0;
    while (dbResults.moveToNext ()  &&  rowCount < limit)  {
        Vector<String> columnValues = new Vector<String> ();
        for (int index = 0; index < requestedColumns.length; index++)  {
            if (requestedColumns[index].compareTo (SearchManager.SUGGEST_COLUMN_ICON_1) == 0)  {
                String flagPath = "flags/small/" + dbResults.getString (
                        dbResults.getColumnIndexOrThrow (queryMappedColumns[index]))
                        + "-flag.gif";
//                    String flagUri = "file:///android_asset/" + flagPath;
//                    String flagUri = "file:///assets/" + flagPath;
                String flagUri = "android.resource://com.lesliesoftware.worldinfo.WorldInfoActivity/assets/" + flagPath;
                columnValues.add (flagUri);
            }  else  {
                //  Add the mapped query column values from the database
                String colValue = dbResults.getString (dbResults.getColumnIndexOrThrow (queryMappedColumns[index]));
                columnValues.add (colValue);
            }
        }

        results.addRow (columnValues);
        rowCount++;
    }

    return results;
}

EDIT:
I have tried other variations including moving the images from the assets to the raw folder.  Nothing worked.  Here are the uri's I tried:

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/raw/flags/small/" +
    countryCode + "-flag.gif";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/assets/flags/small/" +
    countryCode + "-flag.gif";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/assets/flags/small/" +
    countryCode + "-flag";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/raw/" +
    countryCode + "-flag.gif";

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/raw/" +
    countryCode + "-flag";

The only uri that did work was if I moved a test flag into my drawable folder:

flagUriStr = "android.resource://com.lesliesoftware.worldinfo/" +
    R.drawable.small_ca_flag;

Body:
Sadly after much searching around I have reached the conclusion that you cannot return a uri to an image asset to the search facility.  What I did instead was move my flag images to the resources (so they do not clutter up my app's resources I created a library for the flag images) and use resource uri's.  So, in my provider I have code that looks like this in the loop that maps database results to search results:

            if (requestedColumns[index].compareTo (SearchManager.SUGGEST_COLUMN_ICON_1) == 0)  {
                //  Translate the country code into a flag icon uri
                String countryCode = dbResults.getString (
                        dbResults.getColumnIndexOrThrow (queryMappedColumns[index]));

                int flagImageID = FlagLookup.smallFlagResourceID (countryCode);
                String flagUriStr = "android.resource://com.lesliesoftware.worldinfo/" + flagImageID;
                columnValues.add (flagUriStr);
            }

and look up code that looks like this:

static public int smallFlagResourceID (String countryCode)  {
    if (countryCode == null || countryCode.length () == 0)
        return R.drawable.flag_small_none;

    if (countryCode.equalsIgnoreCase ("aa"))
        return R.drawable.flag_small_aa;
    else if (countryCode.equalsIgnoreCase ("ac"))
        return R.drawable.flag_small_ac;
    else if (countryCode.equalsIgnoreCase ("ae"))
        return R.drawable.flag_small_ae;
    ...

I will just have to make sure I create a test that verifies that all countries that have flags returns the expected results.


来源: stackexchange

问:
Javascript timer wrong in math game
I am doing a simple math game in javascript. Everything works  until the moment when the timer needs to be reset on starting generating new question. On this moment something very strange happens. The timer start showing some strange negative or unreal positive values.

To experience my problem first press the play button then start playing the game. Enter only true answers. After some tries you will see that something with the timer is wrong.

Full code below:

https://jsfiddle.net/6xq847gf/

https://codepen.io/Atatanas/pen/KyyLgK

```<code>function timer(timeleft){
    timeleft = 5;
    timeTime = setInterval(function() {
        timeleft--;
        document.getElementById("countdown").textContent = timeleft;
        if(timeleft <= 0){
            clearInterval(timeTime);
        }
    },1000)
}
function clearTime() {
    clearInterval(timeTime);
    timeleft=5;
    timer(5);
}
</code>```

答:
You generated multiple instances of setInterval(). That is why when you did clearInterval(), only immediate setInterval instance is cleared. But, the other instances are still running.

I commented those lines which have to be removed.

You have to call clearInterval() before another setInterval(). So, I put clearTime() before load().

var number1, number2, max = 10,
            sign, numberSigns = 2,
            output, userOutput,points=0,timeleft = 10,timeTime;

function endGame(){
hide('points');
hide('countdown');
hide('base');
randomColor();
}
function timer(timeleft){
  timeleft=5;
  timeTime = setInterval(function(){
    timeleft--;
    document.getElementById("countdown").textContent = timeleft;
    if(timeleft <= 0){
        clearInterval(timeTime);
    }

 },1000)
 }
 function clearTime(){
 clearInterval(timeTime);
 timeleft=5;
 //timer(5);
 }
        function check() {
            userOutput = document.getElementById('enterNumber') .value;
            if (userOutput) {
   if(userOutput==output){
               document.getElementById('points').innerHTML=points=points+1;
      clearTime();
               load();
      randomColor();

            }else{

   alert('WRONG');
        }
  }else{
  alert('Please enter something.');
  }}

        function load() {
            number1 = Math.round(Math.random() * max);
            number2 = Math.round(Math.random() * max);
            sign = Math.round(Math.random() * numberSigns);
            if (sign == 1) {
                if (number1 < number2) {
                    load();
                } else {
                    document.getElementById('outputMath').innerHTML = number1 + "-" + number2;
                    output = number1 - number2;
     timer(5);
                }
            } else {
                document.getElementById('outputMath').innerHTML = number1 + "+" + number2;
                output = number1 + number2;
    timer(5);
            }
        }

        function hideStart() {
            document.getElementById("menu").style.display = "none";
            randomColor();
            load();
            show('base');
   show('points');
   show('countdown');
        }

        function hide(id) {
            document.getElementById(id).style.display = "none";
            randomColor();
        }

        function show(id) {
            document.getElementById(id).style.display = "block";
        }

        function randomColor() {
            var bgcolorlist = new Array("#1abc9c", "#16a085", "#f1c40f", "#f39c12", "#2ecc71", "#27ae60", "#e67e22", "#d35400", "#3498db", "#2980b9", "#e74c3c", "#c0392b", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50");
            document.body.style.background = bgcolorlist[Math.floor(Math.random() * bgcolorlist.length)];
        }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>        * {
            margin: 0;
            padding: 0;
            transition: 1s;
            outline: none
        }
        ::selection {
            color: white;
            background-color: black;
        }
        body,
        html {
            margin: 0;
            padding: 0;
            background: linear-gradient(229deg, #a1c4fd, #c2e9fb, #cfd9df, #667eea, #764ba2, #e2d1c3, #89f7fe, #66a6ff, #48c6ef, #6f86d6, #feada6, #a3bded, #6991c7, #13547a, #80d0c7, #93a5cf, #434343, #000000, #93a5cf, #ff758c, #868f96, #596164, #c79081, #dfa579, #09203f, #96deda, #50c9c3, #29323c, #485563, #1e3c72, #2a5298, #b7f8db, #50a7c2, #2193b0, #6dd5ed);
            background-size: 7400% 7400%;
            animation: backgroundGardient 500s ease infinite;
            height: 100%;
            display: grid;
            overflow: auto;
        }
        @-webkit-keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        @-moz-keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        @-o-keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        @keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        h1#frontText {
            position: fixed;
            top: 10vh;
            font-size: calc(1vh + 1vw + 3em);
            color: white;
            width: 70vw;
            left: 15vw;
        }
        div#menu {
            border-radius: 10em;
            opacity: 0.8;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #ecf0f1;
            color: black;
            width: 80vw;
            text-align: center;
            vertical-align: middle:
        }
        button#startGame {
            font-size: calc(1vh + 1vw + 3em + 10vmax);
            background-color: #141414;
            color: white;
            border: none;
        }
        @keyframes pulse_animation {
            0% {
                transform: scale(1);
            }
            30% {
                transform: scale(1);
            }
            40% {
                transform: scale(1.08);
            }
            50% {
                transform: scale(1);
            }
            60% {
                transform: scale(1);
            }
            70% {
                transform: scale(1.05);
            }
            80% {
                transform: scale(1);
            }
            100% {
                transform: scale(1);
            }
        }
        button#startGame:hover {
            background-color: #ecf0f1;
            border: none;
            cursor: pointer;
            overflow: hidden;
            outline: none;
            transform: rotate(360deg);
            color: black;
            border-radius: 1em;
            transition: 2s;
            box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);
            animation-name: pulse_animation;
            animation-duration: 5000ms;
            transform-origin: 70% 70%;
            animation-iteration-count: infinite;
            animation-timing-function: linear;
        }
        div#menu:hover {
            width: 100vw;
            border-radius: 0;
            opacity: 1;
            transition: 2s;
            box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);
            background-color: #141414;
        }
        div#base {
            display: none;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #ecf0f1;
            border: calc(1vh + 1vw) solid #ecf0f1;
            text-align: center;
            vertical-align: middle;
            border-radius: 0.5em;
   opacity:0.8;
     box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
        }
        div#base:hover {
            border-radius: 0.1em;
   opacity:1;
     box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
        }
        p#outputMath {
            font-size: calc(2vh + 2vw + 5vmax + 5em);
            text-align: center;
            vertical-align: middle;
        }
        input#enterNumber {
            width: 50vw;
            font-size: calc(1vh + 1vw + 1em + 1vmax);
            border: 2px solid black;
   text-align:center;
        }
        input#enterNumber:hover {
            border: 2px solid orange;
        }
        input#enterNumber:focus {
            border: 2px solid red;
        }
        button#submit {
            min-width: 45vw;
            min-height: 10vh;
            background-color: #141414;
            border: none;
            border-radius: 2em;
            font-size: calc(1vh + 1vw + 1em + 1vmax);
            color: white;
        }
        button#submit:hover {
            min-width: 50vw;
            background-color: #2c3e50;
            border-radius: 0.2em;
            color: white;
        }
div#points{
background-color:#e74c3c;
color:white;
 border-bottom-left-radius: 1em;
position:fixed;
top:0vh;
right:0vw;
border:1vw solid #e74c3c;
font-size:calc(1vh + 1vw + 2em);
display:none;
  box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
}
 div#countdown{
 background-color:#3498db;
color:white;
 border-bottom-right-radius: 1em;
position:fixed;
top:0vh;
left:0vw;
border:1vw solid #3498db;
font-size:calc(1vh + 1vw + 2em);
display:none;
  box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
 }
div#result{
position:absolute;
top:0;
left:0;
height:100vh;
width:100vw;
display:none;
}</code>```

<!Doctype html>

<meta charset="utf-8">

        <button onclick='hideStart()' id='startGame'>►

        <input id='enterNumber' type='number'> </input>

        <button onClick='check()' id='submit'>Check</button>

0

```

ContentLicense: CC BY-SA 3.0

Title: Javascript timer wrong in math game

Body:
I am doing a simple math game in javascript. Everything works  until the moment when the timer needs to be reset on starting generating new question. On this moment something very strange happens. The timer start showing some strange negative or unreal positive values.

To experience my problem first press the play button then start playing the game. Enter only true answers. After some tries you will see that something with the timer is wrong.

Full code below:

https://jsfiddle.net/6xq847gf/

https://codepen.io/Atatanas/pen/KyyLgK

function timer(timeleft){
    timeleft = 5;
    timeTime = setInterval(function() {
        timeleft--;
        document.getElementById("countdown").textContent = timeleft;
        if(timeleft <= 0){
            clearInterval(timeTime);
        }
    },1000)
}
function clearTime() {
    clearInterval(timeTime);
    timeleft=5;
    timer(5);
}

Body:
You generated multiple instances of setInterval(). That is why when you did clearInterval(), only immediate setInterval instance is cleared. But, the other instances are still running.

I commented those lines which have to be removed.

You have to call clearInterval() before another setInterval(). So, I put clearTime() before load().

var number1, number2, max = 10,
            sign, numberSigns = 2,
            output, userOutput,points=0,timeleft = 10,timeTime;

function endGame(){
hide('points');
hide('countdown');
hide('base');
randomColor();
}
function timer(timeleft){
  timeleft=5;
  timeTime = setInterval(function(){
    timeleft--;
    document.getElementById("countdown").textContent = timeleft;
    if(timeleft <= 0){
        clearInterval(timeTime);
    }

 },1000)
 }
 function clearTime(){
 clearInterval(timeTime);
 timeleft=5;
 //timer(5);
 }
        function check() {
            userOutput = document.getElementById('enterNumber') .value;
            if (userOutput) {
   if(userOutput==output){
               document.getElementById('points').innerHTML=points=points+1;
      clearTime();
               load();
      randomColor();

            }else{

   alert('WRONG');
        }
  }else{
  alert('Please enter something.');
  }}

        function load() {
            number1 = Math.round(Math.random() * max);
            number2 = Math.round(Math.random() * max);
            sign = Math.round(Math.random() * numberSigns);
            if (sign == 1) {
                if (number1 < number2) {
                    load();
                } else {
                    document.getElementById('outputMath').innerHTML = number1 + "-" + number2;
                    output = number1 - number2;
     timer(5);
                }
            } else {
                document.getElementById('outputMath').innerHTML = number1 + "+" + number2;
                output = number1 + number2;
    timer(5);
            }
        }

        function hideStart() {
            document.getElementById("menu").style.display = "none";
            randomColor();
            load();
            show('base');
   show('points');
   show('countdown');
        }

        function hide(id) {
            document.getElementById(id).style.display = "none";
            randomColor();
        }

        function show(id) {
            document.getElementById(id).style.display = "block";
        }

        function randomColor() {
            var bgcolorlist = new Array("#1abc9c", "#16a085", "#f1c40f", "#f39c12", "#2ecc71", "#27ae60", "#e67e22", "#d35400", "#3498db", "#2980b9", "#e74c3c", "#c0392b", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50");
            document.body.style.background = bgcolorlist[Math.floor(Math.random() * bgcolorlist.length)];
        }

        * {
            margin: 0;
            padding: 0;
            transition: 1s;
            outline: none
        }
        ::selection {
            color: white;
            background-color: black;
        }
        body,
        html {
            margin: 0;
            padding: 0;
            background: linear-gradient(229deg, #a1c4fd, #c2e9fb, #cfd9df, #667eea, #764ba2, #e2d1c3, #89f7fe, #66a6ff, #48c6ef, #6f86d6, #feada6, #a3bded, #6991c7, #13547a, #80d0c7, #93a5cf, #434343, #000000, #93a5cf, #ff758c, #868f96, #596164, #c79081, #dfa579, #09203f, #96deda, #50c9c3, #29323c, #485563, #1e3c72, #2a5298, #b7f8db, #50a7c2, #2193b0, #6dd5ed);
            background-size: 7400% 7400%;
            animation: backgroundGardient 500s ease infinite;
            height: 100%;
            display: grid;
            overflow: auto;
        }
        @-webkit-keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        @-moz-keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        @-o-keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        @keyframes backgroundGardient {
            0% {
                background-position: 0% 83%
            }
            50% {
                background-position: 100% 18%
            }
            100% {
                background-position: 0% 83%
            }
        }
        h1#frontText {
            position: fixed;
            top: 10vh;
            font-size: calc(1vh + 1vw + 3em);
            color: white;
            width: 70vw;
            left: 15vw;
        }
        div#menu {
            border-radius: 10em;
            opacity: 0.8;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #ecf0f1;
            color: black;
            width: 80vw;
            text-align: center;
            vertical-align: middle:
        }
        button#startGame {
            font-size: calc(1vh + 1vw + 3em + 10vmax);
            background-color: #141414;
            color: white;
            border: none;
        }
        @keyframes pulse_animation {
            0% {
                transform: scale(1);
            }
            30% {
                transform: scale(1);
            }
            40% {
                transform: scale(1.08);
            }
            50% {
                transform: scale(1);
            }
            60% {
                transform: scale(1);
            }
            70% {
                transform: scale(1.05);
            }
            80% {
                transform: scale(1);
            }
            100% {
                transform: scale(1);
            }
        }
        button#startGame:hover {
            background-color: #ecf0f1;
            border: none;
            cursor: pointer;
            overflow: hidden;
            outline: none;
            transform: rotate(360deg);
            color: black;
            border-radius: 1em;
            transition: 2s;
            box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);
            animation-name: pulse_animation;
            animation-duration: 5000ms;
            transform-origin: 70% 70%;
            animation-iteration-count: infinite;
            animation-timing-function: linear;
        }
        div#menu:hover {
            width: 100vw;
            border-radius: 0;
            opacity: 1;
            transition: 2s;
            box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);
            background-color: #141414;
        }
        div#base {
            display: none;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #ecf0f1;
            border: calc(1vh + 1vw) solid #ecf0f1;
            text-align: center;
            vertical-align: middle;
            border-radius: 0.5em;
   opacity:0.8;
     box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
        }
        div#base:hover {
            border-radius: 0.1em;
   opacity:1;
     box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
        }
        p#outputMath {
            font-size: calc(2vh + 2vw + 5vmax + 5em);
            text-align: center;
            vertical-align: middle;
        }
        input#enterNumber {
            width: 50vw;
            font-size: calc(1vh + 1vw + 1em + 1vmax);
            border: 2px solid black;
   text-align:center;
        }
        input#enterNumber:hover {
            border: 2px solid orange;
        }
        input#enterNumber:focus {
            border: 2px solid red;
        }
        button#submit {
            min-width: 45vw;
            min-height: 10vh;
            background-color: #141414;
            border: none;
            border-radius: 2em;
            font-size: calc(1vh + 1vw + 1em + 1vmax);
            color: white;
        }
        button#submit:hover {
            min-width: 50vw;
            background-color: #2c3e50;
            border-radius: 0.2em;
            color: white;
        }
div#points{
background-color:#e74c3c;
color:white;
 border-bottom-left-radius: 1em;
position:fixed;
top:0vh;
right:0vw;
border:1vw solid #e74c3c;
font-size:calc(1vh + 1vw + 2em);
display:none;
  box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
}
 div#countdown{
 background-color:#3498db;
color:white;
 border-bottom-right-radius: 1em;
position:fixed;
top:0vh;
left:0vw;
border:1vw solid #3498db;
font-size:calc(1vh + 1vw + 2em);
display:none;
  box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
 }
div#result{
position:absolute;
top:0;
left:0;
height:100vh;
width:100vw;
display:none;
}

<!Doctype html>
<html>
<meta charset="utf-8">

<head>
</head>

<body>
    <div id='menu'>
        <button onclick='hideStart()' id='startGame'>►</h1>
    </div>
    <div id='base'>
        <p id='outputMath'></p>
        <input id='enterNumber' type='number'> </input>
        </br>
        </br>
        <button onClick='check()' id='submit'>Check</button>
    </div>
   <div id='points'>0</div>
   <div  id="countdown"></div>
   <div id='result'></div>
</body>

</html>


问:
Is there an expression for an infinite iterator?
Is there a straight-forward expression that can produce an infinite iterator?

This is a purely theoretical question. No need for a "practical" answer here :)

For example, it is easy to use a generator expression to make a finite iterator:

```<code>my_gen = (0 for i in xrange(42))
</code>```

However, to make an infinite one I need to "pollute" my namespace with a bogus function:

```<code>def _my_gen():
    while True:
        yield 0
my_gen = _my_gen()
</code>```

Doing things in a separate file and import-ing later doesn't count.

I also know that itertools.repeat does exactly this. I'm curious if there is a one-liner solution without that.

答:
Quite ugly and crazy (very funny however), but you can build your own iterator from an expression by using some tricks (without "polluting" your namespace as required):</p>

```<code>{ print("Hello world") for _ in
    (lambda o: setattr(o, '__iter__', lambda x:x)
            or setattr(o, '__next__', lambda x:True)
            or o)
    (type("EvilIterator", (object,), {}))() }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a straight-forward expression that can produce an infinite iterator?

This is a purely theoretical question. No need for a "practical" answer here :)

For example, it is easy to use a generator expression to make a finite iterator:

my_gen = (0 for i in xrange(42))

However, to make an infinite one I need to "pollute" my namespace with a bogus function:

def _my_gen():
    while True:
        yield 0
my_gen = _my_gen()

Doing things in a separate file and import-ing later doesn't count.

I also know that itertools.repeat does exactly this. I'm curious if there is a one-liner solution without that.

Body:
Quite ugly and crazy (very funny however), but you can build your own iterator from an expression by using some tricks (without "polluting" your namespace as required):

{ print("Hello world") for _ in
    (lambda o: setattr(o, '__iter__', lambda x:x)
            or setattr(o, '__next__', lambda x:True)
            or o)
    (type("EvilIterator", (object,), {}))() }


问:
Evaluating list of boolean methods ruby
I have a list of methods who if any of them evaluated to true, I have to trigger an action on the model, in this case it's model audit.

So for example :

```<code>def a?
  false # in reality this is some code
end

def b?
  true # in reality this is some code
end

def c?
  true # in reality this is some code
end
</code>```

Now I can group this into like a parent method like :

```<code>def parent_method
  a? || b? || c?
end
</code>```

This will short-circuit the code, and c? will never be executed which is great. I can execute my .audit method.

But if I wanted to pass in custom message to my .audit method, and I wanted to have different message for every method how can I do that?

My first though to have a hash with keys being the methods and values being the messages or something along that line. But in that case the short circuiting doesn't work as all methods are evaluated in advance. How can I make this work better and more efficient/elegant?

答:
if I wanted to pass in custom message to my .audit method, and I wanted to have different message for every method how can I do that?

You could use a case expression:

```<code>case
when a? then audit(:a)
when b? then audit(:b)
when c? then audit(:c)
end
</code>```

Title: Evaluating list of boolean methods ruby

Body:
I have a list of methods who if any of them evaluated to true, I have to trigger an action on the model, in this case it's model audit.

So for example :

def a?
  false # in reality this is some code
end

def b?
  true # in reality this is some code
end

def c?
  true # in reality this is some code
end

Now I can group this into like a parent method like :

def parent_method
  a? || b? || c?
end

This will short-circuit the code, and c? will never be executed which is great. I can execute my .audit method.

But if I wanted to pass in custom message to my .audit method, and I wanted to have different message for every method how can I do that?

My first though to have a hash with keys being the methods and values being the messages or something along that line. But in that case the short circuiting doesn't work as all methods are evaluated in advance. How can I make this work better and more efficient/elegant?

Body:
if I wanted to pass in custom message to my .audit method, and I wanted to have different message for every method how can I do that?

You could use a case expression:

case
when a? then audit(:a)
when b? then audit(:b)
when c? then audit(:c)
end


问:
how to access object attributes of an array
I recently found out that in the chrome console I was able to do something really unusual.

Here's a simple example using an array of objects.

```<code>g = [{age: 23}, {age:33}];

g.foo = "bar";
> (2) [{…}, {…}, foo: "bar"]
</code>```

I think I'm able to do this because all js data structures are objects? Is there any way get access to foo:bar without knowing what it is beforehand?

```<code>g = g.filter(function(e){
          return e.age !== 33;
          });

> (2) [{…}]
</code>```

Specifically I'm trying to filter an array, without losing the object attributes that I set like foo:"bar".

The filtered arrays I'm getting back do not contain the object attributes I had before.

So my question is what is the best way to get access to attributes that I set on an array object when I treat it like an object in this strange way?

Ideally I could run something(g) and get back {foo: 'bar'}, or a list of all the props that exist on this object that aren't related to the array aspect of it.

Or is this just a super hacky idea and I shouldn't do it like this in the first place?

Thanks!

答:
You could use Object.keys for own enumerable keys of the object, even for arrays.

While own properties are possible, it is not advisable, because it could lead to lose some properties, if used with JSON.stringify more about disadvantage here: Is it good practice to add properties on array in javascript (still opinion-based).

var g = [{ age: 23 }, { age: 33 }];
g.foo = "bar";

console.log(Object.keys(g));
console.log(JSON.stringify(g));```

Body:
I recently found out that in the chrome console I was able to do something really unusual.

Here's a simple example using an array of objects.

g = [{age: 23}, {age:33}];

g.foo = "bar";
> (2) [{…}, {…}, foo: "bar"]

I think I'm able to do this because all js data structures are objects? Is there any way get access to foo:bar without knowing what it is beforehand?

g = g.filter(function(e){
          return e.age !== 33;
          });

> (2) [{…}]

Specifically I'm trying to filter an array, without losing the object attributes that I set like foo:"bar".

The filtered arrays I'm getting back do not contain the object attributes I had before.

So my question is what is the best way to get access to attributes that I set on an array object when I treat it like an object in this strange way?

Ideally I could run something(g) and get back {foo: 'bar'}, or a list of all the props that exist on this object that aren't related to the array aspect of it.

Or is this just a super hacky idea and I shouldn't do it like this in the first place?

Thanks!


问:
Count Number of Records in sqlite3 recordset
Problem: I was using sqlite 2.1 db with php using SQLiteDatabase object in PHP, now I am upgrading to sqlite 3.x, so also want to use SQLite3 in PHP, There is an issue i'm facing that is previously in SQLiteDatabase Object i was easily counting number of records return by querying to databse, but now with SQLite3 i am unable to do the same.

Sample Old Code with SQLiteDatabase:

```<code>$base= new SQLiteDatabase('users.db');
$query = 'select id from users';
$results = $base->query($query, SQLITE_ASSOC);
echo sizeof($results);
</code>```

Output this code generating

```<code>50
</code>```

Sample Old Code with New SQLite3:

```<code>$base = new SQLite3('users.db');
$query = 'select id from users';
$results = $base->query($query);
echo sizeof($results);
</code>```

But above code returns this:

```<code>1
</code>```

Instead of 50 it is showing 1,

Q: How i can calculate the number of rows in recordset($results) in SQLite3?

答:
I don't know the particualr API you're using, but chances are that $results there is holding just a "true" meaning that the query is being processed, I don't know how do you get your results, check your API. I think this is the link http://us.php.net/manual/en/book.pdo.php

apparently you have to do something similar to $rows->fetch(PDO::FETCH_OBJ)->rows; but in any case you need to fetch the results from the object.

Read your API.

Good luck

ContentLicense: CC BY-SA 2.5

Body:
Problem: I was using sqlite 2.1 db with php using SQLiteDatabase object in PHP, now I am upgrading to sqlite 3.x, so also want to use SQLite3 in PHP, There is an issue i'm facing that is previously in SQLiteDatabase Object i was easily counting number of records return by querying to databse, but now with SQLite3 i am unable to do the same.

Sample Old Code with SQLiteDatabase:

$base= new SQLiteDatabase('users.db');
$query = 'select id from users';
$results = $base->query($query, SQLITE_ASSOC);
echo sizeof($results);

Output this code generating

50

Sample Old Code with New SQLite3:

$base = new SQLite3('users.db');
$query = 'select id from users';
$results = $base->query($query);
echo sizeof($results);

But above code returns this:

1

Instead of 50 it is showing 1,

Q: How i can calculate the number of rows in recordset($results) in SQLite3?


问:
How do I include my company's global styles CDN (for dev use) using Webpack, within a Vue cli project?
I've tried importing via the entry file (main.js)...

```<code>import Vue from 'vue'
import App from '@/App'
import router from '@/router/router'
import store from '@/store/store'
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import { Popover } from 'bootstrap-vue/es/directives'
import 'https://mycompany/main.min.css'

Vue.use(BootstrapVue)
Vue.use(Popover)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: { App }
})
</code>```

I've tried to find a place within webpack.base.config (externals or publicPath) via numerous posts online - but none answered my question enough to make it work...

The css file delivered over the CDN essentially uses (and thus overwrites) Bootstrap classes, so it needs to be injected into the  after Bootstrap - can I do this with my current setup? Vue/Webpack.. or do i need a task runner like Gulp? It's not enough to inject the cdn once we've built the project and have dist files.. we need to see the style changes whilst dev's work on the project.
Is there an easier way than either of those 2 methods, and before anyone asks - no.. they won't make it an npm package due to privacy/security.

答:
One way to do it is directly handling the template used by HtmlWebpackPlugin.

First disable inject in build/webpack.prod.conf:

```<code>//...
new HtmlWebpackPlugin({
  //...
  inject: false,
  //...
})
//...
</code>```

And in your index.html:

```<code><!DOCTYPE html>
<html>

<head>
  <!-- ... -->
  <% if (process.env.NODE_ENV === 'production') { %>
    <% for (file of htmlWebpackPlugin.files.css) { %>
      <link rel="stylesheet" href="<%= file %>">
    <% } %>
    <link rel="stylesheet" href="https://mycompany/main.min.css">
  <% } %>
</head>

<body>
  <!-- ... -->
  <div id="app"></div>
  <% if (process.env.NODE_ENV !== 'production') { %>
    <!-- During development there's less of a problem with putting stylesheets in the body -->
     <link rel="stylesheet" href="https://mycompany/main.min.css">
  <% } else{ %>
    <% for (file of htmlWebpackPlugin.files.js) { %>
      <script src="<%= file %>" type="text/javascript"></script>
    <% } %>
  <% } %>
</body>

</html>
</code>```

What this does is inserting the static files manually, so you can choose the order, in production. During development, the link is written in the body tag, as then there isn't much of an issue with keeping standards.

Body:
I've tried importing via the entry file (main.js)...

import Vue from 'vue'
import App from '@/App'
import router from '@/router/router'
import store from '@/store/store'
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import { Popover } from 'bootstrap-vue/es/directives'
import 'https://mycompany/main.min.css'

Vue.use(BootstrapVue)
Vue.use(Popover)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: { App }
})

I've tried to find a place within webpack.base.config (externals or publicPath) via numerous posts online - but none answered my question enough to make it work...

The css file delivered over the CDN essentially uses (and thus overwrites) Bootstrap classes, so it needs to be injected into the  after Bootstrap - can I do this with my current setup? Vue/Webpack.. or do i need a task runner like Gulp? It's not enough to inject the cdn once we've built the project and have dist files.. we need to see the style changes whilst dev's work on the project.
Is there an easier way than either of those 2 methods, and before anyone asks - no.. they won't make it an npm package due to privacy/security.

Body:
One way to do it is directly handling the template used by HtmlWebpackPlugin.

First disable inject in build/webpack.prod.conf:

//...
new HtmlWebpackPlugin({
  //...
  inject: false,
  //...
})
//...

And in your index.html:

<!DOCTYPE html>
<html>

<head>
  <!-- ... -->
  <% if (process.env.NODE_ENV === 'production') { %>
    <% for (file of htmlWebpackPlugin.files.css) { %>
      <link rel="stylesheet" href="<%= file %>">
    <% } %>
    <link rel="stylesheet" href="https://mycompany/main.min.css">
  <% } %>
</head>

<body>
  <!-- ... -->
  <div id="app"></div>
  <% if (process.env.NODE_ENV !== 'production') { %>
    <!-- During development there's less of a problem with putting stylesheets in the body -->
     <link rel="stylesheet" href="https://mycompany/main.min.css">
  <% } else{ %>
    <% for (file of htmlWebpackPlugin.files.js) { %>
      <script src="<%= file %>" type="text/javascript"></script>
    <% } %>
  <% } %>
</body>

</html>

What this does is inserting the static files manually, so you can choose the order, in production. During development, the link is written in the body tag, as then there isn't much of an issue with keeping standards.


问:
Historical updates mysql node js
Hi I am using node JS with MYSQL and trying to see how historical updates work with node-mysql. I am facing a problem in which when I try to update a row with ID  in my table, I would like to get that row, update it with a new time stamp and then insert a new row with ID 2 but no update time stamp.

Example

```<code>ID | Owner | app | status | INSERT_DT           | UPDATE_DT
 1     11     Ok     1       2015-15-20 13:00:21 NULL
</code>```

Now when I update the above row by changing the status, it should be come

```<code>ID | Owner | app | status | INSERT_DT           | UPDATE_DT
 1     11     Ok     1       2015-15-20 13:00:21 20-15-20 12:00:12
 2     11     Ok     0       2015-15-20 12:00:12 | NULL
</code>```

So I get the row like this..

```<code>getUserPath = (Owner) => new Promise((resolve, reject) => {
    db.query('SELECT * from path where Owner = ?', Owner, function (error, results, fields) {
        if (error) {
            reject('Could not get user path');
        }
        resolve(results[0]);
    });
});
</code>```

The update below is where I am not sure how to update the whole row.
So the data includes all the information above

```<code>UpdateUserPath = (data) => new Promise((resolve,reject)=>{
data.INSERT_DT = '2015-15-20 12:00:12';
    db.query('UPDATE path set data', data , function(err,results,fields){
        if(err){
            reject('Could not update user path');
        }else{
            if(results.affectedRows > 0){
                //Making the new row
                data.ID = null;
                insertNewPath(data);
            }else{
                reject('Could not update user path');
            }
        }
    });
});
</code>```

The update statement returns me an error, and I am not sure how to get it working.
I am assuming the set needs me to manually let which fields to update, but I would not like to do that, I want it to happen all at once.

答:
you update statement is wrong. if you trying to update table above it should be:</p>

```<code>db.query('UPDATE path set ID=?, Owner=?, app=?, status=?, INSERT_DT=?, UPDATE_DT=?',[data.ID,data.Owner,data.app,data.status,data.insert_dt,data.update_dt] , function(err,results,fields){ ...
</code>```

Title: Historical updates mysql node js

Body:
Hi I am using node JS with MYSQL and trying to see how historical updates work with node-mysql. I am facing a problem in which when I try to update a row with ID  in my table, I would like to get that row, update it with a new time stamp and then insert a new row with ID 2 but no update time stamp.

Example

ID | Owner | app | status | INSERT_DT           | UPDATE_DT
 1     11     Ok     1       2015-15-20 13:00:21 NULL

Now when I update the above row by changing the status, it should be come

ID | Owner | app | status | INSERT_DT           | UPDATE_DT
 1     11     Ok     1       2015-15-20 13:00:21 20-15-20 12:00:12
 2     11     Ok     0       2015-15-20 12:00:12 | NULL

So I get the row like this..

getUserPath = (Owner) => new Promise((resolve, reject) => {
    db.query('SELECT * from path where Owner = ?', Owner, function (error, results, fields) {
        if (error) {
            reject('Could not get user path');
        }
        resolve(results[0]);
    });
});

The update below is where I am not sure how to update the whole row.
So the data includes all the information above

UpdateUserPath = (data) => new Promise((resolve,reject)=>{
data.INSERT_DT = '2015-15-20 12:00:12';
    db.query('UPDATE path set data', data , function(err,results,fields){
        if(err){
            reject('Could not update user path');
        }else{
            if(results.affectedRows > 0){
                //Making the new row
                data.ID = null;
                insertNewPath(data);
            }else{
                reject('Could not update user path');
            }
        }
    });
});

The update statement returns me an error, and I am not sure how to get it working.
I am assuming the set needs me to manually let which fields to update, but I would not like to do that, I want it to happen all at once.

Body:
you update statement is wrong. if you trying to update table above it should be:

db.query('UPDATE path set ID=?, Owner=?, app=?, status=?, INSERT_DT=?, UPDATE_DT=?',[data.ID,data.Owner,data.app,data.status,data.insert_dt,data.update_dt] , function(err,results,fields){ ...


答:
You can always break these out into a simple array if you're not passing in any arguments. A minimal example looks like:</p>

```<code>TESTS = [ :a?, :b?, :c? ]

def parent_method
  failed = TESTS.find do |test|
    !send(test)
  end

  if (failed)
    # The failed variable contains the name of the method that failed
    # to return `true`. Do whatever you need to do here.
    errors << "Test #{failed} returned false!"

    false
  else
    true
  end
end
</code>```

Title: Evaluating list of boolean methods ruby

Body:
You can always break these out into a simple array if you're not passing in any arguments. A minimal example looks like:

TESTS = [ :a?, :b?, :c? ]

def parent_method
  failed = TESTS.find do |test|
    !send(test)
  end

  if (failed)
    # The failed variable contains the name of the method that failed
    # to return `true`. Do whatever you need to do here.
    errors << "Test #{failed} returned false!"

    false
  else
    true
  end
end


问:
Converting a list of strings to a list of int for machine learning
I have a table with a column corresponding to the education level : "phd", "undergrad", etc.

I would like to change those features to 0, 1, 2..... in order to use the data as an input of a machine learning algorithm.

Is there a way in Python to automatically map those string features to integers?

答:
You can use enumerate if you want to have the same serial order.

```<code>lista = [ "phd", "undergrad", "etc"]
>>> [i for i in enumerate(lista)]
[(0, 'phd'), (1, 'undergrad'), (2, 'etc')]
</code>```

Body:
You can use enumerate if you want to have the same serial order.

lista = [ "phd", "undergrad", "etc"]
>>> [i for i in enumerate(lista)]
[(0, 'phd'), (1, 'undergrad'), (2, 'etc')]


问:
bash awk moving average with skipping
I am trying to calculate a moving average with a data set. But in addition, I want it to skip a few number of data each time the average 'window' moves. For example, if my data set is a column from 1 to 20 and my average window is 5, then the current calculation is the average of (1-5), (2-6), (3-7), (4-8).....
But I want to skip a few data each time the window moves, say I want to skip 2. then the new average will be (1-5), (4-8), (6-10), (8-12)......
Here is the current awk file I am using, can anyone help me edit it so that I can skip a few data each time the window moves? I want to change the skip size and window size as well. Thank you very much!</p>

```<code>#!/bin/awk

BEGIN {
    N=5          # the window size
}
{
    n[NR]=$1       # store the value in an array
}
NR>=N {            # for records where NR >= N
    x=0            # reset the sum variable
    delete n[NR-N] # delete the one out the window of N
    for(i in n)    # all array elements
        x+=n[i]    # ... must be summed
    print x/N  # print the row from the beginning of window
}
</code>```

答:
I see that you want to print MA every K ticks instead of printing for every tick (K=1). So you could add a condition NR%K==0 before printing in your existing code.

But it would be better to keep an array of N elements and overwrite them instead of deleting. Using NR%N as array index. This way, when K is not 1 and want not to calculate the MA, you will avoid checking how many elements to delete etc.

```<code>awk -v n=5 -v k=2       '{ a[NR%n]=$0 }
    NR>=n && (NR-n)%k==0 { s=0; for (i in a) s+=a[i]; print NR ":\t" s/n }' file
</code>```

update condition to (NR-n)%k==0 for always starting from first tick where MA is calculated (that is for NR=n).

Title: bash awk moving average with skipping

Body:
I am trying to calculate a moving average with a data set. But in addition, I want it to skip a few number of data each time the average 'window' moves. For example, if my data set is a column from 1 to 20 and my average window is 5, then the current calculation is the average of (1-5), (2-6), (3-7), (4-8).....
But I want to skip a few data each time the window moves, say I want to skip 2. then the new average will be (1-5), (4-8), (6-10), (8-12)......
Here is the current awk file I am using, can anyone help me edit it so that I can skip a few data each time the window moves? I want to change the skip size and window size as well. Thank you very much!

#!/bin/awk

BEGIN {
    N=5          # the window size
}
{
    n[NR]=$1       # store the value in an array
}
NR>=N {            # for records where NR >= N
    x=0            # reset the sum variable
    delete n[NR-N] # delete the one out the window of N
    for(i in n)    # all array elements
        x+=n[i]    # ... must be summed
    print x/N  # print the row from the beginning of window
}

Body:
I see that you want to print MA every K ticks instead of printing for every tick (K=1). So you could add a condition NR%K==0 before printing in your existing code.

But it would be better to keep an array of N elements and overwrite them instead of deleting. Using NR%N as array index. This way, when K is not 1 and want not to calculate the MA, you will avoid checking how many elements to delete etc.

awk -v n=5 -v k=2       '{ a[NR%n]=$0 }
    NR>=n && (NR-n)%k==0 { s=0; for (i in a) s+=a[i]; print NR ":\t" s/n }' file

update condition to (NR-n)%k==0 for always starting from first tick where MA is calculated (that is for NR=n).


问:
base class with abstract method returning T
I am defining a base class that has a method that returns type T. The classes the derive from this can return different types.

```<code>public abstract class BaseTransport
{
    public abstract T Properties<T>();
}

public class Car : BaseTransport
{
    public override T Properties<T>()
    {
       return new CarProperties();
    }
}

public class Bike : BaseTransport
{
    public override T Properties<T>()
    {
       return new BikeProperties();
    }
}
</code>```

If it makes a difference the return BikeProperties and CarProperties are both derived from BaseProperties.

Is this possible to do? Just trying to enforce the implementation of a method...

答:
You don't want generic methods, you want a generic class:</p>

```<code>public abstract class BaseTransport<T> where T : BaseProperties
{
    public abstract T Properties();
}

public class Car : BaseTransport<CarProperties>
{
    public override CarProperties Properties()
    {
       return new CarProperties();
    }
}

public class Bike : BaseTransport<BikeProperties>
{
    public override BikeProperties Properties()
    {
       return new BikeProperties();
    }
}
</code>```

Body:
I am defining a base class that has a method that returns type T. The classes the derive from this can return different types.

public abstract class BaseTransport
{
    public abstract T Properties<T>();
}

public class Car : BaseTransport
{
    public override T Properties<T>()
    {
       return new CarProperties();
    }
}

public class Bike : BaseTransport
{
    public override T Properties<T>()
    {
       return new BikeProperties();
    }
}

If it makes a difference the return BikeProperties and CarProperties are both derived from BaseProperties.

Is this possible to do? Just trying to enforce the implementation of a method...

Body:
You don't want generic methods, you want a generic class:

public abstract class BaseTransport<T> where T : BaseProperties
{
    public abstract T Properties();
}

public class Car : BaseTransport<CarProperties>
{
    public override CarProperties Properties()
    {
       return new CarProperties();
    }
}

public class Bike : BaseTransport<BikeProperties>
{
    public override BikeProperties Properties()
    {
       return new BikeProperties();
    }
}


问:
How to import headers recusively in Objective-C
Ok this is probably a silly question but why can I do something like this:

```<code>objectA.h

#import <objectB>
#import <objectC>

objectA.m

#import <ObjectA.h>
</code>```

And in ObjectA.m have access to ObjectB and OBjectC definition ?
It's silly to have to import everything you use in each implementation file.
Am i missing something obvious ?

答:
You can do this, and it can occasionally make sense -- provided that the definitions are coupled in such a way that they genuinely belong together.

What you shouldn't do is introduce bogus compilation dependencies just to save a few keystrokes in some implementation file.

Body:
Ok this is probably a silly question but why can I do something like this:

objectA.h

#import <objectB>
#import <objectC>

objectA.m

#import <ObjectA.h>

And in ObjectA.m have access to ObjectB and OBjectC definition ?
It's silly to have to import everything you use in each implementation file.
Am i missing something obvious ?


问:
Using other app to send message to line app
I try the following code to send messages to line app. It works; however, before I send message,it will move to the line friends page and I have to choose friends whom I want to send the messages to. How could I modify the code that I could choose friends  at code instead of choosing friends manually.

```<code>public class MainActivity extends AppCompatActivity {

static final int REQUEST_ACTION_PICK = 1;
public static final String PACKAGE_NAME = "jp.naver.line.android";
public static final String CLASS_NAME = "jp.naver.line.android.activity.selectchat.SelectChatActivity";
private List<ApplicationInfo> m_appList;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sendTextHandler(this);
}

public void sendTextHandler(MainActivity view) {
    String sendText = ((TextView)findViewById(R.id.send_text)).getText().toString();
    if(checkLineInstalled()){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setClassName(PACKAGE_NAME, CLASS_NAME);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, sendText);
        startActivity(intent);
    }else{
        Toast toast = Toast.makeText(this, "LINEがインストールされていません", Toast.LENGTH_SHORT);
        toast.show();
    }
}
private boolean checkLineInstalled(){
    PackageManager pm = getPackageManager();
    m_appList = pm.getInstalledApplications(0);
    boolean lineInstallFlag = false;
    for (ApplicationInfo ai : m_appList) {
        if(ai.packageName.equals(PACKAGE_NAME)){
            lineInstallFlag = true;
            break;
        }
    }
    return lineInstallFlag;
}

}
</code>```

The code is from https://gist.github.com/ekos/3993270.

答:
If you want to be able to open a specific user based on the ID you can do the following:

```<code>String userId = findUserId();
String sendText = "line://ti/p/~" + userId;
Intent intent = null;
try {
    intent = Intent.parseUri(sendText, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
    e.printStackTrace();
}
startActivity(intent);
</code>```

If you want to make a message and then be able to choose who to send it to you can use the following:

```<code>Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("line://msg/text/" + getMessage()));
startActivity(intent);
</code>```

Body:
I try the following code to send messages to line app. It works; however, before I send message,it will move to the line friends page and I have to choose friends whom I want to send the messages to. How could I modify the code that I could choose friends  at code instead of choosing friends manually.

public class MainActivity extends AppCompatActivity {

static final int REQUEST_ACTION_PICK = 1;
public static final String PACKAGE_NAME = "jp.naver.line.android";
public static final String CLASS_NAME = "jp.naver.line.android.activity.selectchat.SelectChatActivity";
private List<ApplicationInfo> m_appList;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sendTextHandler(this);
}

public void sendTextHandler(MainActivity view) {
    String sendText = ((TextView)findViewById(R.id.send_text)).getText().toString();
    if(checkLineInstalled()){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setClassName(PACKAGE_NAME, CLASS_NAME);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, sendText);
        startActivity(intent);
    }else{
        Toast toast = Toast.makeText(this, "LINEがインストールされていません", Toast.LENGTH_SHORT);
        toast.show();
    }
}
private boolean checkLineInstalled(){
    PackageManager pm = getPackageManager();
    m_appList = pm.getInstalledApplications(0);
    boolean lineInstallFlag = false;
    for (ApplicationInfo ai : m_appList) {
        if(ai.packageName.equals(PACKAGE_NAME)){
            lineInstallFlag = true;
            break;
        }
    }
    return lineInstallFlag;
}

}

The code is from https://gist.github.com/ekos/3993270.

Body:
If you want to be able to open a specific user based on the ID you can do the following:

String userId = findUserId();
String sendText = "line://ti/p/~" + userId;
Intent intent = null;
try {
    intent = Intent.parseUri(sendText, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
    e.printStackTrace();
}
startActivity(intent);

If you want to make a message and then be able to choose who to send it to you can use the following:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("line://msg/text/" + getMessage()));
startActivity(intent);


问:
How to disable Hybrid Shutdown in Windows with a Command Line
How to disable Hybrid Shutdown in Windows with a Command Line.

I am using a ramdisk (with imdisk software), after the upgrade from Windows 8.1 pro into Windows 10 pro - The Computer does Save automatic My Ramdisk to My Hard Disk everytime if i Shutdown my Windows, i do not want that. (The ramdisk Size is to Big [2GB] and i want to use it with a clean ramdisk).

Is it Maybe possible that i have Two msdos commanding scripts On my Desktop.(Other Languages like autohotkey or Python is for me also ok.)

The Scripts must can do this.

```<code>1 - Disable Hybrid and then Shutdown Windows.

2 - Enable Hybrid and then Shutdown Windows.
</code>```

答:
You can use these msdos bat files:

1 - HybridOn_ShutDown.bat

This will save the Whole Ram memory to your HardDisk (MemoryFile),
and then it will ShutDown Windows. The next time that you will start up your Computer, it Will Load your (MemoryFile) into the Ram Memory - The Pros are:The Computer will Startup Faster and it will remember all your data + Including the Ramdisk data.

```<code>@echo off
powercfg /h on
shutdown /h
</code>```

2 - HybridOff_ShutDown.bat

This Will Shutdown Windows Without Saving The Ram Memory to your HardDisk. The next time that you will start up your Computer, it will do a Clean/Fresh Windows Start up + With a Clean/Fresh Ramdisk Start up.

```<code>@echo off
powercfg /h off
shutdown /p /f
</code>```

note - This works only if you run the bat files (as administrator)

And If you want to run it direct you can use:

Method 2: Converting the .BAT files into .EXE files with Admin Manifest added.

Click Here and Read Method 2:

Body:
How to disable Hybrid Shutdown in Windows with a Command Line.

I am using a ramdisk (with imdisk software), after the upgrade from Windows 8.1 pro into Windows 10 pro - The Computer does Save automatic My Ramdisk to My Hard Disk everytime if i Shutdown my Windows, i do not want that. (The ramdisk Size is to Big [2GB] and i want to use it with a clean ramdisk).

Is it Maybe possible that i have Two msdos commanding scripts On my Desktop.(Other Languages like autohotkey or Python is for me also ok.)

The Scripts must can do this.

1 - Disable Hybrid and then Shutdown Windows.

2 - Enable Hybrid and then Shutdown Windows.

Body:
You can use these msdos bat files:

1 - HybridOn_ShutDown.bat

This will save the Whole Ram memory to your HardDisk (MemoryFile),
and then it will ShutDown Windows. The next time that you will start up your Computer, it Will Load your (MemoryFile) into the Ram Memory - The Pros are:The Computer will Startup Faster and it will remember all your data + Including the Ramdisk data.

@echo off
powercfg /h on
shutdown /h

2 - HybridOff_ShutDown.bat

This Will Shutdown Windows Without Saving The Ram Memory to your HardDisk. The next time that you will start up your Computer, it will do a Clean/Fresh Windows Start up + With a Clean/Fresh Ramdisk Start up.

@echo off
powercfg /h off
shutdown /p /f

note - This works only if you run the bat files (as administrator)

And If you want to run it direct you can use:

Method 2: Converting the .BAT files into .EXE files with Admin Manifest added.

Click Here and Read Method 2:


问:
.Net Core Kafka ProduceAsync doesn't complete
I'm trying to make a proof of concept, simple Kafka producer and consumer. The platform I'm using is .Net Core 2.0, built by Visual Studio 2017. The Nuget Package I'm using is Confluent.Kafka

I've found some code through research that has had the best success, but now it seems to have trouble when implementing a .ProduceAsync() method. No error codes appear, and the program seems to continue to run, but otherwise doesn't execute the method.

Here is my Producer:

```<code>class Producer
    {
        static void Main(string[] args)
        {
            Console.WriteLine("PRODUCER!!!");

            // The Kafka endpoint address
            string kafkaEndpoint = "127.0.0.1:9092";

            // The Kafka topic we'll be using
            string kafkaTopic = "testtopic";

            // Create the producer configuration
            var producerConfig = new Dictionary<string, object> { { "bootstrap.servers", kafkaEndpoint } };

            // Create the producer
            using (var producer = new Producer<Null, string>(producerConfig, null, new StringSerializer(Encoding.UTF8)))
            {
                Console.WriteLine("Producer Created!");
                // Send 10 messages to the topic
                for (int i = 0; i < 10; i++)
                {
                    var message = $"Event {i}";
                    Console.WriteLine($"Begin Event {i}");
                    var result = producer.ProduceAsync(kafkaTopic, null, message).GetAwaiter().GetResult();
                    Console.WriteLine($"Event {i} sent on Partition: {result.Partition} with Offset: {result.Offset}");
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadLine();
                }
            }
        }
    }
</code>```

And here is my Consumer:

```<code>class Consumer
    {
        static void Main(string[] args)
        {
            Console.WriteLine("CONSUMER!!!");

            // The Kafka endpoint address
            string kafkaEndpoint = "127.0.0.1:9092";

            // The Kafka topic we'll be using
            string kafkaTopic = "testtopic";

            // Create the consumer configuration
            var consumerConfig = new Dictionary<string, object>
            {
                { "group.id", "myconsumer" },
                { "bootstrap.servers", kafkaEndpoint },
            };

            // Create the consumer
            using (var consumer = new Consumer<Null, string>(consumerConfig, null, new StringDeserializer(Encoding.UTF8)))
            {
                // Subscribe to the OnMessage event
                consumer.OnMessage += (obj, msg) =>
                {
                    Console.WriteLine($"Received: {msg.Value}");
                };

                // Subscribe to the Kafka topic
                consumer.Subscribe(new List<string>() { kafkaTopic });

                // Handle Cancel Keypress
                var cancelled = false;
                Console.CancelKeyPress += (_, e) =>
                {
                    e.Cancel = true; // prevent the process from terminating.
                    cancelled = true;
                };

                Console.WriteLine("Ctrl-C to exit.");

                // Poll for messages
                while (!cancelled)
                {
                    consumer.Poll(3000);
                    //consumer.Poll();
                }
            }
        }
    }
</code>```

As I run the code, the Consumer sits idle because it appears that no messages are produced, but here is my console output for the Producer:

```<code>PRODUCER!!!
Producer Created!
Begin Event 0
</code>```

(And that's it. Console also sits idle at this point.)

The question is: How can this be fixed so that the messages are in fact produced, and so that the consumer can receive them?

答:
You can force to get the result by changing the line in producer to:

```<code>var result = producer.ProduceAsync(kafkaTopic, null, message).Result;
</code>```

Check the result contents to find what went wrong.

Body:
I'm trying to make a proof of concept, simple Kafka producer and consumer. The platform I'm using is .Net Core 2.0, built by Visual Studio 2017. The Nuget Package I'm using is Confluent.Kafka

I've found some code through research that has had the best success, but now it seems to have trouble when implementing a .ProduceAsync() method. No error codes appear, and the program seems to continue to run, but otherwise doesn't execute the method.

Here is my Producer:

class Producer
    {
        static void Main(string[] args)
        {
            Console.WriteLine("PRODUCER!!!");

            // The Kafka endpoint address
            string kafkaEndpoint = "127.0.0.1:9092";

            // The Kafka topic we'll be using
            string kafkaTopic = "testtopic";

            // Create the producer configuration
            var producerConfig = new Dictionary<string, object> { { "bootstrap.servers", kafkaEndpoint } };

            // Create the producer
            using (var producer = new Producer<Null, string>(producerConfig, null, new StringSerializer(Encoding.UTF8)))
            {
                Console.WriteLine("Producer Created!");
                // Send 10 messages to the topic
                for (int i = 0; i < 10; i++)
                {
                    var message = $"Event {i}";
                    Console.WriteLine($"Begin Event {i}");
                    var result = producer.ProduceAsync(kafkaTopic, null, message).GetAwaiter().GetResult();
                    Console.WriteLine($"Event {i} sent on Partition: {result.Partition} with Offset: {result.Offset}");
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadLine();
                }
            }
        }
    }

And here is my Consumer:

class Consumer
    {
        static void Main(string[] args)
        {
            Console.WriteLine("CONSUMER!!!");

            // The Kafka endpoint address
            string kafkaEndpoint = "127.0.0.1:9092";

            // The Kafka topic we'll be using
            string kafkaTopic = "testtopic";

            // Create the consumer configuration
            var consumerConfig = new Dictionary<string, object>
            {
                { "group.id", "myconsumer" },
                { "bootstrap.servers", kafkaEndpoint },
            };

            // Create the consumer
            using (var consumer = new Consumer<Null, string>(consumerConfig, null, new StringDeserializer(Encoding.UTF8)))
            {
                // Subscribe to the OnMessage event
                consumer.OnMessage += (obj, msg) =>
                {
                    Console.WriteLine($"Received: {msg.Value}");
                };

                // Subscribe to the Kafka topic
                consumer.Subscribe(new List<string>() { kafkaTopic });

                // Handle Cancel Keypress
                var cancelled = false;
                Console.CancelKeyPress += (_, e) =>
                {
                    e.Cancel = true; // prevent the process from terminating.
                    cancelled = true;
                };

                Console.WriteLine("Ctrl-C to exit.");

                // Poll for messages
                while (!cancelled)
                {
                    consumer.Poll(3000);
                    //consumer.Poll();
                }
            }
        }
    }

As I run the code, the Consumer sits idle because it appears that no messages are produced, but here is my console output for the Producer:

PRODUCER!!!
Producer Created!
Begin Event 0

(And that's it. Console also sits idle at this point.)

The question is: How can this be fixed so that the messages are in fact produced, and so that the consumer can receive them?

Body:
You can force to get the result by changing the line in producer to:

var result = producer.ProduceAsync(kafkaTopic, null, message).Result;

Check the result contents to find what went wrong.


问:
get an array of objects from php using Volley
I have php file that return a list of objects from database.
this is the php code:

```<code><?php
require_once('../connect.php');

$sql = "SELECT * FROM categories";
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $mydata = $json->addChild('category');
        $mydata->addChild('id',$row['id']);
        $mydata->addChild('name',$row['Name']);
         }
} else {
    echo "0 results";
}
$conn->close();
     echo( json_encode ($json));
?>
</code>```

and this is the result:

{"category":[{"id":"1","name":"test"},{"id":"2","name":"test2"}]}

Now i want to get the list of categories in android, i tried to do it using this code but it always return empty list:

```<code>   public List<Category> getAllCategories(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://localhost/Android/Categories/Select_All_Categories" ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("TAG","response :"+response);
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray sts = null;
                            sts = jsonObject.getJSONArray("category");

                            for (int i = 0; i < sts.length(); i++) {
                                JSONObject jo = sts.getJSONObject(i);
                                Category cc = new Category();
                                cc.setId(jo.getInt("id"));
                                cc.setName(jo.getString("name"));
                                ar.add(cc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });

        return ar;
    }
</code>```

can someone please help me and tell me what I am doing wrong?

Update for diegoveloper: this is the code i used in my main.

```<code>MyListener listener = new MyListener() {
    @Override
    public void returnYourData(List<Category> list) {
        for(Category c:list){
            lc.add(c);
        }
    }

    @Override
    public void returnError() {

    }
};

System.out.println(lc.size());
</code>```

答:
Check your server response 1st. Run your php manually, using your browser. Then get its json response. If its empty or error, problem in your server or php. Sometimes those type of things happen in local host by blocking ports & etc. If it has a json array. use below methods to get its data. Those methods work perfect for me, I used in many applications.</p>

```<code> RequestQueue rq; //assign as a global variable
 String json_string; //assign as a global variable
 String url = "http://yourphpfilelink.php"; //assign as a global variable

protected void onCreate(Bundle savedInstanceState) { //call below functions inside oncreate

        rq = Volley.newRequestQueue(this);
        sendjsonrequest();
}

    public void sendjsonrequest(){
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            //json_string = response.getString("server_response");
                            jsonget(response);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                        }});
                    rq.add(jsonObjectRequest);
                }

             public void jsonget(JSONObject json_string1){
                        try {
                            JSONArray jsonArray = json_string1.getJSONArray("server_response");
                            int count = 0;
                            String name1,name2,name3;
                            msg="";
                            while (count<jsonArray.length()){
                                JSONObject JO = jsonArray.getJSONObject(count);
                                name1 = JO.getString("name1");
                                name2 = JO.getString("name2");
                                name3 = JO.getString("name3");
                                msg = msg+"name1: " + name1 + "\nname2: "+ name2 + "\nname3: " + name3 + "C\n\n";
                                count++;        }
                            yourtextview.setText(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();  }
                    }
</code>```

Body:
I have php file that return a list of objects from database.
this is the php code:

<?php
require_once('../connect.php');

$sql = "SELECT * FROM categories";
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $mydata = $json->addChild('category');
        $mydata->addChild('id',$row['id']);
        $mydata->addChild('name',$row['Name']);
         }
} else {
    echo "0 results";
}
$conn->close();
     echo( json_encode ($json));
?>

and this is the result:

{"category":[{"id":"1","name":"test"},{"id":"2","name":"test2"}]}

Now i want to get the list of categories in android, i tried to do it using this code but it always return empty list:

   public List<Category> getAllCategories(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://localhost/Android/Categories/Select_All_Categories" ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("TAG","response :"+response);
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray sts = null;
                            sts = jsonObject.getJSONArray("category");

                            for (int i = 0; i < sts.length(); i++) {
                                JSONObject jo = sts.getJSONObject(i);
                                Category cc = new Category();
                                cc.setId(jo.getInt("id"));
                                cc.setName(jo.getString("name"));
                                ar.add(cc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });

        return ar;
    }

can someone please help me and tell me what I am doing wrong?

Update for diegoveloper: this is the code i used in my main.

MyListener listener = new MyListener() {
    @Override
    public void returnYourData(List<Category> list) {
        for(Category c:list){
            lc.add(c);
        }
    }

    @Override
    public void returnError() {

    }
};

System.out.println(lc.size());

Body:
Check your server response 1st. Run your php manually, using your browser. Then get its json response. If its empty or error, problem in your server or php. Sometimes those type of things happen in local host by blocking ports & etc. If it has a json array. use below methods to get its data. Those methods work perfect for me, I used in many applications.

 RequestQueue rq; //assign as a global variable
 String json_string; //assign as a global variable
 String url = "http://yourphpfilelink.php"; //assign as a global variable

protected void onCreate(Bundle savedInstanceState) { //call below functions inside oncreate

        rq = Volley.newRequestQueue(this);
        sendjsonrequest();
}

    public void sendjsonrequest(){
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            //json_string = response.getString("server_response");
                            jsonget(response);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                        }});
                    rq.add(jsonObjectRequest);
                }

             public void jsonget(JSONObject json_string1){
                        try {
                            JSONArray jsonArray = json_string1.getJSONArray("server_response");
                            int count = 0;
                            String name1,name2,name3;
                            msg="";
                            while (count<jsonArray.length()){
                                JSONObject JO = jsonArray.getJSONObject(count);
                                name1 = JO.getString("name1");
                                name2 = JO.getString("name2");
                                name3 = JO.getString("name3");
                                msg = msg+"name1: " + name1 + "\nname2: "+ name2 + "\nname3: " + name3 + "C\n\n";
                                count++;        }
                            yourtextview.setText(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();  }
                    }


问:
Regarding p2p connection and c#
i just want to know how two application interact with each other across the internet. how one send some message to other one because when IP is not fixed. please give me some coding tips by which a p2p apps connect other one across the internet when IP is not known.

please help me in detail.

答: Usually this would happen via some sort of directory hosted on a server in a known location.</p>

Title: Regarding p2p connection and c#


问:
Retaining a field value when the value includes to other values from a separate field
Imagine that we are a health plan and we have a database that records all of the claim line details for every claim a provider bills to us. I want to identify claim ids that were billed with two specific procedure codes. Here is a dummy dataset:

```<code>val df = Seq(
        ("153T32", "D0201"),
        ("153T32", "D3303"),
        ("153T32", "F2303"),
        ("421F32", "D0200"),
        ("421F32", "D1111"),
        ("421F32", "D0201"),
        ("991E32", "D0201"),
        ("991E32", "F2303"),
        ("991E32", "A1123"),
        ("529E52", "G1029"),
        ("529E52", "B0392")).
    toDF("claim_id", "code")
</code>```

In this fake example, I want to identify the claim_id values that are associated with both code === "D0201" and code === "F2303". I figured out how to do this creating two new DataFrames where each is filtered on one of the code values and then inner joining them together. But if there is a way to do this without creating to intermediary DataFrames, then I would like to see how you all would do it.

Here is my current solution:

```<code>val df1 = df.where($"code" === "D0201")
val df2 = df.where($"code" === "F2303")
val joinExpr = df1.col("claim_id") === df2.col("claim_id")

val finalDF = df1.join(df2, joinExpr, "inner").select(df1.col("claim_id"))

finalDF.show()
+--------+
|claim_id|
+--------+
|  153T32|
|  991E32|
+--------+
</code>```

答:
Assume there are no duplicated rows in the original data frame, here is one approach without joining:</p>

```<code>(df.where($"code".isin("D0201", "F2303"))
   .groupBy("claim_id").agg(count($"code").as("cnt"))
   .where($"cnt" === 2).select("claim_id")
).show
+--------+
|claim_id|
+--------+
|  153T32|
|  991E32|
+--------+
</code>```

Body:
Imagine that we are a health plan and we have a database that records all of the claim line details for every claim a provider bills to us. I want to identify claim ids that were billed with two specific procedure codes. Here is a dummy dataset:

val df = Seq(
        ("153T32", "D0201"),
        ("153T32", "D3303"),
        ("153T32", "F2303"),
        ("421F32", "D0200"),
        ("421F32", "D1111"),
        ("421F32", "D0201"),
        ("991E32", "D0201"),
        ("991E32", "F2303"),
        ("991E32", "A1123"),
        ("529E52", "G1029"),
        ("529E52", "B0392")).
    toDF("claim_id", "code")

In this fake example, I want to identify the claim_id values that are associated with both code === "D0201" and code === "F2303". I figured out how to do this creating two new DataFrames where each is filtered on one of the code values and then inner joining them together. But if there is a way to do this without creating to intermediary DataFrames, then I would like to see how you all would do it.

Here is my current solution:

val df1 = df.where($"code" === "D0201")
val df2 = df.where($"code" === "F2303")
val joinExpr = df1.col("claim_id") === df2.col("claim_id")

val finalDF = df1.join(df2, joinExpr, "inner").select(df1.col("claim_id"))

finalDF.show()
+--------+
|claim_id|
+--------+
|  153T32|
|  991E32|
+--------+

Body:
Assume there are no duplicated rows in the original data frame, here is one approach without joining:

(df.where($"code".isin("D0201", "F2303"))
   .groupBy("claim_id").agg(count($"code").as("cnt"))
   .where($"cnt" === 2).select("claim_id")
).show
+--------+
|claim_id|
+--------+
|  153T32|
|  991E32|
+--------+