问:
Java Array vs Array List
Java array vs Java ArrayList: I wrote a program to compare the time it takes to store a Java array and ArrayList of size MAX with random numbers. Are these results coming out right? Is ArrayList supposed to be faster?

```<code>package arraylists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;

public class arraylists {

    public final static int MAX = 10000;
    static Random rand = new Random();
    static int rand_int1 = rand.nextInt(1000);
    static int rand_int2 = rand.nextInt(1000);

    public static void arrayFunc(int a1 ) {

        int [] arry = new int[a1];

        for(int i = 0; i < a1; i++) {
            arry[i] =  rand_int1;
        }

    }

    public static void arrayList(int a2) {

        ArrayList<Integer> num = new ArrayList<Integer>();

        for(int i = 0; i < a2; i++) {
            num.add(rand_int2);
        }

}

    public static void main(String args[]) {

        for(int i = 0; i < 10; i++){
            int num;
            System.out.println("Enter the number of iterations: ");
            Scanner input = new Scanner(System.in);
            num = input.nextInt();

            long start1 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end1 = System.nanoTime();
            long timeElapsed1 = end1 - start1;

            long start2 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end2 = System.nanoTime();
            long timeElapsed2 = end2 - start2;

            System.out.println("Java Array execution time (in nanonseconds): " + timeElapsed1);
            System.out.println("Java Array List execution time (in nanoseconds): " + timeElapsed2);
        }

    }

}
</code>```

Java Array vs Java Array List: I wrote a program to compare the time it takes to store a java array and array list of size MAX with random numbers, are these numbers coming out right? is array list suppose to be faster?

答:
ArrayList is backed by an array (plus the logic to create a new array and migrate references when the list outgrow the array).

So, array is faster but it has a lower level interface, you have to manage the size and manage to update the indexes when you remove or insert in the middle of the list.

Unless required, or you are doing really low level programming, stick with the List interface.

Title: Java Array vs Array List

Body:
Java array vs Java ArrayList: I wrote a program to compare the time it takes to store a Java array and ArrayList of size MAX with random numbers. Are these results coming out right? Is ArrayList supposed to be faster?

package arraylists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;

public class arraylists {

    public final static int MAX = 10000;
    static Random rand = new Random();
    static int rand_int1 = rand.nextInt(1000);
    static int rand_int2 = rand.nextInt(1000);

    public static void arrayFunc(int a1 ) {

        int [] arry = new int[a1];

        for(int i = 0; i < a1; i++) {
            arry[i] =  rand_int1;
        }

    }

    public static void arrayList(int a2) {

        ArrayList<Integer> num = new ArrayList<Integer>();

        for(int i = 0; i < a2; i++) {
            num.add(rand_int2);
        }

}

    public static void main(String args[]) {

        for(int i = 0; i < 10; i++){
            int num;
            System.out.println("Enter the number of iterations: ");
            Scanner input = new Scanner(System.in);
            num = input.nextInt();

            long start1 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end1 = System.nanoTime();
            long timeElapsed1 = end1 - start1;

            long start2 = System.nanoTime();

            for(int j = 0; j < num; j++) {

                arrayFunc(MAX);

            }

            long end2 = System.nanoTime();
            long timeElapsed2 = end2 - start2;

            System.out.println("Java Array execution time (in nanonseconds): " + timeElapsed1);
            System.out.println("Java Array List execution time (in nanoseconds): " + timeElapsed2);
        }

    }

}

Java Array vs Java Array List: I wrote a program to compare the time it takes to store a java array and array list of size MAX with random numbers, are these numbers coming out right? is array list suppose to be faster?


来源: stackexchange

问:
AnyChart android refreshing a chart
I am using anychart library for android to display a pie chart, it gets the data from a mysql using volley and a node JS api to facilitate the crud operation

I am just facing a problem refresing the chart when new data is available from the data base.
I used Log.d to make sure the data is actually being updated it, I checked anycharts github and tried the solutions they listed, mainly that I just need to set the data again with the new data, that didn't work
Please any help is greatly appreciated.
I even tried creating a button and try to set the graph with complety new and hardcoded data. but that didn't work, I tried to use gone and visible and that didn't work

here is my code:

```<code> package com.dana.baizaty_frontend.fragments

import Transaction
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.anychart.APIlib
import com.anychart.AnyChart
import com.anychart.AnyChartView
import com.anychart.chart.common.dataentry.DataEntry
import com.anychart.chart.common.dataentry.ValueDataEntry
import com.anychart.enums.Align
import com.anychart.enums.LegendLayout
import com.dana.baizaty_frontend.R
import com.dana.baizaty_frontend.singleton.AppSingleton
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_pfm.*

class PFM : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

//        val anyChartView: AnyChartView? = any_chart_view

        // Inflate the layout for this fragment
//        createChart()

        var v = inflater.inflate(R.layout.fragment_pfm, container, false)

        return v

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        getTransactions()
        button.setOnClickListener{
            updateChart()
        }

    }

    override fun onStart() {

        super.onStart()
        getTransactions()

        Toast.makeText(context, "testing", "testing".length).show()
    }
    fun createChart (data1: MutableList<DataEntry>
    ) {
//        var anyChartView: AnyChartView? = any_chart_view

//        APIlib.getInstance().setActiveAnyChartView(any_chart_view)
//        any_chart_view.clear()
        any_chart_view.visibility=View.GONE

        any_chart_view.setProgressBar(progress_bar)
        var pie = AnyChart.pie3d()
//        anyChartView?.setProgressBar(progress_bar)

//        data.add(ValueDataEntry("Restarant", 30))
//        data.add(ValueDataEntry("transportation", 23))
//        data.add(ValueDataEntry("cafe", 10))
        Log.d("catagor3",data1.toString())

        pie.data(data1)
        pie.title("spending")
        pie.labels().position("outside")
        pie.legend().title().enabled(true)

        pie.legend()
            .position("center-bottom")
            .itemsLayout(LegendLayout.HORIZONTAL)
            .align(Align.CENTER);

        any_chart_view?.setChart(pie);
        any_chart_view.visibility=View.VISIBLE
        data1.clear()

    }
    fun updateChart(){
        var data1 = mutableListOf<DataEntry>()
        data1.add(ValueDataEntry("Restarant", 30))
        data1.add(ValueDataEntry("transportation", 23))
        data1.add(ValueDataEntry("cafe", 10))
        var pie=AnyChart.pie3d()
        any_chart_view.setChart(pie)

    }

    fun getTransactions() {
        var data = mutableListOf<DataEntry>()
        any_chart_view.invalidate()
        var queue = AppSingleton.instance.getQueue(context)
        var transactionsRequest = StringRequest(
            Request.Method.GET,
            AppSingleton.instance.getBaseUrl() + "transactions/3",
            Response.Listener<String> { response ->
                // Success case

                var transactionList = Gson().fromJson<List<Transaction>>(response, object :
                    TypeToken<List<Transaction>>() {}.type)

                var catagories = mutableListOf<String>()
                var values = mutableListOf<Double>()

                transactionList.forEach {
//                    Log.d("catgor",it.toString())
                    if (catagories.contains(it.catagorie)) {
                        var idx = catagories.indexOf(it.catagorie)
//                        Log.d("catgor1",idx.toString())
//                        Log.d("catgor2",catagories.toString())

                        values[idx] += it.amount

                    }else{
                        catagories.add(it.catagorie)
                        values.add(it.amount)
                        var idx=catagories.indexOf(it.catagorie)
//                        values[idx]=0.0
                    }
                }
                Log.d("catagor",catagories.toString())
                Log.d("catagor",values.toString())

                catagories.forEach{
                    var idx=catagories.indexOf(it)
                    data.add(ValueDataEntry(it,values[idx]))
                }
                Log.d("catagor3",data.toString())

                createChart(data)
                data.clear()
                Log.d("catagor3",data.toString())

            },
            Response.ErrorListener {
                // Error case
            })
        queue?.add(transactionsRequest)
    }
}
</code>```

and here is my xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.PFM">

    <com.anychart.AnyChartView
        android:id="@+id/any_chart_view"
        android:layout_width="389dp"
        android:layout_height="333dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="144dp"
        android:layout_marginTop="78dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/any_chart_view" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Basically all you need to update the chart with new data is to make it active and apply new data.
For details, check the following issue threads:
issue 1
issue 2</p>

ContentLicense: CC BY-SA 4.0

Title: AnyChart android refreshing a chart

Body:
I am using anychart library for android to display a pie chart, it gets the data from a mysql using volley and a node JS api to facilitate the crud operation

I am just facing a problem refresing the chart when new data is available from the data base.
I used Log.d to make sure the data is actually being updated it, I checked anycharts github and tried the solutions they listed, mainly that I just need to set the data again with the new data, that didn't work
Please any help is greatly appreciated.
I even tried creating a button and try to set the graph with complety new and hardcoded data. but that didn't work, I tried to use gone and visible and that didn't work

here is my code:

 package com.dana.baizaty_frontend.fragments

import Transaction
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.anychart.APIlib
import com.anychart.AnyChart
import com.anychart.AnyChartView
import com.anychart.chart.common.dataentry.DataEntry
import com.anychart.chart.common.dataentry.ValueDataEntry
import com.anychart.enums.Align
import com.anychart.enums.LegendLayout
import com.dana.baizaty_frontend.R
import com.dana.baizaty_frontend.singleton.AppSingleton
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_pfm.*

class PFM : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

//        val anyChartView: AnyChartView? = any_chart_view

        // Inflate the layout for this fragment
//        createChart()

        var v = inflater.inflate(R.layout.fragment_pfm, container, false)

        return v

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        getTransactions()
        button.setOnClickListener{
            updateChart()
        }

    }

    override fun onStart() {

        super.onStart()
        getTransactions()

        Toast.makeText(context, "testing", "testing".length).show()
    }
    fun createChart (data1: MutableList<DataEntry>
    ) {
//        var anyChartView: AnyChartView? = any_chart_view

//        APIlib.getInstance().setActiveAnyChartView(any_chart_view)
//        any_chart_view.clear()
        any_chart_view.visibility=View.GONE

        any_chart_view.setProgressBar(progress_bar)
        var pie = AnyChart.pie3d()
//        anyChartView?.setProgressBar(progress_bar)

//        data.add(ValueDataEntry("Restarant", 30))
//        data.add(ValueDataEntry("transportation", 23))
//        data.add(ValueDataEntry("cafe", 10))
        Log.d("catagor3",data1.toString())

        pie.data(data1)
        pie.title("spending")
        pie.labels().position("outside")
        pie.legend().title().enabled(true)

        pie.legend()
            .position("center-bottom")
            .itemsLayout(LegendLayout.HORIZONTAL)
            .align(Align.CENTER);

        any_chart_view?.setChart(pie);
        any_chart_view.visibility=View.VISIBLE
        data1.clear()

    }
    fun updateChart(){
        var data1 = mutableListOf<DataEntry>()
        data1.add(ValueDataEntry("Restarant", 30))
        data1.add(ValueDataEntry("transportation", 23))
        data1.add(ValueDataEntry("cafe", 10))
        var pie=AnyChart.pie3d()
        any_chart_view.setChart(pie)

    }

    fun getTransactions() {
        var data = mutableListOf<DataEntry>()
        any_chart_view.invalidate()
        var queue = AppSingleton.instance.getQueue(context)
        var transactionsRequest = StringRequest(
            Request.Method.GET,
            AppSingleton.instance.getBaseUrl() + "transactions/3",
            Response.Listener<String> { response ->
                // Success case

                var transactionList = Gson().fromJson<List<Transaction>>(response, object :
                    TypeToken<List<Transaction>>() {}.type)

                var catagories = mutableListOf<String>()
                var values = mutableListOf<Double>()

                transactionList.forEach {
//                    Log.d("catgor",it.toString())
                    if (catagories.contains(it.catagorie)) {
                        var idx = catagories.indexOf(it.catagorie)
//                        Log.d("catgor1",idx.toString())
//                        Log.d("catgor2",catagories.toString())

                        values[idx] += it.amount

                    }else{
                        catagories.add(it.catagorie)
                        values.add(it.amount)
                        var idx=catagories.indexOf(it.catagorie)
//                        values[idx]=0.0
                    }
                }
                Log.d("catagor",catagories.toString())
                Log.d("catagor",values.toString())

                catagories.forEach{
                    var idx=catagories.indexOf(it)
                    data.add(ValueDataEntry(it,values[idx]))
                }
                Log.d("catagor3",data.toString())

                createChart(data)
                data.clear()
                Log.d("catagor3",data.toString())

            },
            Response.ErrorListener {
                // Error case
            })
        queue?.add(transactionsRequest)
    }
}

and here is my xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.PFM">

    <com.anychart.AnyChartView
        android:id="@+id/any_chart_view"
        android:layout_width="389dp"
        android:layout_height="333dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="144dp"
        android:layout_marginTop="78dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/any_chart_view" />
</androidx.constraintlayout.widget.ConstraintLayout>


问:
maxDistance parameter of Query.Near not working
I'm using MongoDB's C# driver and am trying to get Query.Near to work to return homes for sale within 5, 10, 25, or 50 miles of a center point. Here is the query:

```<code>var near = Query.Near("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    //var near = Query.WithinCircle("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    var query = Collection().Find(near);
    query.Limit = 1000;
    var listings = query.ToList();
</code>```

I'm dividing the mile radius by 62.1868289 to get the radians and inputting that into the query, however it's returning the same amount of homes for sale regardless of what radians value I pass in. I also tried both setting the spherical param to true and using Query.WithinCircle, however neither works any better.

I'm using the latest C# driver (1.0.0.4098), is this a bug in the C# driver, a bug in MongoDB, or am I missing something here?

Here are what the queries look like:

5 miles away (near):

```<code>db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.072463768115942032 } });
</code>```

10 miles away (near):

```<code>db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.14492753623188406 } });
</code>```

5 miles away (spherical near):

```<code>db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0012629451881788331 } });
</code>```

10 miles away (spherical near):

```<code>db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0025258903763576662 } });
</code>```

Here is my test case that returns the same # of results whether I pass in 5 miles away or 25 miles away:

```<code>[Test]
        public void NearTest()
        {
            var isSpherical = true;
            var latitude = 39.4812172;
            var longitude = -76.6438598;
            var milesAway = 5;
            var distance = milesAway / (isSpherical ? 3959.0 : 69.0);

            //search within 5 miles.
            var near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            var collection = ContextWorker.Database.GetCollection<Schemas.Listing.Listing>("Listing");
            var query = collection.Find(near);
            query.Limit = 1000;
            var listings = query.ToList();
            var count1 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count1 + " results returned that are " + milesAway + " miles away");

            //search within 25 miles.
            milesAway = 25;
            distance = milesAway / (isSpherical ? 3959.0 : 69.0);
            near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            query = collection.Find(near);
            query.Limit = 1000;
            listings = query.ToList();
            var count2 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count2 + " results returned that are " + milesAway + " miles away");

            //values should be different.
            Assert.AreNotEqual(count1, count2, "Returned same results for 5 and 25 miles away");
        }

172 results returned that are 5 miles away
172 results returned that are 25 miles away
Test 'Housters.Test.SearchTest.NearTest' failed:
  Returned same results for 5 and 25 miles away
  Expected: not 172
  But was:  172
    SearchTest.cs(68,0): at Housters.Test.SearchTest.NearTest()
</code>```

答:
A bunch of problems here:

Pretty much all the Mongo geospatial queries take the x-coordinate (longitude) first.

When you're not using the spherical queries, Mongo just calculates simple Cartesian distances, and the distance you need to pass is in the same units as your coordinates (likely decimal degrees).

If you do use a spherical query (either near or within), you do need to specify your distance in radians, but to convert from miles to radians, you need to divide by a much bigger number than 62.1868289. You convert from radians to miles by dividing by the Earth's radius (about 3,959 miles).

The conversion you performed above is actually much closer to the conversion from miles to degrees (divide the distance in miles by about 69).

ContentLicense: CC BY-SA 3.0

Body:
I'm using MongoDB's C# driver and am trying to get Query.Near to work to return homes for sale within 5, 10, 25, or 50 miles of a center point. Here is the query:

var near = Query.Near("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    //var near = Query.WithinCircle("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    var query = Collection().Find(near);
    query.Limit = 1000;
    var listings = query.ToList();

I'm dividing the mile radius by 62.1868289 to get the radians and inputting that into the query, however it's returning the same amount of homes for sale regardless of what radians value I pass in. I also tried both setting the spherical param to true and using Query.WithinCircle, however neither works any better.

I'm using the latest C# driver (1.0.0.4098), is this a bug in the C# driver, a bug in MongoDB, or am I missing something here?

Here are what the queries look like:

5 miles away (near):

db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.072463768115942032 } });

10 miles away (near):

db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.14492753623188406 } });

5 miles away (spherical near):

db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0012629451881788331 } });

10 miles away (spherical near):

db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0025258903763576662 } });

Here is my test case that returns the same # of results whether I pass in 5 miles away or 25 miles away:

[Test]
        public void NearTest()
        {
            var isSpherical = true;
            var latitude = 39.4812172;
            var longitude = -76.6438598;
            var milesAway = 5;
            var distance = milesAway / (isSpherical ? 3959.0 : 69.0);

            //search within 5 miles.
            var near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            var collection = ContextWorker.Database.GetCollection<Schemas.Listing.Listing>("Listing");
            var query = collection.Find(near);
            query.Limit = 1000;
            var listings = query.ToList();
            var count1 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count1 + " results returned that are " + milesAway + " miles away");

            //search within 25 miles.
            milesAway = 25;
            distance = milesAway / (isSpherical ? 3959.0 : 69.0);
            near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            query = collection.Find(near);
            query.Limit = 1000;
            listings = query.ToList();
            var count2 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count2 + " results returned that are " + milesAway + " miles away");

            //values should be different.
            Assert.AreNotEqual(count1, count2, "Returned same results for 5 and 25 miles away");
        }

172 results returned that are 5 miles away
172 results returned that are 25 miles away
Test 'Housters.Test.SearchTest.NearTest' failed:
  Returned same results for 5 and 25 miles away
  Expected: not 172
  But was:  172
    SearchTest.cs(68,0): at Housters.Test.SearchTest.NearTest()


问:
Hourglass Array Submission error
I am trying to solve the hourglass problem on hackerrank.you can find the details of problem here (https://www.hackerrank.com/challenges/2d-array).

On my machine code works fine and give correct results even for the testcase that gives error on hackerrank.

Here is the code:

```<code>maxSum = -70
#hourglass = []
arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
for row in range(0,6):
    for col in range(0,6):
        if (row + 2) < 6 and (col + 2) < 6 :
            sum = arr[row][col] + arr[row][col+1] + arr[row][col+2] + arr[row+1][col+1] + arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2]
            if sum > maxSum:
                #hourglass.append(arr[row][col])
                #hourglass.append(arr[row][col+1])
                #hourglass.append(arr[row][col+2])
                #hourglass.append(arr[row+1][col+1])
                #hourglass.append(arr[row+2][col])
                #hourglass.append(arr[row+2][col+1])
                #hourglass.append(arr[row+2][col+2])
                maxSum = sum
print(maxSum)
#print(hourglass)
</code>```

Following error rased while running code:

```<code>Traceback (most recent call last):
  File "solution.py", line 4, in <module>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
ValueError: invalid literal for int() with base 10: '1 1 1 0 0 0'
</code>```

The testcase for which error is raised is:

```<code>1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
</code>```

答:
The attractiveness of this algorithm bears a resemblance to CNN (Convolutional Neural Networks); with minor exceptions, such as: 3x3 Kernel size has fixed sparse points (i.e. the [size(3,1), size(1,1), size(3,1)] the second row was delimited by the corners/edges), striding/sliding is always 1 (but, in practice you might change to >=1 (e.g. deep CNN reduces number of filters of a NN, as a heuristic regularization approach to avoid overfitting), and padding was not taken into considerations (i.e. if a list meets its end, instead of continue to next rows(lists), it moves the next ranges to the being of the list, e.g. [0,1,2,3]:
[0,1,2] -> [1,2,3] -> [2,3,0] -> [3,0,1]).

```<code>def hourglassSum(arr):
    Kernel_size = (3, 3)
    stride = 1
    memory = []

    for i in range(0,Kernel_size[0]+1, stride):
        for j in range(0, Kernel_size[1]+1, stride):
            hour_glass_sum = sum(arr[i][j:3+j]) + arr[i+1][1+j] + sum(arr[i+2][j:3+j])
            memory.append(hour_glass_sum)

    return max(memory)
</code>```

Title: Hourglass Array Submission error

Body:
I am trying to solve the hourglass problem on hackerrank.you can find the details of problem here (https://www.hackerrank.com/challenges/2d-array).

On my machine code works fine and give correct results even for the testcase that gives error on hackerrank.

Here is the code:

maxSum = -70
#hourglass = []
arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
for row in range(0,6):
    for col in range(0,6):
        if (row + 2) < 6 and (col + 2) < 6 :
            sum = arr[row][col] + arr[row][col+1] + arr[row][col+2] + arr[row+1][col+1] + arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2]
            if sum > maxSum:
                #hourglass.append(arr[row][col])
                #hourglass.append(arr[row][col+1])
                #hourglass.append(arr[row][col+2])
                #hourglass.append(arr[row+1][col+1])
                #hourglass.append(arr[row+2][col])
                #hourglass.append(arr[row+2][col+1])
                #hourglass.append(arr[row+2][col+2])
                maxSum = sum
print(maxSum)
#print(hourglass)

Following error rased while running code:

Traceback (most recent call last):
  File "solution.py", line 4, in <module>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
ValueError: invalid literal for int() with base 10: '1 1 1 0 0 0'

The testcase for which error is raised is:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0

Body:
The attractiveness of this algorithm bears a resemblance to CNN (Convolutional Neural Networks); with minor exceptions, such as: 3x3 Kernel size has fixed sparse points (i.e. the [size(3,1), size(1,1), size(3,1)] the second row was delimited by the corners/edges), striding/sliding is always 1 (but, in practice you might change to >=1 (e.g. deep CNN reduces number of filters of a NN, as a heuristic regularization approach to avoid overfitting), and padding was not taken into considerations (i.e. if a list meets its end, instead of continue to next rows(lists), it moves the next ranges to the being of the list, e.g. [0,1,2,3]:
[0,1,2] -> [1,2,3] -> [2,3,0] -> [3,0,1]).

def hourglassSum(arr):
    Kernel_size = (3, 3)
    stride = 1
    memory = []

    for i in range(0,Kernel_size[0]+1, stride):
        for j in range(0, Kernel_size[1]+1, stride):
            hour_glass_sum = sum(arr[i][j:3+j]) + arr[i+1][1+j] + sum(arr[i+2][j:3+j])
            memory.append(hour_glass_sum)

    return max(memory)


问:
Pass through folder with any specific pattern
I have a batch script that would only copy pdf file, based on the user inputted code. As soon as they hit enter it will look for a folder that has same filename with the inputted code.. then if exist it will copy the pdf inside..

Now I'm having a problem because in one sub-folder, it's file name doesn't have standard filename.

Like for ex : sometimes its filename is UV DATA others is UV-DATA , UV

example folder structure storage for the pdf file :

```<code>server
'----22050-022
     '----Folder1
               22050-022-DATA.pdf
</code>```

example folder destination :

```<code>server2
'----Folder
     '----22050-022
          '----UV DATA
               '----DOCUMENTS
</code>```

The UV DATA folder is the only one is changing..
How can I set only only UV and second word is any specific pattern?

Sample XCopy if it is a static code and make default file name is UV DATA:

```<code>set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV DATA\DOCUMENTS\" /D /E /C /I /Y /H
</code>```

I only tried something like this but doesn't work:

```<code>set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV*.*\DOCUMENTS\" /D /E /C /I /Y /H
</code>```

答:
Wildcards in folders are not supported in operations like xcopy

This solution using FOR /F is sort of hacky, but definitely works:

```<code>@echo off
set /p "code=Input Control Number:"
for /f "tokens=* delims= " %%a in ('dir /b /ad "%MySetDestination%\Folder1\%code%\UV*"') (
xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV-%%a\DOCUMENTS\" /D /E /C /I /Y /H
)
</code>```

This will copy the file to all folders in the format UV<ANYTHING HERE>

Body:
I have a batch script that would only copy pdf file, based on the user inputted code. As soon as they hit enter it will look for a folder that has same filename with the inputted code.. then if exist it will copy the pdf inside..

Now I'm having a problem because in one sub-folder, it's file name doesn't have standard filename.

Like for ex : sometimes its filename is UV DATA others is UV-DATA , UV

example folder structure storage for the pdf file :

server
'----22050-022
     '----Folder1
               22050-022-DATA.pdf

example folder destination :

server2
'----Folder
     '----22050-022
          '----UV DATA
               '----DOCUMENTS

The UV DATA folder is the only one is changing..
How can I set only only UV and second word is any specific pattern?

Sample XCopy if it is a static code and make default file name is UV DATA:

set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV DATA\DOCUMENTS\" /D /E /C /I /Y /H

I only tried something like this but doesn't work:

set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV*.*\DOCUMENTS\" /D /E /C /I /Y /H

Body:
Wildcards in folders are not supported in operations like xcopy

This solution using FOR /F is sort of hacky, but definitely works:

@echo off
set /p "code=Input Control Number:"
for /f "tokens=* delims= " %%a in ('dir /b /ad "%MySetDestination%\Folder1\%code%\UV*"') (
xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV-%%a\DOCUMENTS\" /D /E /C /I /Y /H
)

This will copy the file to all folders in the format UV<ANYTHING HERE>


问:
SqlCommandBuilder generating incorrect update statement
I am trying to use a SqlDataAdapter to update a table in a database.

I retrieve the schema from the table, and it populates the DataTable correctly with the columns and the primary key. There is only one constraint in the DataTable, and it is the correct three PK columns.

```<code>DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add(tableName);
adapter.SelectCommand = new SqlCommand("select * from " + tableName, connection);
adapter.FillSchema(dt, SchemaType.Source);

// Add datarows
</code>```

I create a SqlCommandBuilder for the adapter, ...

```<code>SqlCommandBuilder cmdBld = new SqlCommandBuilder(adapter);
</code>```

... but the update command it generates includes a lot of field combinations in the WHERE clause that aren't the primary key. From what I read, the builder should generate the update statement based on the PK constraint of the DataTable:

```<code>UPDATE [MyTable]
SET [CCode] = @p1,
    [RefNumber] = @p2,
    [BrandId] = @p3,
    [BasePrice1] = @p4,
    [BasePrice2] = @p5,
    ....
WHERE
    (([CCode] = @p14) -- PK
    AND ([RefNumber] = @p15) -- PK
    AND ([BrandId] = @p16) -- PK
    AND ([BasePrice1] = @p17)
    AND ([BasePrice2] = @p18)
    AND ((@p19 = 1 AND [AddedBy] IS NULL) OR ([AddedBy] = @p20))
    AND ((@p21 = 1 AND [SFlag] IS NULL) OR ([SFlag] = @p22))
    AND ((@p23 = 1 AND [CartonCode] IS NULL) OR ([CartonCode] = @p24))
    AND ((@p25 = 1 AND [AvailableOrder] IS NULL) OR ([AvailableOrder] = @p26))
    AND ((@p27 = 1 AND [AvailableRegistration] IS NULL) OR ([AvailableRegistration] = @p28))
    AND ((@p29 = 1 AND [IsFOC] IS NULL) OR ([IsFOC] = @p30))
    AND ((@p31 = 1 AND [ItemBrand] IS NULL) OR ([ItemBrand] = @p32))
    AND ((@p33 = 1 AND [QuantityMultiply] IS NULL) OR ([QuantityMultiply] = @p34)))
</code>```

Can anyone help me understand why I'm not getting the expected, PK-based update command?

Thanks.

答:
This answer is a bit late, but have a look at the SqlCommandBuilder.ConflictOption property. The default is: CompareAllSearchableValues, which is the behaviour you are seeing. If you only want to check the primary key, try using OverwriteChanges.

e.g.

```<code>SqlCommandBuilder cmdBld = new SqlCommandBuilder(adapter);
cmdBld.ConflictOption = ConflictOption.OverwriteChanges;
</code>```

Reference on ConflictOption Enum:
https://learn.microsoft.com/en-us/dotnet/api/system.data.conflictoption?view=netframework-4.8

Body:
I am trying to use a SqlDataAdapter to update a table in a database.

I retrieve the schema from the table, and it populates the DataTable correctly with the columns and the primary key. There is only one constraint in the DataTable, and it is the correct three PK columns.

DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add(tableName);
adapter.SelectCommand = new SqlCommand("select * from " + tableName, connection);
adapter.FillSchema(dt, SchemaType.Source);

// Add datarows

I create a SqlCommandBuilder for the adapter, ...

SqlCommandBuilder cmdBld = new SqlCommandBuilder(adapter);

... but the update command it generates includes a lot of field combinations in the WHERE clause that aren't the primary key. From what I read, the builder should generate the update statement based on the PK constraint of the DataTable:

UPDATE [MyTable]
SET [CCode] = @p1,
    [RefNumber] = @p2,
    [BrandId] = @p3,
    [BasePrice1] = @p4,
    [BasePrice2] = @p5,
    ....
WHERE
    (([CCode] = @p14) -- PK
    AND ([RefNumber] = @p15) -- PK
    AND ([BrandId] = @p16) -- PK
    AND ([BasePrice1] = @p17)
    AND ([BasePrice2] = @p18)
    AND ((@p19 = 1 AND [AddedBy] IS NULL) OR ([AddedBy] = @p20))
    AND ((@p21 = 1 AND [SFlag] IS NULL) OR ([SFlag] = @p22))
    AND ((@p23 = 1 AND [CartonCode] IS NULL) OR ([CartonCode] = @p24))
    AND ((@p25 = 1 AND [AvailableOrder] IS NULL) OR ([AvailableOrder] = @p26))
    AND ((@p27 = 1 AND [AvailableRegistration] IS NULL) OR ([AvailableRegistration] = @p28))
    AND ((@p29 = 1 AND [IsFOC] IS NULL) OR ([IsFOC] = @p30))
    AND ((@p31 = 1 AND [ItemBrand] IS NULL) OR ([ItemBrand] = @p32))
    AND ((@p33 = 1 AND [QuantityMultiply] IS NULL) OR ([QuantityMultiply] = @p34)))

Can anyone help me understand why I'm not getting the expected, PK-based update command?

Thanks.

Body:
This answer is a bit late, but have a look at the SqlCommandBuilder.ConflictOption property. The default is: CompareAllSearchableValues, which is the behaviour you are seeing. If you only want to check the primary key, try using OverwriteChanges.

e.g.

SqlCommandBuilder cmdBld = new SqlCommandBuilder(adapter);
cmdBld.ConflictOption = ConflictOption.OverwriteChanges;

Reference on ConflictOption Enum:
https://learn.microsoft.com/en-us/dotnet/api/system.data.conflictoption?view=netframework-4.8


问:
Sorting Javascript Array with Split Function
I have an array that looks like this

```<code>var testArray = ['name1:13', 'name2:15', 'name3:13'];
</code>```

I would like to sort the array by the number to the right of the colon.

So far I have this:

```<code>var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);
</code>```

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15

答:
Split, convert to number and compare.

var testArray = ["name1:13", "name2:15", "name3:13"];

const sortFunction = (a, b) => {
  const value = str => Number(str.split(":")[1]);
  return value(a) - value(b);
};

testArray.sort(sortFunction);

console.log(testArray);```

Body:
I have an array that looks like this

var testArray = ['name1:13', 'name2:15', 'name3:13'];

I would like to sort the array by the number to the right of the colon.

So far I have this:

var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15


问:
Can I have powershell scripts in file with no extension?
Usually powershell script files end with .ps1, and modules end with .psm1.

Can one have powershell scripts/modules in files with no extension? Just "build" or "start" and so on? Will this cause an issue in any specific environment?

If yes, Can one have powershell scripts/modules in files with other "texty" extensions like .sh, .ps etc?

Is there an easier way to invoke powershell scripts instead of keying in .\script.ps1 arg1, arg2 , for example like : go arg1, arg2?

答:
Super late answer, but I wanted to do this for all the scripts in my bin folder, and it took me a while to figure it out. I wound up with this:

```<code>Get-ChildItem -path <bin where your ps1 files live> -Filter *.ps1 |
Foreach-Object{
    $name = $_.Name
    $scptName = $_.Name -split ".ps1",0,"simplematch"
    $scptName = $scptName[0]
    new-alias $name $scptName
}
</code>```

And I also wanted it for all the python scripts in my python bin, which was more complicated but still doable:

```<code>Get-ChildItem -path <pybin path> -Filter *.py |
Foreach-Object{
    $name = $_.Name
    $scptName =  $_.Name -split '.py',0,'simplematch'
    $scptName = $scptName[0]
    $eName = $scptName -split '-',0,'simplematch'
    $eName = $eName[1]
    invoke-expression('
    $val' + $eName + ' = $name
    function doRun' + $eName + '{
        python "<pybin path>/$val' + $eName + '" $args
    }
    $alias = "doRun$ename"
    set-alias $scptName $alias
    ')
}
</code>```

Note that you are invoke-expressioning on an expression containing filenames on your system, so this is a security problem if other people can potentially write to that directory. Since this is my bin directory and I'm execing this stuff all the time anyways I've decided it doesn't matter, but it could so keep that in mind.

There's also certainly a more elegant way to have accomplished this, but I wasn't sure what it was.

Body:
Super late answer, but I wanted to do this for all the scripts in my bin folder, and it took me a while to figure it out. I wound up with this:

Get-ChildItem -path <bin where your ps1 files live> -Filter *.ps1 |
Foreach-Object{
    $name = $_.Name
    $scptName = $_.Name -split ".ps1",0,"simplematch"
    $scptName = $scptName[0]
    new-alias $name $scptName
}

And I also wanted it for all the python scripts in my python bin, which was more complicated but still doable:

Get-ChildItem -path <pybin path> -Filter *.py |
Foreach-Object{
    $name = $_.Name
    $scptName =  $_.Name -split '.py',0,'simplematch'
    $scptName = $scptName[0]
    $eName = $scptName -split '-',0,'simplematch'
    $eName = $eName[1]
    invoke-expression('
    $val' + $eName + ' = $name
    function doRun' + $eName + '{
        python "<pybin path>/$val' + $eName + '" $args
    }
    $alias = "doRun$ename"
    set-alias $scptName $alias
    ')
}

Note that you are invoke-expressioning on an expression containing filenames on your system, so this is a security problem if other people can potentially write to that directory. Since this is my bin directory and I'm execing this stuff all the time anyways I've decided it doesn't matter, but it could so keep that in mind.

There's also certainly a more elegant way to have accomplished this, but I wasn't sure what it was.


问:
Using the unite function in R and removing duplicated values
I'm trying to use the unite function in R to concatenate values across columns, but also deduplicate the values. How can I accomplish this?

Here is the input data:

```<code>input <- tibble(
  id = c('aa', 'ss', 'dd', 'qq'),
  '2017' = c('tv', NA, NA, 'web'),
  '2018' = c('tv', 'web', NA, NA),
  '2019' = c(NA, 'web', 'book', 'tv')
)

# A tibble: 4 x 4
  id    `2017` `2018` `2019`
  <chr> <chr>  <chr>  <chr>
1 aa    tv     tv     NA
2 ss    NA     web    web
3 dd    NA     NA     book
4 qq    web    NA     tv
</code>```

The desired output with the ALL column is:

```<code>> output
# A tibble: 4 x 5
  id    `2017` `2018` `2019` ALL
  <chr> <chr>  <chr>  <chr>  <chr>
1 aa    tv     tv     NA     tv
2 ss    NA     web    web    web
3 dd    NA     NA     book   book
4 qq    web    NA     tv     web, tv
</code>```

答:
Similar questions exist here on SO, but since you are after a unite solution and I couldn't find any that specifically use unite, here we go:

Using unite

```<code>input %>% unite(ALL, -id, sep = ", ", remove = FALSE, na.rm = TRUE)
## A tibble: 4 x 5
#  id    ALL     `2017` `2018` `2019`
#  <chr> <chr>   <chr>  <chr>  <chr>
#1 aa    tv      tv     NA     NA
#2 ss    web     NA     web    NA
#3 dd    book    NA     NA     book
#4 qq    web, tv web    NA     tv
</code>```

To recover the exact column order of your expected output, you can add a %>% select(names(input), ALL).

Alternatively, using nest

```<code>input %>%
    group_by(id) %>%
    nest() %>%
    mutate(ALL = map_chr(data, ~toString(unlist(.x[!is.na(unlist(.x))])))) %>%
    unnest(data)
## A tibble: 4 x 5
## Groups:   id [4]
#  id    `2017` `2018` `2019` ALL
#  <chr> <chr>  <chr>  <chr>  <chr>
#1 aa    tv     NA     NA     tv
#2 ss    NA     web    NA     web
#3 dd    NA     NA     book   book
#4 qq    web    NA     tv     web, tv
</code>```

Or the base R way (as in How to create new column with all non-NA values from multiple other columns?):

```<code>input$ALL <- apply(input[, -1], 1, function(x) toString(x[!is.na(x)]))
input
# A tibble: 4 x 5
#   id    `2017` `2018` `2019` ALL
#  <chr> <chr>  <chr>  <chr>  <chr>
#1 aa    tv     NA     NA     tv
#2 ss    NA     web    NA     web
#3 dd    NA     NA     book   book
#4 qq    web    NA     tv     web, tv
</code>```

Body:
I'm trying to use the unite function in R to concatenate values across columns, but also deduplicate the values. How can I accomplish this?

Here is the input data:

input <- tibble(
  id = c('aa', 'ss', 'dd', 'qq'),
  '2017' = c('tv', NA, NA, 'web'),
  '2018' = c('tv', 'web', NA, NA),
  '2019' = c(NA, 'web', 'book', 'tv')
)

# A tibble: 4 x 4
  id    `2017` `2018` `2019`
  <chr> <chr>  <chr>  <chr>
1 aa    tv     tv     NA
2 ss    NA     web    web
3 dd    NA     NA     book
4 qq    web    NA     tv

The desired output with the ALL column is:

> output
# A tibble: 4 x 5
  id    `2017` `2018` `2019` ALL
  <chr> <chr>  <chr>  <chr>  <chr>
1 aa    tv     tv     NA     tv
2 ss    NA     web    web    web
3 dd    NA     NA     book   book
4 qq    web    NA     tv     web, tv

Body:
Similar questions exist here on SO, but since you are after a unite solution and I couldn't find any that specifically use unite, here we go:

Using unite

input %>% unite(ALL, -id, sep = ", ", remove = FALSE, na.rm = TRUE)
## A tibble: 4 x 5
#  id    ALL     `2017` `2018` `2019`
#  <chr> <chr>   <chr>  <chr>  <chr>
#1 aa    tv      tv     NA     NA
#2 ss    web     NA     web    NA
#3 dd    book    NA     NA     book
#4 qq    web, tv web    NA     tv

To recover the exact column order of your expected output, you can add a %>% select(names(input), ALL).

Alternatively, using nest

input %>%
    group_by(id) %>%
    nest() %>%
    mutate(ALL = map_chr(data, ~toString(unlist(.x[!is.na(unlist(.x))])))) %>%
    unnest(data)
## A tibble: 4 x 5
## Groups:   id [4]
#  id    `2017` `2018` `2019` ALL
#  <chr> <chr>  <chr>  <chr>  <chr>
#1 aa    tv     NA     NA     tv
#2 ss    NA     web    NA     web
#3 dd    NA     NA     book   book
#4 qq    web    NA     tv     web, tv

Or the base R way (as in How to create new column with all non-NA values from multiple other columns?):

input$ALL <- apply(input[, -1], 1, function(x) toString(x[!is.na(x)]))
input
# A tibble: 4 x 5
#   id    `2017` `2018` `2019` ALL
#  <chr> <chr>  <chr>  <chr>  <chr>
#1 aa    tv     NA     NA     tv
#2 ss    NA     web    NA     web
#3 dd    NA     NA     book   book
#4 qq    web    NA     tv     web, tv


问:
sorting DataFrame based on multiple conditions in pandas
I have a DataFrame similar to the following

```<code>date      mood    score   count  avg       abs
23/12/18 negative -50.893   137  -0.371     50.893
23/12/18 neutral  0.2193    10   0.0219     0.2193
23/12/18 positive 336.5098  673  0.5000     336.5098
24/12/18 positive 91.2414   232  -0.393     91.2414
24/12/18 neutral  0.063     14   0.0045     0.063
24/12/18 negative -649.697  1184 0.5487     649.697
25/12/18 negative -72.4142  8   -9.0517     72.4142
25/12/18 positive   0       0    0          0
25/12/18 neutral  323.0056  173 1.86708     323.0056
26/12/18 negative -12.0467   15 -.8031      12.0467
</code>```

I want to apply the following conditions to this dataset.

```<code>Con: if the absolute value(abs) score on a date is the greatest (of 3 moods), keep that date only together with its other attributes.
Con: No duplicate date is to be kept. So the dataset will be reduced quite a lot compared to its original size.
</code>```

Expected Output

```<code>date       mood_corrected   score   count   avg          abs
23/12/18    positive      336.5098  673    0.50001456   336.5098
24/12/18    negative      649.697   1184   0.54873057   649.697
25/12/18    neutral       323.0056  173    1.86708439   323.0056
26/12/18    negative      -12.0467  15     -0.8031      12.0467
</code>```

My code

```<code>import pandas as pd

df =pd.read_csv('file.csv')

new_df= df.sort_values('abs', ascending=False).drop_duplicates(['date','mood'])
</code>```

While I get result that sort the dataset based on absolute value**(abs)**, I still have the full dataset. It is not reduced. Any help is appreciated. Many thanks.

Note: I looked at stackoverflow but have not found a quite similar problem.

答:
The following will do the job!</p>

```<code>new_df = df.sort_values('abs', ascending=False).drop_duplicates(['date']).sort_values('date')
</code>```

Body:
I have a DataFrame similar to the following

date      mood    score   count  avg       abs
23/12/18 negative -50.893   137  -0.371     50.893
23/12/18 neutral  0.2193    10   0.0219     0.2193
23/12/18 positive 336.5098  673  0.5000     336.5098
24/12/18 positive 91.2414   232  -0.393     91.2414
24/12/18 neutral  0.063     14   0.0045     0.063
24/12/18 negative -649.697  1184 0.5487     649.697
25/12/18 negative -72.4142  8   -9.0517     72.4142
25/12/18 positive   0       0    0          0
25/12/18 neutral  323.0056  173 1.86708     323.0056
26/12/18 negative -12.0467   15 -.8031      12.0467

I want to apply the following conditions to this dataset.

Con: if the absolute value(abs) score on a date is the greatest (of 3 moods), keep that date only together with its other attributes.
Con: No duplicate date is to be kept. So the dataset will be reduced quite a lot compared to its original size.

Expected Output

date       mood_corrected   score   count   avg          abs
23/12/18    positive      336.5098  673    0.50001456   336.5098
24/12/18    negative      649.697   1184   0.54873057   649.697
25/12/18    neutral       323.0056  173    1.86708439   323.0056
26/12/18    negative      -12.0467  15     -0.8031      12.0467

My code

import pandas as pd

df =pd.read_csv('file.csv')

new_df= df.sort_values('abs', ascending=False).drop_duplicates(['date','mood'])

While I get result that sort the dataset based on absolute value**(abs)**, I still have the full dataset. It is not reduced. Any help is appreciated. Many thanks.

Note: I looked at stackoverflow but have not found a quite similar problem.

Body:
The following will do the job!

new_df = df.sort_values('abs', ascending=False).drop_duplicates(['date']).sort_values('date')


问:
Update records in table from CTE results
I want to update the records in my table using CTE.
And I've been trying with the insert function using CTE and it's working.
This is my query with the insert function:

```<code>; WITH CTE AS
(
    SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
    FROM DAILYDATA
)
INSERT INTO DAILYDATAWH (NIP, NAME, DEPARTMENT, STATUSIN, STATUSOUT)
SELECT  NIP, NAME, DEPARTMENT, STATUSIN = MIN(DATEATTEND), STATUSOUT = MAX(DATEATTEND)
FROM    CTE
GROUP BY NIP, NAME, DEPARTMENT, (RN - 1) / 2
</code>```

How to change that with the update function?

i want to change to update function because when i use insert function,the previous data that already exists in DAILYDATA appear again

This is table DAILYDATA

This is table DAILYDATAWH

答:
Not sure why you're calculating row_number but you might

```<code>; WITH CTE AS
(
    SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND),
    MIN(DATEATTEND) OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND) AS cteSTATUSIN,
    MAX(DATEATTEND) OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND) AS cteSTATUSOUT
    FROM DAILYDATA
)
Update DAILYDATAWH
SET DAILYDATAWH.NIP = CTE.NIP , DAILYDATAWH.NAME = CTE.NAME,
DAILYDATAWH.DEPARTMENT = CTE.DEPARTMENT,
DAILYDATAWH.STATUSIN = cteSTATUSIN,
DAILYDATAWH.STATUSOUT = cteSTATUSOUT,
From DAILYDATA Inner join CTE on DAILYDATA.NIP = CTE.NIP
</code>```

Body:
I want to update the records in my table using CTE.
And I've been trying with the insert function using CTE and it's working.
This is my query with the insert function:

; WITH CTE AS
(
    SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
    FROM DAILYDATA
)
INSERT INTO DAILYDATAWH (NIP, NAME, DEPARTMENT, STATUSIN, STATUSOUT)
SELECT  NIP, NAME, DEPARTMENT, STATUSIN = MIN(DATEATTEND), STATUSOUT = MAX(DATEATTEND)
FROM    CTE
GROUP BY NIP, NAME, DEPARTMENT, (RN - 1) / 2

How to change that with the update function?

i want to change to update function because when i use insert function,the previous data that already exists in DAILYDATA appear again

This is table DAILYDATA

This is table DAILYDATAWH

Body:
Not sure why you're calculating row_number but you might

; WITH CTE AS
(
    SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND),
    MIN(DATEATTEND) OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND) AS cteSTATUSIN,
    MAX(DATEATTEND) OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND) AS cteSTATUSOUT
    FROM DAILYDATA
)
Update DAILYDATAWH
SET DAILYDATAWH.NIP = CTE.NIP , DAILYDATAWH.NAME = CTE.NAME,
DAILYDATAWH.DEPARTMENT = CTE.DEPARTMENT,
DAILYDATAWH.STATUSIN = cteSTATUSIN,
DAILYDATAWH.STATUSOUT = cteSTATUSOUT,
From DAILYDATA Inner join CTE on DAILYDATA.NIP = CTE.NIP


问:
Subclassing NSDictionary not working
I have a dictionary that I read from a plist. I want to create a subclass of NSDictionary to implement something like the following, so that I can avoid using @"key name" everywhere in my source code:

```<code>@interface MyDict{
}
-(NSString*) textString;
@end

@implementation MyDict
-(NSString*) textString {
    return [self objectForKey:@"textString"];
}
@end
</code>```

In my other method:

```<code>MyDict *d = ... // something i read from plist
NSString *str = [d textString];
</code>```

When I call the method, the app crashes because of "unrecognized selector textString". What is wrong here?

答:
Just assigning an NSDictionary to a MyDict pointer doesn't make it a MyDict instance.

One way you can do this would be to create a category to add your method to NSDictionary. See http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1 for info.

Title: Subclassing NSDictionary not working

Body:
I have a dictionary that I read from a plist. I want to create a subclass of NSDictionary to implement something like the following, so that I can avoid using @"key name" everywhere in my source code:

@interface MyDict{
}
-(NSString*) textString;
@end

@implementation MyDict
-(NSString*) textString {
    return [self objectForKey:@"textString"];
}
@end

In my other method:

MyDict *d = ... // something i read from plist
NSString *str = [d textString];

When I call the method, the app crashes because of "unrecognized selector textString". What is wrong here?


问:
Same questions still show up even if deleted/modified/changed from the array (android studio)
This is made from android studio

So, basically I have SQLite database for the questions for my quiz game

it basically works: It has 20 questions for the user to answer correct, but I want to switch things and I added a difficulty setting easy - 10 easy questions medium - 15 questions hard - 20 questions

I just made another class for the medium and hard difficulties and just copied and pasted the codes and questions over from the original database class and just changed the questions.

It worked. However the questions are still the same (all 20 questions are still there). I even tried to remove all the questions in the array (when there should be no questions cause I removed them all) and the same 20 questions are there.

tldr: the same 20 questions are still showing up regardless if it is removed/added/edited from the array

```<code>private Context context;
private static final String DB_NAME = "TQuiz.db";

//If you want to add more questions or wanna update table values
//or any kind of modification in db just increment version no.
private static final int DB_VERSION = 3;
//Table name
private static final String TABLE_NAME = "TQ";
//Id of question
private static final String UID = "_UID";
//Question
private static final String QUESTION = "QUESTION";
//Option A
private static final String OPTA = "OPTA";
//Option B
private static final String OPTB = "OPTB";
//Option C
private static final String OPTC = "OPTC";
//Option D
private static final String OPTD = "OPTD";
//Answer
private static final String ANSWER = "ANSWER";
//So basically we are now creating table with first column-id , sec column-question , third column -option A, fourth column -option B , Fifth column -option C , sixth column -option D , seventh column - answer(i.e ans of  question)
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + QUESTION + " VARCHAR(255), " + OPTA + " VARCHAR(255), " + OPTB + " VARCHAR(255), " + OPTC + " VARCHAR(255), " + OPTD + " VARCHAR(255), " + ANSWER + " VARCHAR(255));";
//Drop table query
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

TriviaQuizHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    this.context = context;
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    //OnCreate is called only once
    sqLiteDatabase.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    //OnUpgrade is called when ever we upgrade or increment our database version no
    sqLiteDatabase.execSQL(DROP_TABLE);
    onCreate(sqLiteDatabase);
}

void allQuestion() {
    ArrayList<TriviaQuestion> arraylist = new ArrayList<>();

    arraylist.add(new TriviaQuestion("Galileo was an Italian astronomer who developed?" , "Telescope", "Airoplane", "Electricity", "Train", "Telescope"));

    arraylist.add(new TriviaQuestion("Who is the father of Geometry ?" , "Aristotle", "Euclid", "Pythagoras", "Kepler", "Euclid"));

    arraylist.add(new TriviaQuestion("Who was known as Iron man of India ?", "Govind Ballabh Pant", "Jawaharlal Nehru", "Subhash Chandra Bose", "Sardar Vallabhbhai Patel", "Sardar Vallabhbhai Patel"));

    arraylist.add(new TriviaQuestion("The first woman in space was ?", "Valentina Tereshkova", "Sally Ride", "Naidia Comenci", "Tamara Press", "Valentina Tereshkova"));

    arraylist.add(new TriviaQuestion("Who is the Flying Sikh of India ?", "Mohinder Singh", "Joginder Singh", "Ajit Pal Singh", "Milkha singh", "Milkha singh"));

    arraylist.add(new TriviaQuestion("The Indian to beat the computers in mathematical wizardry is", "Ramanujam", "Rina Panigrahi", "Raja Ramanna", "Shakunthala Devi", "Shakunthala Devi"));

    arraylist.add(new TriviaQuestion("Who is Larry Pressler ?", "Politician", "Painter", "Actor", "Tennis player", "Politician"));

    arraylist.add(new TriviaQuestion("Michael Jackson is a distinguished person in the field of ?", "Pop Music", "Jounalism", "Sports", "Acting", "Pop Music"));

    arraylist.add(new TriviaQuestion("The first Indian to swim across English channel was ?", "V. Merchant", "P. K. Banerji", "Mihir Sen", "Arati Saha", "Mihir Sen"));

    arraylist.add(new TriviaQuestion("Who was the first Indian to make a movie?", "Dhundiraj Govind Phalke", " Asha Bhonsle", " Ardeshir Irani", "V. Shantaram", "Dhundiraj Govind Phalke"));

    arraylist.add(new TriviaQuestion("Who is known as the ' Saint of the gutters ?", "B.R.Ambedkar", "Mother Teresa", "Mahatma Gandhi", "Baba Amte", "Mother Teresa"));

    arraylist.add(new TriviaQuestion("Who invented the famous formula E=mc^2", "Albert Einstein", "Galilio", "Sarvesh", "Bill Gates", "Albert Einstein"));

    arraylist.add(new TriviaQuestion("Who is elected as president of us 2016", "Donald Trump", "Hilary Clinton", "Jhon pol", "Barack Obama", "Donald Trump"));

    arraylist.add(new TriviaQuestion("Who was the founder of company Microsoft", "Bill Gates", "Bill Clinton", "Jhon rio", "Steve jobs", "Bill Gates"));

    arraylist.add(new TriviaQuestion("Who was the founder of company Apple ?", "Steve Jobs", "Steve Washinton", "Bill Gates", "Jobs Wills", "Steve Jobs"));

    arraylist.add(new TriviaQuestion("Who was the founder of company Google ?", "Steve Jobs", "Bill Gates", "Larry Page", "Sundar Pichai", "Larry Page"));

    arraylist.add(new TriviaQuestion("Who is know as god of cricket ?", "Sachin Tendulkar", "Kapil Dev", "Virat Koli", "Dhoni", "Sachin Tendulkar"));

    arraylist.add(new TriviaQuestion("who has won ballon d'or of 2015 ?", "Lionel Messi", "Cristiano Ronaldo", "Neymar", "Kaka", "Lionel Messi"));

    arraylist.add(new TriviaQuestion("who has won ballon d'or of 2014 ?", "Neymar", "Lionel Messi", "Cristiano Ronaldo", "Kaka", "Cristiano Ronaldo"));

    arraylist.add(new TriviaQuestion("the Founder of the most famous gaming platform steam is ?",
            "Bill Cliton", "Bill Williams", "Gabe Newell", "Bill Gates", "Gabe Newell"));

    this.addAllQuestions(arraylist);

}

private void addAllQuestions(ArrayList<TriviaQuestion> allQuestions) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    try {
        ContentValues values = new ContentValues();
        for (TriviaQuestion question : allQuestions) {
            values.put(QUESTION, question.getQuestion());
            values.put(OPTA, question.getOptA());
            values.put(OPTB, question.getOptB());
            values.put(OPTC, question.getOptC());
            values.put(OPTD, question.getOptD());
            values.put(ANSWER, question.getAnswer());
            db.insert(TABLE_NAME, null, values);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        db.close();
    }
}

List<TriviaQuestion> getAllOfTheQuestions() {

    List<TriviaQuestion> questionsList = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    String coloumn[] = {UID, QUESTION, OPTA, OPTB, OPTC, OPTD, ANSWER};
    Cursor cursor = db.query(TABLE_NAME, coloumn, null, null, null, null, null);

    while (cursor.moveToNext()) {
        TriviaQuestion question = new TriviaQuestion();
        question.setId(cursor.getInt(0));
        question.setQuestion(cursor.getString(1));
        question.setOptA(cursor.getString(2));
        question.setOptB(cursor.getString(3));
        question.setOptC(cursor.getString(4));
        question.setOptD(cursor.getString(5));
        question.setAnswer(cursor.getString(6));
        questionsList.add(question);
    }

    db.setTransactionSuccessful();
    db.endTransaction();
    cursor.close();
    db.close();
    return questionsList;
}}
</code>```

答: If you copied you database class, but forget to change table name - it can lead to duplication of data.</p>

Body:
This is made from android studio

So, basically I have SQLite database for the questions for my quiz game

it basically works: It has 20 questions for the user to answer correct, but I want to switch things and I added a difficulty setting easy - 10 easy questions medium - 15 questions hard - 20 questions

I just made another class for the medium and hard difficulties and just copied and pasted the codes and questions over from the original database class and just changed the questions.

It worked. However the questions are still the same (all 20 questions are still there). I even tried to remove all the questions in the array (when there should be no questions cause I removed them all) and the same 20 questions are there.

tldr: the same 20 questions are still showing up regardless if it is removed/added/edited from the array

private Context context;
private static final String DB_NAME = "TQuiz.db";

//If you want to add more questions or wanna update table values
//or any kind of modification in db just increment version no.
private static final int DB_VERSION = 3;
//Table name
private static final String TABLE_NAME = "TQ";
//Id of question
private static final String UID = "_UID";
//Question
private static final String QUESTION = "QUESTION";
//Option A
private static final String OPTA = "OPTA";
//Option B
private static final String OPTB = "OPTB";
//Option C
private static final String OPTC = "OPTC";
//Option D
private static final String OPTD = "OPTD";
//Answer
private static final String ANSWER = "ANSWER";
//So basically we are now creating table with first column-id , sec column-question , third column -option A, fourth column -option B , Fifth column -option C , sixth column -option D , seventh column - answer(i.e ans of  question)
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + QUESTION + " VARCHAR(255), " + OPTA + " VARCHAR(255), " + OPTB + " VARCHAR(255), " + OPTC + " VARCHAR(255), " + OPTD + " VARCHAR(255), " + ANSWER + " VARCHAR(255));";
//Drop table query
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

TriviaQuizHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    this.context = context;
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    //OnCreate is called only once
    sqLiteDatabase.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    //OnUpgrade is called when ever we upgrade or increment our database version no
    sqLiteDatabase.execSQL(DROP_TABLE);
    onCreate(sqLiteDatabase);
}

void allQuestion() {
    ArrayList<TriviaQuestion> arraylist = new ArrayList<>();

    arraylist.add(new TriviaQuestion("Galileo was an Italian astronomer who developed?" , "Telescope", "Airoplane", "Electricity", "Train", "Telescope"));

    arraylist.add(new TriviaQuestion("Who is the father of Geometry ?" , "Aristotle", "Euclid", "Pythagoras", "Kepler", "Euclid"));

    arraylist.add(new TriviaQuestion("Who was known as Iron man of India ?", "Govind Ballabh Pant", "Jawaharlal Nehru", "Subhash Chandra Bose", "Sardar Vallabhbhai Patel", "Sardar Vallabhbhai Patel"));

    arraylist.add(new TriviaQuestion("The first woman in space was ?", "Valentina Tereshkova", "Sally Ride", "Naidia Comenci", "Tamara Press", "Valentina Tereshkova"));

    arraylist.add(new TriviaQuestion("Who is the Flying Sikh of India ?", "Mohinder Singh", "Joginder Singh", "Ajit Pal Singh", "Milkha singh", "Milkha singh"));

    arraylist.add(new TriviaQuestion("The Indian to beat the computers in mathematical wizardry is", "Ramanujam", "Rina Panigrahi", "Raja Ramanna", "Shakunthala Devi", "Shakunthala Devi"));

    arraylist.add(new TriviaQuestion("Who is Larry Pressler ?", "Politician", "Painter", "Actor", "Tennis player", "Politician"));

    arraylist.add(new TriviaQuestion("Michael Jackson is a distinguished person in the field of ?", "Pop Music", "Jounalism", "Sports", "Acting", "Pop Music"));

    arraylist.add(new TriviaQuestion("The first Indian to swim across English channel was ?", "V. Merchant", "P. K. Banerji", "Mihir Sen", "Arati Saha", "Mihir Sen"));

    arraylist.add(new TriviaQuestion("Who was the first Indian to make a movie?", "Dhundiraj Govind Phalke", " Asha Bhonsle", " Ardeshir Irani", "V. Shantaram", "Dhundiraj Govind Phalke"));

    arraylist.add(new TriviaQuestion("Who is known as the ' Saint of the gutters ?", "B.R.Ambedkar", "Mother Teresa", "Mahatma Gandhi", "Baba Amte", "Mother Teresa"));

    arraylist.add(new TriviaQuestion("Who invented the famous formula E=mc^2", "Albert Einstein", "Galilio", "Sarvesh", "Bill Gates", "Albert Einstein"));

    arraylist.add(new TriviaQuestion("Who is elected as president of us 2016", "Donald Trump", "Hilary Clinton", "Jhon pol", "Barack Obama", "Donald Trump"));

    arraylist.add(new TriviaQuestion("Who was the founder of company Microsoft", "Bill Gates", "Bill Clinton", "Jhon rio", "Steve jobs", "Bill Gates"));

    arraylist.add(new TriviaQuestion("Who was the founder of company Apple ?", "Steve Jobs", "Steve Washinton", "Bill Gates", "Jobs Wills", "Steve Jobs"));

    arraylist.add(new TriviaQuestion("Who was the founder of company Google ?", "Steve Jobs", "Bill Gates", "Larry Page", "Sundar Pichai", "Larry Page"));

    arraylist.add(new TriviaQuestion("Who is know as god of cricket ?", "Sachin Tendulkar", "Kapil Dev", "Virat Koli", "Dhoni", "Sachin Tendulkar"));

    arraylist.add(new TriviaQuestion("who has won ballon d'or of 2015 ?", "Lionel Messi", "Cristiano Ronaldo", "Neymar", "Kaka", "Lionel Messi"));

    arraylist.add(new TriviaQuestion("who has won ballon d'or of 2014 ?", "Neymar", "Lionel Messi", "Cristiano Ronaldo", "Kaka", "Cristiano Ronaldo"));

    arraylist.add(new TriviaQuestion("the Founder of the most famous gaming platform steam is ?",
            "Bill Cliton", "Bill Williams", "Gabe Newell", "Bill Gates", "Gabe Newell"));

    this.addAllQuestions(arraylist);

}

private void addAllQuestions(ArrayList<TriviaQuestion> allQuestions) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    try {
        ContentValues values = new ContentValues();
        for (TriviaQuestion question : allQuestions) {
            values.put(QUESTION, question.getQuestion());
            values.put(OPTA, question.getOptA());
            values.put(OPTB, question.getOptB());
            values.put(OPTC, question.getOptC());
            values.put(OPTD, question.getOptD());
            values.put(ANSWER, question.getAnswer());
            db.insert(TABLE_NAME, null, values);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        db.close();
    }
}

List<TriviaQuestion> getAllOfTheQuestions() {

    List<TriviaQuestion> questionsList = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    String coloumn[] = {UID, QUESTION, OPTA, OPTB, OPTC, OPTD, ANSWER};
    Cursor cursor = db.query(TABLE_NAME, coloumn, null, null, null, null, null);

    while (cursor.moveToNext()) {
        TriviaQuestion question = new TriviaQuestion();
        question.setId(cursor.getInt(0));
        question.setQuestion(cursor.getString(1));
        question.setOptA(cursor.getString(2));
        question.setOptB(cursor.getString(3));
        question.setOptC(cursor.getString(4));
        question.setOptD(cursor.getString(5));
        question.setAnswer(cursor.getString(6));
        questionsList.add(question);
    }

    db.setTransactionSuccessful();
    db.endTransaction();
    cursor.close();
    db.close();
    return questionsList;
}}


问:
In flutter, how to add an outline button that look like a text field with underline?
In flutter, how to add an outline button that look like a text field with underline? I only need a bottom underline.</p>

```<code>           OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
              borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0),
            ),
          ),
            )
</code>```

答:
If I understand your question correctly, you just need to add decoration property of the text and pass TextDecoration.underline to it, to achieve the bottom underline. Working sample code below:

```<code>body: Center(
        child: OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
            //  borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0, decoration: TextDecoration.underline),
            ),
          ),
            )
      ),
</code>```

Hope this answers your question.

Body:
In flutter, how to add an outline button that look like a text field with underline? I only need a bottom underline.

           OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
              borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0),
            ),
          ),
            )

Body:
If I understand your question correctly, you just need to add decoration property of the text and pass TextDecoration.underline to it, to achieve the bottom underline. Working sample code below:

body: Center(
        child: OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
            //  borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0, decoration: TextDecoration.underline),
            ),
          ),
            )
      ),

Hope this answers your question.


问:
Eclipse (atollic) Pre-Build command format
I'm using Eclipe-Atollic to build for a STM32 micro. Running Windows 10 and TortoiseSvn. Im trying to get the Svn version into my code using the Tortoise "svnversion" command.

I'm trying to add the following command to the Pre-build steps in Eclipse-atollic under  "Project Properties >> C/C++ Build >> Settings >> Build Steps >> Pre-build steps" .

svnversion > Src\svnvers.inc

This works fine from the Command prompt, but when I use the Eclipse builder - I get the following error message:

```<code>Info: Internal Builder is used for build
svnversion > Src\svnvers.inc
svnversion: E020024: Error resolving case of '>'
</code>```

After the initial error, I've tried a variety of combinations of " and \ escapes, but without success.

Looking for any guidance on how to configure Eclipse to execute this command.

Thanks,

答:
OK, If anyone else needs to know, I used "cmd -c" to execute the command, so what worked was:

cmd -c svnversion > Src\svnvers.inc

Body:
I'm using Eclipe-Atollic to build for a STM32 micro. Running Windows 10 and TortoiseSvn. Im trying to get the Svn version into my code using the Tortoise "svnversion" command.

I'm trying to add the following command to the Pre-build steps in Eclipse-atollic under  "Project Properties >> C/C++ Build >> Settings >> Build Steps >> Pre-build steps" .

svnversion > Src\svnvers.inc

This works fine from the Command prompt, but when I use the Eclipse builder - I get the following error message:

Info: Internal Builder is used for build
svnversion > Src\svnvers.inc
svnversion: E020024: Error resolving case of '>'

After the initial error, I've tried a variety of combinations of " and \ escapes, but without success.

Looking for any guidance on how to configure Eclipse to execute this command.

Thanks,


问:
How do I make a selfbot join a server?
I want my selfbot to join servers by an invite by using a command such as /summon [invite].

I have tried to use the accept invite function but it didn't seem to be working.

```<code>client.accept_invite()
</code>```

It doesn't return any errors or anything.

答:
A quick look in the Networking tab on the Discord app shows a request made when attempting to join a server. You can manually use this request to try and join a server.

You can have a python bot join a server by sending a POST request to https://discordapp.com/api/v6/invites/dank?inputValue=SERVER_JOIN_STR&with_counts=true.

You have to also set the authorization header to your token. an example would look like:

```<code>import requests
requests.post("https://discordapp.com/api/v6/invites/SERVER_JOIN_STR",headers={'authorization':'TOKEN'})
</code>```

Remember to use ethically, and hope it helps.

Title: How do I make a selfbot join a server?

Body:
I want my selfbot to join servers by an invite by using a command such as /summon [invite].

I have tried to use the accept invite function but it didn't seem to be working.

client.accept_invite()

It doesn't return any errors or anything.

Body:
A quick look in the Networking tab on the Discord app shows a request made when attempting to join a server. You can manually use this request to try and join a server.

You can have a python bot join a server by sending a POST request to https://discordapp.com/api/v6/invites/dank?inputValue=SERVER_JOIN_STR&with_counts=true.

You have to also set the authorization header to your token. an example would look like:

import requests
requests.post("https://discordapp.com/api/v6/invites/SERVER_JOIN_STR",headers={'authorization':'TOKEN'})

Remember to use ethically, and hope it helps.


问:
DOM Based XSS Attack and InnerHTML
How would one go about securing the below DOM Based XSS attack?

Specifically, is there a protect() function that will make the below safe?
If no, then is there another solution?
eg: Giving the div an id and then later assigning the element an onclick handler

```<code><?php
function protect()
{
   // For non-DOM XSS attacks, hex-encoding all non-alphanumeric characters
   // with ASCII values less than 256 works (ie: \xHH)
   // But is it possible to augment this function to protect against
   // the below DOM based XSS attack?
}
?>

<body>
  <div id="mydiv"></div>
  <script type="text/javascript">
    var xss = "<?php echo protect($_GET["xss"]) ?>";
    $("#mydiv").html("<div onclick='myfunc(\""+xss+"\")'></div>")
  </script>
</body>
</code>```

I'm hoping for an answer that is not "avoid using innerHTML" or "regex the xss variable to [a-zA-Z0-9]"...ie: is there a more general solution?

Thanks

答: I'm no PHP expert, but if you want to prevent XSS attacks against the code sample presented, in the current format, with minimum changes, you could use the PHP edition of OWASP ESAPI. To be specific, use the JavaScript codec class from ESAPI to protect the contents of the xss variable, as it appears in a JavaScript context.

Title: DOM Based XSS Attack and InnerHTML

Body:
How would one go about securing the below DOM Based XSS attack?

Specifically, is there a protect() function that will make the below safe?
If no, then is there another solution?
eg: Giving the div an id and then later assigning the element an onclick handler

<?php
function protect()
{
   // For non-DOM XSS attacks, hex-encoding all non-alphanumeric characters
   // with ASCII values less than 256 works (ie: \xHH)
   // But is it possible to augment this function to protect against
   // the below DOM based XSS attack?
}
?>

I'm hoping for an answer that is not "avoid using innerHTML" or "regex the xss variable to [a-zA-Z0-9]"...ie: is there a more general solution?

Thanks


问:
I have click event attached to elements
, but it only fires once on the first

I have click event attached to elements
, but it only fires once on the first
. I can see its child element also has click event attached. Please help.

$(document).ready(function(){
  $(".nav-item").click(function(){
    console.log("I am clicked");
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <!-- Brand -->
  Navbar

  <!-- Toggler/collapsibe Button -->
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>

  <!-- Navbar links -->
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="myclick nav-item dropdown">
        Link A
        <div class="dropdown-menu">
          Link 1
          Link 2
          Link 3
        </div>
      </li>
      <li class="myclick nav-item">
        Link B
      </li>
      <li class="myclick nav-item">
        Link C
      </li>
    </ul>
  </div>
</nav>

</body>
</html></code>```

答:
```<code>$(".nav-item").get(0).click(function(){
    console.log("I am clicked");
});
try this.
</code>```

You need to call native DOM click() method in order to trigger clicking behavior. This is a exception to ancher tag by jQuery. To get native DOM from jQuery object you can use get(0) or simply [0]. Eg: $(".nav-item").get(0) or $(".nav-item")[0]

Title: I have click event attached to elements <li>, but it only fires once on the first <li>

Body:
I have click event attached to elements
, but it only fires once on the first
. I can see its child element also has click event attached. Please help.

$(document).ready(function(){
  $(".nav-item").click(function(){
    console.log("I am clicked");
  });
})

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  Navbar

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

  </button>

        Link A

          Link 1
          Link 2
          Link 3

        Link B

        Link C

Body:
$(".nav-item").get(0).click(function(){
    console.log("I am clicked");
});
try this.

You need to call native DOM click() method in order to trigger clicking behavior. This is a exception to ancher tag by jQuery. To get native DOM from jQuery object you can use get(0) or simply [0]. Eg: $(".nav-item").get(0) or $(".nav-item")[0]


问:
Keep task working when the app is in the background
I'm coding a map tracking app on Xamarin forms. I'm using async tasks(with Device.StartTimer) to keep track of the location and another task for counter timer, but when I need to open another app, like a music app or whatever the app can't keep track while it is in the background. All tasks are stopping when I send the app in the background. When I start the app again, the tasks are not continued.
I just need to keep working while app running.

How could this be done?

答:
Due to Background Execution Limits in Android 8.0 or later, Normal service will be killed when in the Background.

In the Android 8.0 or later, I suggest you to achieve a foreground service to achieve that( receive higher priority than a "regular" service and a foreground service must provide a Notification that Android will display as long as the service is running).

You can use dependence service to open a foreground service in xamarin forms.

IService.cs create a interface for android to start service.

```<code>public interface IService
{
  void Start();
}
</code>```

Then achieved DependentService to start a Foreground Service.

DependentService.cs

```<code>[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
  [Service]
public class DependentService : Service, IService
{
public void Start()
{
    var intent = new Intent(Android.App.Application.Context,
    typeof(DependentService));

    if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
    {
        Android.App.Application.Context.StartForegroundService(intent);
    }
    else
    {
        Android.App.Application.Context.StartService(intent);
    }
}

public override IBinder OnBind(Intent intent)
{
    return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
    // From shared code or in your PCL

    CreateNotificationChannel();
    string messageBody = "service starting";

    var notification = new Notification.Builder(this, "10111")
    .SetContentTitle(Resources.GetString(Resource.String.app_name))
    .SetContentText(messageBody)
    .SetSmallIcon(Resource.Drawable.main)
    .SetOngoing(true)
    .Build();
    StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
    //do you work
    return StartCommandResult.Sticky;
}

void CreateNotificationChannel()
{
    if (Build.VERSION.SdkInt < BuildVersionCodes.O)
    {
        // Notification channels are new in API 26 (and not a part of the
        // support library). There is no need to create a notification
        // channel on older versions of Android.
        return;
    }

    var channelName = Resources.GetString(Resource.String.channel_name);
    var channelDescription = GetString(Resource.String.channel_description);
    var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
    {
        Description = channelDescription
    };

    var notificationManager = (NotificationManager)GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(channel);
 }
}
}
</code>```

Here is a similar thread about your needs.
How to create service doing work at period time in Xamarin.Forms?

For IOS background Tasks. you can refer to this thread

Body:
Due to Background Execution Limits in Android 8.0 or later, Normal service will be killed when in the Background.

In the Android 8.0 or later, I suggest you to achieve a foreground service to achieve that( receive higher priority than a "regular" service and a foreground service must provide a Notification that Android will display as long as the service is running).

You can use dependence service to open a foreground service in xamarin forms.

IService.cs create a interface for android to start service.

public interface IService
{
  void Start();
}

Then achieved DependentService to start a Foreground Service.

DependentService.cs

[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
  [Service]
public class DependentService : Service, IService
{
public void Start()
{
    var intent = new Intent(Android.App.Application.Context,
    typeof(DependentService));

    if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
    {
        Android.App.Application.Context.StartForegroundService(intent);
    }
    else
    {
        Android.App.Application.Context.StartService(intent);
    }
}

public override IBinder OnBind(Intent intent)
{
    return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
    // From shared code or in your PCL

    CreateNotificationChannel();
    string messageBody = "service starting";

    var notification = new Notification.Builder(this, "10111")
    .SetContentTitle(Resources.GetString(Resource.String.app_name))
    .SetContentText(messageBody)
    .SetSmallIcon(Resource.Drawable.main)
    .SetOngoing(true)
    .Build();
    StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
    //do you work
    return StartCommandResult.Sticky;
}

void CreateNotificationChannel()
{
    if (Build.VERSION.SdkInt < BuildVersionCodes.O)
    {
        // Notification channels are new in API 26 (and not a part of the
        // support library). There is no need to create a notification
        // channel on older versions of Android.
        return;
    }

    var channelName = Resources.GetString(Resource.String.channel_name);
    var channelDescription = GetString(Resource.String.channel_description);
    var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
    {
        Description = channelDescription
    };

    var notificationManager = (NotificationManager)GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(channel);
 }
}
}

Here is a similar thread about your needs.
How to create service doing work at period time in Xamarin.Forms?

For IOS background Tasks. you can refer to this thread


问:
Vue Tables 2 cells are all outline, like they are selectable
Please help. I have been using Vue Tables 2 for > 2 years now, and I have never had this problem. My table shows up perfectly as usual, but now whenever I click on a cell, it is surrounded by a blue outline on chrome and a dotted outline on firefox.  It is exhibiting the same behavior as if I had clicked on an input. I went through my Vue Tables 2 options one by one, disabling each in turn and it did not change the behavior. I looked through bootstrap 4 tables documentation, and could not find the same behavior as a option, so i believe it is vue tables that is doing it. The demo fiddle on the Vue Tables 2 page also has this behavior. It is very distracting and I am trying to get it to stop.

My goal is to have the table show the behavior it has before, which is to do nothing when you click on a cell.

I am using Bootstrap 4.4, and Vue-Tables-2 version 1.6.25

My options array looks like so

```<code>tableOptions: {
            skin: 'table table-sm table-hover border-0',
            filterable: true,
            pagination: { chunk:4 },
            perPageValues: [],
            perPage: 18,
        dateColumns: ['created_at'],
        dateFormat: 'MM-DD-YYYY',
        toMomentFormat:  'YYYY-MM-DD H:mm:ss',
            texts:{
                filter:"",
                count:"",
                filterPlaceholder:"Search",
                page:"Page:",
                noResults:"No matching records",
                loading:'Loading...',
            },
            columnsClasses: {
                cntCnt: 'text-center noOutline',
                qtCnt: 'text-center noOutline',
                statusName: 'text-center noOutline',
                created_at: 'text-center ',
            },
            headings: {
                id: 'Ref',
                name: 'Name',
                cntCnt: 'Contacts',
                qtCnt: 'Quotes',
                statusName: 'Status',
                created_at: 'Created',
                orgSelect: '',
            },
        }
</code>```

I have added a picture that shows whats going on.The outline is arouns any and every cell I click, including the column headers.

答:
That is the focus selector of CSS whose style is being applied. See here: https://developer.mozilla.org/en-US/docs/Web/CSS/:focus

You need to override this CSS and set border to none.

You can also do this:

```<code>:focus { outline: none; }
</code>```

Body:
Please help. I have been using Vue Tables 2 for > 2 years now, and I have never had this problem. My table shows up perfectly as usual, but now whenever I click on a cell, it is surrounded by a blue outline on chrome and a dotted outline on firefox.  It is exhibiting the same behavior as if I had clicked on an input. I went through my Vue Tables 2 options one by one, disabling each in turn and it did not change the behavior. I looked through bootstrap 4 tables documentation, and could not find the same behavior as a option, so i believe it is vue tables that is doing it. The demo fiddle on the Vue Tables 2 page also has this behavior. It is very distracting and I am trying to get it to stop.

My goal is to have the table show the behavior it has before, which is to do nothing when you click on a cell.

I am using Bootstrap 4.4, and Vue-Tables-2 version 1.6.25

My options array looks like so

tableOptions: {
            skin: 'table table-sm table-hover border-0',
            filterable: true,
            pagination: { chunk:4 },
            perPageValues: [],
            perPage: 18,
        dateColumns: ['created_at'],
        dateFormat: 'MM-DD-YYYY',
        toMomentFormat:  'YYYY-MM-DD H:mm:ss',
            texts:{
                filter:"",
                count:"",
                filterPlaceholder:"Search",
                page:"Page:",
                noResults:"No matching records",
                loading:'Loading...',
            },
            columnsClasses: {
                cntCnt: 'text-center noOutline',
                qtCnt: 'text-center noOutline',
                statusName: 'text-center noOutline',
                created_at: 'text-center ',
            },
            headings: {
                id: 'Ref',
                name: 'Name',
                cntCnt: 'Contacts',
                qtCnt: 'Quotes',
                statusName: 'Status',
                created_at: 'Created',
                orgSelect: '',
            },
        }

I have added a picture that shows whats going on.The outline is arouns any and every cell I click, including the column headers.

Body:
That is the focus selector of CSS whose style is being applied. See here: https://developer.mozilla.org/en-US/docs/Web/CSS/:focus

You need to override this CSS and set border to none.

You can also do this:

:focus { outline: none; }