问:
How to insert image and date in php
```<code>if(isset($_POST['post-submit'])){

    $post_category_id = $_POST['post_category_id'];
    $post_title = $_POST['post_title'];
    $post_author = $_POST['post_author'];
    $post_tags = $_POST['post_tags'];
    $post_status = $_POST['post_status'];

    $post_content = $_POST['post_content'];
    // SQL Injection
    $post_content = mysqli_real_escape_string($connection, $post_content );

    $post_date = date('d-m-y');
    $post_comment_count = 4;

    $post_image = $_FILES['image']['name'];
    $post_image_temp = $_FILES['image']['temp_name'];
    move_uploaded_file($post_image_temp, "../img/blog/$post_image" );

    $query  = "INSERT INTO posts(post_image,post_date,post_comment_count, post_category_id, post_title, post_author, post_tags, post_status, post_content) " ;
    $query .= "VALUES('$post_image', now(), '$post_comment_count' ,'$post_category_id','$post_title','$post_author','$post_tags','$post_status','$post_content')";

    $insert_all_post_query = mysqli_query($connection, $query);

    if(!$insert_all_post_query) {
      die("QUERY FAILED" . mysqli_error($connection));
    } else {
      echo "<h2>Data Sucessfully Updated</h2>";
    }
}
</code>```

Notice: Undefined index: temp_name in C:\xampp\htdocs\cms_admin\admin\postCreate.php on line 35

getting this error - but post is getting inseted perfectly

答:
you are using function now() in column place

you should write column name for example created_at
and if you want current timestamp value in values write there now()

Title: How to insert image and date in php

Body:
if(isset($_POST['post-submit'])){

    $post_category_id = $_POST['post_category_id'];
    $post_title = $_POST['post_title'];
    $post_author = $_POST['post_author'];
    $post_tags = $_POST['post_tags'];
    $post_status = $_POST['post_status'];

    $post_content = $_POST['post_content'];
    // SQL Injection
    $post_content = mysqli_real_escape_string($connection, $post_content );

    $post_date = date('d-m-y');
    $post_comment_count = 4;

    $post_image = $_FILES['image']['name'];
    $post_image_temp = $_FILES['image']['temp_name'];
    move_uploaded_file($post_image_temp, "../img/blog/$post_image" );

    $query  = "INSERT INTO posts(post_image,post_date,post_comment_count, post_category_id, post_title, post_author, post_tags, post_status, post_content) " ;
    $query .= "VALUES('$post_image', now(), '$post_comment_count' ,'$post_category_id','$post_title','$post_author','$post_tags','$post_status','$post_content')";

    $insert_all_post_query = mysqli_query($connection, $query);

    if(!$insert_all_post_query) {
      die("QUERY FAILED" . mysqli_error($connection));
    } else {
      echo "
Data Sucessfully Updated
";
    }
}

Notice: Undefined index: temp_name in C:\xampp\htdocs\cms_admin\admin\postCreate.php on line 35

getting this error - but post is getting inseted perfectly


来源: stackexchange

问:
Reflection api - find subclass type
Hi I am trying to find out the subclass, form an superclass object.

```<code>if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)

Lets say I have a object of Super type as
Super superObject = new Sub1();
</code>```

now for the superObject, is it possible to find which subclass the superObject extends in Java?

Since "SuperClass will not be aware of any SubClasses it has", can you please tell me is my above question valid in the first place, or am I missing any basic concept?

Thanks in advance.

答:
Your question, "is it possible to find which subclass the superObject extends in Java?", is not making any sense.

Anyway, I assume you are looking for Class.isAssignableFrom() might help in this regards.

Usage:

```<code>superClass.isAssignableFrom(subClass);
</code>```

Docs:

Determines if the class or interface
  represented by this Class object is
  either the same as, or is a superclass
  or superinterface of, the class or
  interface represented by the specified
  Class parameter.

Reference

ContentLicense: CC BY-SA 3.0

Title: Reflection api - find subclass type

Body:
Hi I am trying to find out the subclass, form an superclass object.

if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)

Lets say I have a object of Super type as
Super superObject = new Sub1();

now for the superObject, is it possible to find which subclass the superObject extends in Java?

Since "SuperClass will not be aware of any SubClasses it has", can you please tell me is my above question valid in the first place, or am I missing any basic concept?

Thanks in advance.

Body:
Your question, "is it possible to find which subclass the superObject extends in Java?", is not making any sense.

Anyway, I assume you are looking for Class.isAssignableFrom() might help in this regards.

Usage:

superClass.isAssignableFrom(subClass);

Docs:

Determines if the class or interface
  represented by this Class object is
  either the same as, or is a superclass
  or superinterface of, the class or
  interface represented by the specified
  Class parameter.

Reference


问:
Fill holes on cave generated by cellular automata
I'm generating caves for a game. The caves are 50x50 matrix builded by cellular automata, where 0(purple) is wall and 1(yellow) is empty space (where the player can move).Here is an example of my output

I pointed out my problem with the red circles. There are "holes" in the walls which are unreachable by the player. I'm trying to fill this holes but I cannot. Basically I want to turn 1 surrounded by 0 into 0.

I have tried to use floodfill with this approach to do this:

First I count how many cells I paint with floodfill from a starting point x,y. If this count is less than 16 and greater than 1 then I actually paint the cells.

```<code>for x in range(0, WIDTH - 1):
    for y in range(0, HEIGHT - 1):
        number_cells_paint = floodfill_count(cellmap, x, y, number_cells_paint)
        if 16 > len(number_cells_paint) > 1:
            floodfill(cellmap, x, y)

        number_cells_paint = []
</code>```

number_cells_paint is an array where I append every cell I visit in floodfill_count. This is how I think to count inside recursive algorithm and probably where my mistake is.

This is floodfill_count:

```<code>def floodfill_count(cellmap, x, y, number_cells_paint):
  cellmap_aux = cellmap
  if len(number_cells_paint) > 16:
      return number_cells_paint

  if cellmap_aux[x, y] == 1:
      cellmap_aux[x, y] = 0
      number_cells_paint.append(cellmap[x, y])

      if x > 0 and cellmap[x - 1, y] == 1:
          floodfill_count(cellmap_aux, x - 1, y, number_cells_paint)

      if x < WIDTH - 1 and cellmap[x + 1, y] == 1:
          floodfill_count(cellmap_aux, x + 1, y, number_cells_paint)

      if y > 0 and cellmap[x, y - 1] == 1:
          floodfill_count(cellmap_aux, x, y - 1, number_cells_paint)

      if y < HEIGHT - 1 and cellmap[x, y + 1] == 1:
          floodfill_count(cellmap_aux, x, y + 1, number_cells_paint)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y + 1] == 1:
          floodfill_count(cellmap_aux, x + 1, y + 1, number_cells_paint)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y + 1] == 1:
          floodfill_count(cellmap_aux, x - 1, y + 1, number_cells_paint)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y - 1] == 1:
          floodfill_count(cellmap_aux, x + 1, y - 1, number_cells_paint)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y - 1] == 1:
          floodfill_count(cellmap_aux, x - 1, y - 1, number_cells_paint)

  return number_cells_paint
</code>```

and floodfill:

```<code>def floodfill(cellmap, x, y):

  if cellmap[x, y] == 1:
      cellmap[x, y] = 0

      if x > 0 and cellmap[x - 1, y] == 1:
          floodfill(cellmap, x - 1, y)

      if x < WIDTH - 1 and cellmap[x + 1, y] == 1:
          floodfill(cellmap, x + 1, y)

      if y > 0 and cellmap[x, y - 1] == 1:
          floodfill(cellmap, x, y - 1)

      if y < HEIGHT - 1 and cellmap[x, y + 1] == 1:
          floodfill(cellmap, x, y + 1)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y + 1] == 1:
          floodfill(cellmap, x + 1, y + 1)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y + 1] == 1:
          floodfill(cellmap, x - 1, y + 1)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y - 1] == 1:
          floodfill(cellmap, x + 1, y - 1)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y - 1] == 1:
          floodfill(cellmap, x - 1, y - 1)

  return cellmap
</code>```

This implementation of floodfill works, I have tried before so my problem is on floodfill_count.

With this code I have this final output

答: The problem is in cellmap_aux = cellmap this line of code. Python assigned lists as a reference, so any changes to cellmap_aux would be the changes in cellmap (therefore floodfill_count paints all the field). cellmap_aux = cellmap.copy() should be used instead.

ContentLicense: CC BY-SA 4.0

Body:
I'm generating caves for a game. The caves are 50x50 matrix builded by cellular automata, where 0(purple) is wall and 1(yellow) is empty space (where the player can move).Here is an example of my output

I pointed out my problem with the red circles. There are "holes" in the walls which are unreachable by the player. I'm trying to fill this holes but I cannot. Basically I want to turn 1 surrounded by 0 into 0.

I have tried to use floodfill with this approach to do this:

First I count how many cells I paint with floodfill from a starting point x,y. If this count is less than 16 and greater than 1 then I actually paint the cells.

for x in range(0, WIDTH - 1):
    for y in range(0, HEIGHT - 1):
        number_cells_paint = floodfill_count(cellmap, x, y, number_cells_paint)
        if 16 > len(number_cells_paint) > 1:
            floodfill(cellmap, x, y)

        number_cells_paint = []

number_cells_paint is an array where I append every cell I visit in floodfill_count. This is how I think to count inside recursive algorithm and probably where my mistake is.

This is floodfill_count:

def floodfill_count(cellmap, x, y, number_cells_paint):
  cellmap_aux = cellmap
  if len(number_cells_paint) > 16:
      return number_cells_paint

  if cellmap_aux[x, y] == 1:
      cellmap_aux[x, y] = 0
      number_cells_paint.append(cellmap[x, y])

      if x > 0 and cellmap[x - 1, y] == 1:
          floodfill_count(cellmap_aux, x - 1, y, number_cells_paint)

      if x < WIDTH - 1 and cellmap[x + 1, y] == 1:
          floodfill_count(cellmap_aux, x + 1, y, number_cells_paint)

      if y > 0 and cellmap[x, y - 1] == 1:
          floodfill_count(cellmap_aux, x, y - 1, number_cells_paint)

      if y < HEIGHT - 1 and cellmap[x, y + 1] == 1:
          floodfill_count(cellmap_aux, x, y + 1, number_cells_paint)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y + 1] == 1:
          floodfill_count(cellmap_aux, x + 1, y + 1, number_cells_paint)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y + 1] == 1:
          floodfill_count(cellmap_aux, x - 1, y + 1, number_cells_paint)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y - 1] == 1:
          floodfill_count(cellmap_aux, x + 1, y - 1, number_cells_paint)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y - 1] == 1:
          floodfill_count(cellmap_aux, x - 1, y - 1, number_cells_paint)

  return number_cells_paint

and floodfill:

def floodfill(cellmap, x, y):

  if cellmap[x, y] == 1:
      cellmap[x, y] = 0

      if x > 0 and cellmap[x - 1, y] == 1:
          floodfill(cellmap, x - 1, y)

      if x < WIDTH - 1 and cellmap[x + 1, y] == 1:
          floodfill(cellmap, x + 1, y)

      if y > 0 and cellmap[x, y - 1] == 1:
          floodfill(cellmap, x, y - 1)

      if y < HEIGHT - 1 and cellmap[x, y + 1] == 1:
          floodfill(cellmap, x, y + 1)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y + 1] == 1:
          floodfill(cellmap, x + 1, y + 1)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y + 1] == 1:
          floodfill(cellmap, x - 1, y + 1)

      if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y - 1] == 1:
          floodfill(cellmap, x + 1, y - 1)

      if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y - 1] == 1:
          floodfill(cellmap, x - 1, y - 1)

  return cellmap

This implementation of floodfill works, I have tried before so my problem is on floodfill_count.

With this code I have this final output


问:
SPOJ Factorial Problem
I am trying to develop code for SPOJ factorial problem number 11. The following is my code

```<code>import java.math.*;
import java.io.*;
public class Problem11 {

/**
 * Count the number of zeroes at the end of
 * the factorial value of a number.
 */
public static void main(String[] args) throws IOException
{
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 int numOfInputs=0;
 numOfInputs=Integer.parseInt(br.readLine());
 BigInteger nextNum[]=new BigInteger[numOfInputs];
 BigInteger factValue[]=new BigInteger[numOfInputs];

 //Get all the numbers to be computed
 for(int count=0;count<numOfInputs;count++)
 {
    nextNum[count]=new BigInteger(br.readLine());
 }

 //Obtain the factorial value for each number
 for(int count=0;count<numOfInputs;count++)
 {
     factValue[count]=getFact(nextNum[count]);
 }

 //Obtain the number of trailing zeroes
 for(int count=0;count<numOfInputs;count++)
 {
     //System.out.println(factValue[count]);
     System.out.println(getZeroes(factValue[count]));

 }
}

public static String getZeroes(BigInteger num)
 {
    int numOfZeroes=0;
    while(num.remainder(BigInteger.TEN).equals(BigInteger.ZERO))
    {
        num=num.divide(BigInteger.TEN);
        numOfZeroes++;
    }
    return String.valueOf(numOfZeroes);
 }

public static BigInteger getFact(BigInteger num)
{
    BigInteger factorial=BigInteger.ONE;
    if(num.equals(0))
    {
      return (BigInteger.valueOf(1));
    }
    else
    {
        int count=1;
        while((BigInteger.valueOf(count).compareTo(num))<=0)
        {
            factorial=factorial.multiply(BigInteger.valueOf(count));
            count++;
        }
    }

    return factorial;

}

}
</code>```

The code works fine for numbers up to 5 digits with small delay and for the last number
8735373 it is taking too much time, if I submit my solution, the judge shows compilation error.. I am unable to figure out whats the error. Please have a look at my code and help me to trace the problem.

答:
```<code>import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
        while (t-->0){
            int n = s.nextInt();
            int count = 0;
            while(n>0){
                count +=n/5;
                n/=5;
            }
            System.out.println(count);
        }

    }
}
</code>```

This solution will work absolutely fine.
Let me explain it.
When you refer to quantitative aptitude there is a short formula for calculating the number of trailing zeroes for any factorial number. Divide the number directly by 5 and start adding quotient and then divide quotient with 5 and again add until the value start giving constant quotient. Refer to below example. If you don't even understand refer to quantitative aptitude from any source.

e.g.

```<code>1. 60!  60/5 = 12, 12/5 = 2, add all the quotient i.e equals to 14.
2. 500! 500/5 = 100, 100/5 = 20, 20/5 = 4, ans = 124.
</code>```

Title: SPOJ Factorial Problem

Body:
I am trying to develop code for SPOJ factorial problem number 11. The following is my code

import java.math.*;
import java.io.*;
public class Problem11 {

/**
 * Count the number of zeroes at the end of
 * the factorial value of a number.
 */
public static void main(String[] args) throws IOException
{
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 int numOfInputs=0;
 numOfInputs=Integer.parseInt(br.readLine());
 BigInteger nextNum[]=new BigInteger[numOfInputs];
 BigInteger factValue[]=new BigInteger[numOfInputs];

 //Get all the numbers to be computed
 for(int count=0;count<numOfInputs;count++)
 {
    nextNum[count]=new BigInteger(br.readLine());
 }

 //Obtain the factorial value for each number
 for(int count=0;count<numOfInputs;count++)
 {
     factValue[count]=getFact(nextNum[count]);
 }

 //Obtain the number of trailing zeroes
 for(int count=0;count<numOfInputs;count++)
 {
     //System.out.println(factValue[count]);
     System.out.println(getZeroes(factValue[count]));

 }
}

public static String getZeroes(BigInteger num)
 {
    int numOfZeroes=0;
    while(num.remainder(BigInteger.TEN).equals(BigInteger.ZERO))
    {
        num=num.divide(BigInteger.TEN);
        numOfZeroes++;
    }
    return String.valueOf(numOfZeroes);
 }

public static BigInteger getFact(BigInteger num)
{
    BigInteger factorial=BigInteger.ONE;
    if(num.equals(0))
    {
      return (BigInteger.valueOf(1));
    }
    else
    {
        int count=1;
        while((BigInteger.valueOf(count).compareTo(num))<=0)
        {
            factorial=factorial.multiply(BigInteger.valueOf(count));
            count++;
        }
    }

    return factorial;

}

}

The code works fine for numbers up to 5 digits with small delay and for the last number
8735373 it is taking too much time, if I submit my solution, the judge shows compilation error.. I am unable to figure out whats the error. Please have a look at my code and help me to trace the problem.

Body:
import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
        while (t-->0){
            int n = s.nextInt();
            int count = 0;
            while(n>0){
                count +=n/5;
                n/=5;
            }
            System.out.println(count);
        }

    }
}

This solution will work absolutely fine.
Let me explain it.
When you refer to quantitative aptitude there is a short formula for calculating the number of trailing zeroes for any factorial number. Divide the number directly by 5 and start adding quotient and then divide quotient with 5 and again add until the value start giving constant quotient. Refer to below example. If you don't even understand refer to quantitative aptitude from any source.

e.g.

1. 60!  60/5 = 12, 12/5 = 2, add all the quotient i.e equals to 14.
2. 500! 500/5 = 100, 100/5 = 20, 20/5 = 4, ans = 124.


问:
Is it possible to create a VectorDrawable from File System (*.xml File)
I am trying to use VectorDrawables in my Android App.

I want to load an xml File from the File System and get an Instance of android.graphics.Drawable to display it in an ImageView.  If i add the xml File to the Resources directory it works. But when i try to load it from the filesystem i always get a NullPointer.

I am currently trying to load the File via
Drawable.createFromPath(*Path to File*) or VectorDrawable.createFromPath(*Path to File*), but i keep getting a NullPointer.
The File exists and is a valid xml File (see below).

In adb log i always get :

```<code>SkImageDecoder::Factory returned null
</code>```

When i use  mContext.getFilesDir() the Path looks something like

```<code>/data/data/*packagename*/files/*filename*.xml
</code>```

I also tried some public Folders like "Downloads". When i check the File with the File.io Api it exists(), canRead() and canWrite()

Update This ist the XML Code taken from the android Dev Pages

```<code> <vector xmlns:android="http://schemas.android.com/apk/res/android"
 android:height="64dp"
 android:width="64dp"
 android:viewportHeight="600"
 android:viewportWidth="600" >
 <group
     android:name="rotationGroup"
     android:pivotX="300.0"
     android:pivotY="300.0"
     android:rotation="45.0" >
     <path
         android:name="v"
         android:fillColor="#000000"
         android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />
 </group>
</code>```

答:
Yes, it is possible but sadly according to what someone shown me, it has multiple disadvantages:

Requires reflection, so might not work some day

The reflection is on private API, which is not recommended

Works only on compiled VectorDrawable XML files.

That being said, maybe you could create your own XmlPullParser by looking at the code of other libraries, such as here (or my fork of it, here). The interesting class name there is "BinaryXmlParser", which I think might help. I tried using other methods, but it caused an exception of java.lang.ClassCastException: android.util.XmlPullAttributes cannot be cast to android.content.res.XmlBlock$Parser , so maybe it wants to use only the reflected XmlBlock class, which means even if you do implement it, I think there is a good chance it won't work.

Here's the code (based on here) :

```<code>object VectorDrawableParser {
    /**
     * Create a vector drawable from a binary XML byte array.
     *
     * @param context Any context.
     * @param binXml  Byte array containing the binary XML.
     * @return The vector drawable or null it couldn't be created.
     */
    @SuppressLint("PrivateApi", "DiscouragedPrivateApi")
    fun getVectorDrawable(context: Context, binXml: ByteArray): Drawable? {
        try {
            // Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable
            // This is the equivalent of what AssetManager#getXml() does
            val xmlBlock = Class.forName("android.content.res.XmlBlock")
            val xmlBlockConstr = xmlBlock.getConstructor(ByteArray::class.java)
            val xmlParserNew = xmlBlock.getDeclaredMethod("newParser")
            xmlBlockConstr.isAccessible = true
            xmlParserNew.isAccessible = true
            val parser = xmlParserNew.invoke(xmlBlockConstr.newInstance(binXml)) as XmlPullParser
            return if (Build.VERSION.SDK_INT >= 24) {
                Drawable.createFromXml(context.resources, parser)
            } else {
                // Before API 24, vector drawables aren't rendered correctly without compat lib
                val attrs = Xml.asAttributeSet(parser)
                var type = parser.next()
                while (type != XmlPullParser.START_TAG) {
                    type = parser.next()
                }
                VectorDrawableCompat.createFromXmlInner(context.resources, parser, attrs, null)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}
</code>```

And how to use:

```<code>val filePath = "/storage/emulated/0/abc_vector_test.xml"
val readBytes = FileInputStream(File(filePath)).readBytes()
val vectorDrawable = VectorDrawableParser.getVectorDrawable(this, readBytes)
Log.d("AppLog", "got it?${vectorDrawable != null}")
</code>```

Body:
I am trying to use VectorDrawables in my Android App.

I want to load an xml File from the File System and get an Instance of android.graphics.Drawable to display it in an ImageView.  If i add the xml File to the Resources directory it works. But when i try to load it from the filesystem i always get a NullPointer.

I am currently trying to load the File via
Drawable.createFromPath(*Path to File*) or VectorDrawable.createFromPath(*Path to File*), but i keep getting a NullPointer.
The File exists and is a valid xml File (see below).

In adb log i always get :

SkImageDecoder::Factory returned null

When i use  mContext.getFilesDir() the Path looks something like

/data/data/*packagename*/files/*filename*.xml

I also tried some public Folders like "Downloads". When i check the File with the File.io Api it exists(), canRead() and canWrite()

Update This ist the XML Code taken from the android Dev Pages

 <vector xmlns:android="http://schemas.android.com/apk/res/android"
 android:height="64dp"
 android:width="64dp"
 android:viewportHeight="600"
 android:viewportWidth="600" >
 <group
     android:name="rotationGroup"
     android:pivotX="300.0"
     android:pivotY="300.0"
     android:rotation="45.0" >
     <path
         android:name="v"
         android:fillColor="#000000"
         android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />
 </group>

Body:
Yes, it is possible but sadly according to what someone shown me, it has multiple disadvantages:

Requires reflection, so might not work some day

The reflection is on private API, which is not recommended

Works only on compiled VectorDrawable XML files.

That being said, maybe you could create your own XmlPullParser by looking at the code of other libraries, such as here (or my fork of it, here). The interesting class name there is "BinaryXmlParser", which I think might help. I tried using other methods, but it caused an exception of java.lang.ClassCastException: android.util.XmlPullAttributes cannot be cast to android.content.res.XmlBlock$Parser , so maybe it wants to use only the reflected XmlBlock class, which means even if you do implement it, I think there is a good chance it won't work.

Here's the code (based on here) :

object VectorDrawableParser {
    /**
     * Create a vector drawable from a binary XML byte array.
     *
     * @param context Any context.
     * @param binXml  Byte array containing the binary XML.
     * @return The vector drawable or null it couldn't be created.
     */
    @SuppressLint("PrivateApi", "DiscouragedPrivateApi")
    fun getVectorDrawable(context: Context, binXml: ByteArray): Drawable? {
        try {
            // Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable
            // This is the equivalent of what AssetManager#getXml() does
            val xmlBlock = Class.forName("android.content.res.XmlBlock")
            val xmlBlockConstr = xmlBlock.getConstructor(ByteArray::class.java)
            val xmlParserNew = xmlBlock.getDeclaredMethod("newParser")
            xmlBlockConstr.isAccessible = true
            xmlParserNew.isAccessible = true
            val parser = xmlParserNew.invoke(xmlBlockConstr.newInstance(binXml)) as XmlPullParser
            return if (Build.VERSION.SDK_INT >= 24) {
                Drawable.createFromXml(context.resources, parser)
            } else {
                // Before API 24, vector drawables aren't rendered correctly without compat lib
                val attrs = Xml.asAttributeSet(parser)
                var type = parser.next()
                while (type != XmlPullParser.START_TAG) {
                    type = parser.next()
                }
                VectorDrawableCompat.createFromXmlInner(context.resources, parser, attrs, null)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}

And how to use:

val filePath = "/storage/emulated/0/abc_vector_test.xml"
val readBytes = FileInputStream(File(filePath)).readBytes()
val vectorDrawable = VectorDrawableParser.getVectorDrawable(this, readBytes)
Log.d("AppLog", "got it?${vectorDrawable != null}")


问:
RazorPages anchor tag helper with multiple parameters
Here's the RazorPages page I'm trying to make a link to:

```<code>@page "{ReportId:int}/{SicCode:alpha?}"
</code>```

This works

```<code><a asp-page="/ReportSics" asp-route-ReportId="3">rs1</a>
</code>```

it produces

```<code><a href="/Reports/ReportSics/3">rs1</a>
</code>```

But this produces a blank href.

```<code><a asp-page="/ReportSics" asp-route-ReportId="3" asp-route-SicCode="10">rss2</a>
</code>```

That is: the tag helper works with one parameter but not with two.
Why?
Is it possible to make it work?

(I have another page with the same @page but with the second parameter not optional and it appears to be impossible to create a link to it.)

Furthermore, requesting Page/2/M works, but Page/2/12 returns 404. Why? (The second parameter is a string that can sometimes be a number, but it always treated as a string.)

答: It turns out that if a parameter has the constraint :alpha then it only works if the value being passed can not be parsed as an int or float.

Body:
Here's the RazorPages page I'm trying to make a link to:

@page "{ReportId:int}/{SicCode:alpha?}"

This works

rs1

it produces

rs1

But this produces a blank href.

rss2

That is: the tag helper works with one parameter but not with two.
Why?
Is it possible to make it work?

(I have another page with the same @page but with the second parameter not optional and it appears to be impossible to create a link to it.)

Furthermore, requesting Page/2/M works, but Page/2/12 returns 404. Why? (The second parameter is a string that can sometimes be a number, but it always treated as a string.)


问:
SwiftUI - Navigation bar colour change not being applied to status bar
I have the following:

```<code>var body: some View {
        NavigationView {
            VStack {
                 Text("Hello")
            }.navigationBarTitle("Edit Profile", displayMode: .inline)
             .background(NavigationConfiguration { nc in
                 nc.navigationBar.barTintColor = .red
                 nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black]
            })
        }.navigationViewStyle(StackNavigationViewStyle())
}
</code>```

For the configuration of the nav bar i have:

```<code>struct NavigationConfiguration: UIViewControllerRepresentable {
    var configuration: (UINavigationController) -> Void = { _ in }
    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfiguration>) -> UIViewController {
        UIViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfiguration>) {
        if let nc = uiViewController.navigationController {
            self.configuration(nc)
        }
    }
}
</code>```

But for some reason the top status bar is being left out and the colour is not being applied to it:

How can the red colour also be applied to the status bar above the nav bar, I want it to be the same colour.

I've tried the below, but this fails:

```<code>init() {
    UINavigationBar.appearance().backgroundColor = .red
}
</code>```

答:
Try the following (it should work, at least as tested with Xcode 11.4 / iOS 13.4, but someone reported it was not, so it might be dependent)

```<code>init() {
       let navBarAppearance = UINavigationBarAppearance()
       navBarAppearance.configureWithOpaqueBackground()
       navBarAppearance.backgroundColor = UIColor.systemRed

       UINavigationBar.appearance().standardAppearance = navBarAppearance
}
</code>```

Body:
I have the following:

var body: some View {
        NavigationView {
            VStack {
                 Text("Hello")
            }.navigationBarTitle("Edit Profile", displayMode: .inline)
             .background(NavigationConfiguration { nc in
                 nc.navigationBar.barTintColor = .red
                 nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black]
            })
        }.navigationViewStyle(StackNavigationViewStyle())
}

For the configuration of the nav bar i have:

struct NavigationConfiguration: UIViewControllerRepresentable {
    var configuration: (UINavigationController) -> Void = { _ in }
    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfiguration>) -> UIViewController {
        UIViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfiguration>) {
        if let nc = uiViewController.navigationController {
            self.configuration(nc)
        }
    }
}

But for some reason the top status bar is being left out and the colour is not being applied to it:

How can the red colour also be applied to the status bar above the nav bar, I want it to be the same colour.

I've tried the below, but this fails:

init() {
    UINavigationBar.appearance().backgroundColor = .red
}

Body:
Try the following (it should work, at least as tested with Xcode 11.4 / iOS 13.4, but someone reported it was not, so it might be dependent)

init() {
       let navBarAppearance = UINavigationBarAppearance()
       navBarAppearance.configureWithOpaqueBackground()
       navBarAppearance.backgroundColor = UIColor.systemRed

       UINavigationBar.appearance().standardAppearance = navBarAppearance
}


问:
How to show user specific data on the list based on a many to many relationship using Symfony 5 EasyAdmin Bundle
I am very new to EasyAdmin bundle. I was trying to load user specific content in the list of a logged in user.

So here is my composer.json file:

```<code>{
"type": "project",
"license": "proprietary",
"require": {
    "php": "^7.2.5",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "easycorp/easyadmin-bundle": "^2.3",
    "sensio/framework-extra-bundle": "^5.1",
    "symfony/asset": "5.0.*",
    "symfony/console": "5.0.*",
    "symfony/dotenv": "5.0.*",
    "symfony/expression-language": "5.0.*",
    "symfony/flex": "^1.3.1",
    "symfony/form": "5.0.*",
    "symfony/framework-bundle": "5.0.*",
    "symfony/http-client": "5.0.*",
    "symfony/intl": "5.0.*",
    "symfony/mailer": "5.0.*",
    "symfony/monolog-bundle": "^3.1",
    "symfony/notifier": "5.0.*",
    "symfony/orm-pack": "*",
    "symfony/process": "5.0.*",
    "symfony/security-bundle": "5.0.*",
    "symfony/serializer-pack": "*",
    "symfony/string": "5.0.*",
    "symfony/translation": "5.0.*",
    "symfony/twig-pack": "*",
    "symfony/validator": "5.0.*",
    "symfony/web-link": "5.0.*",
    "symfony/yaml": "5.0.*"
},
</code>```

I have a Project Requirements entity which has a many to many relationship with the User entity like the following:

```<code>/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="User", inversedBy="projectRequirementsHasUserProjectRequirements")
 * @ORM\JoinTable(name="project_requirements_has_user",
 *   joinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_project_requirements_id", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_user_id", referencedColumnName="id")
 *   }
 * )
 */
private $projectRequirementsHasUserUser;

/**
 * Constructor
 */
public function __construct()
{
    $this->projectRequirementsHasUserUser = new \Doctrine\Common\Collections\ArrayCollection();
}
</code>```

So when adding requirements I can assign user like this:

You can see that the first requirements has assigned to 2 users:

Now I want to show all the requirements which has assigned to the logged in user.

I came to know that I need to override the default EasyAdminController, so I configured my entity in config/packages/easy_admin.yaml:

```<code>    # Project Planning
    ProjectRequirements:
      controller: App\Controller\ProjectRequirementsController
      class: App\Entity\ProjectRequirements
</code>```

And then create a controller but don't know how to write the filter or query to select only the requirements which has assigned to the logged in user:

```<code><?php
namespace App\Controller;

use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;

class ProjectRequirementsController extends EasyAdminController {

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{

    /** @var QueryBuilder $result  */
    $result = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);

    return $result;

}
</code>```

}

Any help is highly appreciable.

答:
After searching a lot about 2 days finally I understand how EasyAdmin and Symfony QueryBuilder works. It was nice to find the solution by myself. So here is what I came up with the solution:

```<code># App\Controller\ProjectRequirementsController.php

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{
    /** @var QueryBuilder $result  */
    $result = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);

    # Getting data User wise
    $result->leftJoin('entity.projectRequirementsHasUserUser', 'user')
    ->andWhere('user.id = :user')
    ->setParameter('user', $this->getUser());

    return $result;

}
</code>```

Hope this helps someone in the future.

Body:
I am very new to EasyAdmin bundle. I was trying to load user specific content in the list of a logged in user.

So here is my composer.json file:

{
"type": "project",
"license": "proprietary",
"require": {
    "php": "^7.2.5",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "easycorp/easyadmin-bundle": "^2.3",
    "sensio/framework-extra-bundle": "^5.1",
    "symfony/asset": "5.0.*",
    "symfony/console": "5.0.*",
    "symfony/dotenv": "5.0.*",
    "symfony/expression-language": "5.0.*",
    "symfony/flex": "^1.3.1",
    "symfony/form": "5.0.*",
    "symfony/framework-bundle": "5.0.*",
    "symfony/http-client": "5.0.*",
    "symfony/intl": "5.0.*",
    "symfony/mailer": "5.0.*",
    "symfony/monolog-bundle": "^3.1",
    "symfony/notifier": "5.0.*",
    "symfony/orm-pack": "*",
    "symfony/process": "5.0.*",
    "symfony/security-bundle": "5.0.*",
    "symfony/serializer-pack": "*",
    "symfony/string": "5.0.*",
    "symfony/translation": "5.0.*",
    "symfony/twig-pack": "*",
    "symfony/validator": "5.0.*",
    "symfony/web-link": "5.0.*",
    "symfony/yaml": "5.0.*"
},

I have a Project Requirements entity which has a many to many relationship with the User entity like the following:

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="User", inversedBy="projectRequirementsHasUserProjectRequirements")
 * @ORM\JoinTable(name="project_requirements_has_user",
 *   joinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_project_requirements_id", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_user_id", referencedColumnName="id")
 *   }
 * )
 */
private $projectRequirementsHasUserUser;

/**
 * Constructor
 */
public function __construct()
{
    $this->projectRequirementsHasUserUser = new \Doctrine\Common\Collections\ArrayCollection();
}

So when adding requirements I can assign user like this:

You can see that the first requirements has assigned to 2 users:

Now I want to show all the requirements which has assigned to the logged in user.

I came to know that I need to override the default EasyAdminController, so I configured my entity in config/packages/easy_admin.yaml:

    # Project Planning
    ProjectRequirements:
      controller: App\Controller\ProjectRequirementsController
      class: App\Entity\ProjectRequirements

And then create a controller but don't know how to write the filter or query to select only the requirements which has assigned to the logged in user:

<?php
namespace App\Controller;

use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;

class ProjectRequirementsController extends EasyAdminController {

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{

    /** @var QueryBuilder $result  */
    $result = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);

    return $result;

}

}

Any help is highly appreciable.

Body:
After searching a lot about 2 days finally I understand how EasyAdmin and Symfony QueryBuilder works. It was nice to find the solution by myself. So here is what I came up with the solution:

# App\Controller\ProjectRequirementsController.php

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{
    /** @var QueryBuilder $result  */
    $result = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);

    # Getting data User wise
    $result->leftJoin('entity.projectRequirementsHasUserUser', 'user')
    ->andWhere('user.id = :user')
    ->setParameter('user', $this->getUser());

    return $result;

}

Hope this helps someone in the future.


问:
hide text from printing but keeping the space
We have in-house server which brings the records by php from mysql.

We have Dot matrix printer which we are using for printing on carbon less paper (2 copies:- one for official records,one for customer and one for gatekeeper).

We tried to print the content by display:none but it was removing that space from that Div.

Then we tried to print it with the white color font without display:none (we realized that print head reads everything), so it was printing the characters on the 2nd and 3rd copy.

So We want to know how can hide the text at the same time by keeping that much space blank.

Please tell how to do the same thing with border ?

thanks in advance

答: you can keep the div with text in one div with height and width and give style display:none property to the div with text. this way the space will remain


问:
Template metaprogramming to match function signature exactly
With template meta-programming it's possible to query properties of types. For example in the case below I'm checking if a certain type has a member function "foo" which takes in another type as the argument.

Is there a way to check if the parameter type is an exact match for the template vs. one that be converted to it, e.g. double or char can be converted into float (causing main to print true twice) but I'm trying to see if there is a way to structure my_test_t so that it matches perfectly, i.e. main() prints false unless T2 = float.

```<code>struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype(declval<T1>().foo(declval<T2>()));

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{
};

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t<my_test_t<T1, T2>>> : std::true_type
{
};

int main()
{
   cout << boolalpha << is_formed<S2, double>::value << endl;
   cout << boolalpha << is_formed<S2, char>::value << endl;
}
</code>```

答:
```<code>#include <type_traits>
#include <utility>

template <typename C, typename P>
auto test(short) -> std::false_type;

template <typename C, typename P>
auto test(int)
    -> decltype(static_cast<decltype(std::declval<C&>().foo(std::declval<P>())) (C::*)(P)>(&C::foo)
              , std::true_type{});

template <typename C, typename P>
using my_test_t = decltype(test<C, P>(0));
</code>```

DEMO

Body:
With template meta-programming it's possible to query properties of types. For example in the case below I'm checking if a certain type has a member function "foo" which takes in another type as the argument.

Is there a way to check if the parameter type is an exact match for the template vs. one that be converted to it, e.g. double or char can be converted into float (causing main to print true twice) but I'm trying to see if there is a way to structure my_test_t so that it matches perfectly, i.e. main() prints false unless T2 = float.

struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype(declval<T1>().foo(declval<T2>()));

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{
};

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t<my_test_t<T1, T2>>> : std::true_type
{
};

int main()
{
   cout << boolalpha << is_formed<S2, double>::value << endl;
   cout << boolalpha << is_formed<S2, char>::value << endl;
}

Body:
#include <type_traits>
#include <utility>

template <typename C, typename P>
auto test(short) -> std::false_type;

template <typename C, typename P>
auto test(int)
    -> decltype(static_cast<decltype(std::declval<C&>().foo(std::declval<P>())) (C::*)(P)>(&C::foo)
              , std::true_type{});

template <typename C, typename P>
using my_test_t = decltype(test<C, P>(0));

DEMO


问:
Apollo react hooks array object mutation
So I am doing a MARN stack using MongoDB, Apollo, React Native (Expo) and Node

I am stuck trying to figure out how to upload an array of object. i.e  A post with an array of shots

It is all working fine in the Apollo playground with this:

```<code>mutation createPost {
  createPost(
    input: {
      shots: [
        {
          title: "Test test test"
          content: "Test test test"
          image: "https://source.unsplash.com/random/768x768"
        }
        {
          title: "Best best best"
          content: "Test test test"
          image: "https://source.unsplash.com/random/768x768"
        }
      ]
    }
  ) {
    id
    shots {
      id
    }
  }
}
</code>```

And this is my server schema:

```<code>  type Post {
    id: ID!
    shots: [Shot]!
  }

  type Shot {
    id: ID!
    title: String
    content: String
    image: String
  }

  input CreatePostInput {
    shots: [ShotInput]!
  }

  input ShotInput {
    title: String!
    content: String!
    image: String!
  }
</code>```

Now this is my react mutation, the part I am stuck on. Because it is generating an error and I have no idea how to fix it.
If I replace $shots with a static array of objects, it works! Do I need to use some fancy @relation tag or something?

```<code>const CREATE_POST = gql`
  mutation createPost($shots: [ShotInput]) {
    createPost(input: { shots: $shots }) {
      id
      shots {
        id
      }
    }
  }
`;

</code>```

This is how I am triggering the error:

```<code><Button
  title="Button"
  onPress={() => {
    createPost({
      variables: { shots: [{ title: 'test', content: 'test', image: 'test' }] },
    });
  }}
/>
</code>```

And this is the error I can't shake

```<code>[GraphQL error]: Message: Variable "$shots" of type "[ShotInput]" used in position expecting type "[ShotInput]!"., Location: [object Object],[object Object], Path: undefined
</code>```

Regardless of this little hurdle, I gotta say that Apollo is the bees knees! Absolute awesomeness!!!

答:
I figured it out. I was so close the whole time!!!

All I was missing was an exclamation "!" at createPost()

```<code>const CREATE_POST = gql`
  mutation createPost($shots: [ShotInput!]! <===== Right here) {
    createPost(input: { shots: $shots }) {
      id
      shots {
        id
      }
    }
  }
`;
</code>```

Ouch that hurt! So many variables at play. Lesson learned!!!

Body:
So I am doing a MARN stack using MongoDB, Apollo, React Native (Expo) and Node

I am stuck trying to figure out how to upload an array of object. i.e  A post with an array of shots

It is all working fine in the Apollo playground with this:

mutation createPost {
  createPost(
    input: {
      shots: [
        {
          title: "Test test test"
          content: "Test test test"
          image: "https://source.unsplash.com/random/768x768"
        }
        {
          title: "Best best best"
          content: "Test test test"
          image: "https://source.unsplash.com/random/768x768"
        }
      ]
    }
  ) {
    id
    shots {
      id
    }
  }
}

And this is my server schema:

  type Post {
    id: ID!
    shots: [Shot]!
  }

  type Shot {
    id: ID!
    title: String
    content: String
    image: String
  }

  input CreatePostInput {
    shots: [ShotInput]!
  }

  input ShotInput {
    title: String!
    content: String!
    image: String!
  }

Now this is my react mutation, the part I am stuck on. Because it is generating an error and I have no idea how to fix it.
If I replace $shots with a static array of objects, it works! Do I need to use some fancy @relation tag or something?

const CREATE_POST = gql`
  mutation createPost($shots: [ShotInput]) {
    createPost(input: { shots: $shots }) {
      id
      shots {
        id
      }
    }
  }
`;

This is how I am triggering the error:

<Button
  title="Button"
  onPress={() => {
    createPost({
      variables: { shots: [{ title: 'test', content: 'test', image: 'test' }] },
    });
  }}
/>

And this is the error I can't shake

[GraphQL error]: Message: Variable "$shots" of type "[ShotInput]" used in position expecting type "[ShotInput]!"., Location: [object Object],[object Object], Path: undefined

Regardless of this little hurdle, I gotta say that Apollo is the bees knees! Absolute awesomeness!!!

Body:
I figured it out. I was so close the whole time!!!

All I was missing was an exclamation "!" at createPost()

const CREATE_POST = gql`
  mutation createPost($shots: [ShotInput!]! <===== Right here) {
    createPost(input: { shots: $shots }) {
      id
      shots {
        id
      }
    }
  }
`;

Ouch that hurt! So many variables at play. Lesson learned!!!


问:
Almost the same statements, but different value
I'm working on a classic DP question, Count Subset Sum.

The problem statement is as follows if you are not sure about the problem:
Given a set of positive numbers, find the total number of subsets whose sum is equal to a given number ‘S’.

I'm trying to work solve it with backtracking approach.

Assume the given array is [1, 1, 2, 3] and the sum is 4, so the expected result is 3

The weird thing is the code blow works fine, and it generates the correct result.

  private int backtrack2(int[] nums, int sum) {
    int[] count = new int[1];
    backtrack2Helper(nums, sum, count, 0);
    return count[0];
  }

  private int backtrack2Helper(int[] nums, int sum, int[] count, int pos) {
    if (0 == sum) return 1;
    if (pos == nums.length) return 0;

    for (int i = pos; i < nums.length; ++i) {
      if (sum - nums[i] >= 0) {
        int temp = backtrack2Helper(nums, sum - nums[i], count, i + 1);
        count[0] += temp;
      }
    }

    return 0;
  }
```

<p>However, the code below can not generate the correct result:</p>

<pre class="lang-java prettyprint-override"><code>  private int backtrack2(int[] nums, int sum) {
    int[] count = new int[1];
    backtrack2Helper(nums, sum, count, 0);
    return count[0];
  }

  private int backtrack2Helper(int[] nums, int sum, int[] count, int pos) {
    if (0 == sum) return 1;
    if (pos == nums.length) return 0;

    for (int i = pos; i < nums.length; ++i) {
      if (sum - nums[i] >= 0) {
        count[0] += backtrack2Helper(nums, sum - nums[i], count, i + 1);
      }
    }

    return 0;
  }
</code>```

The only difference is the if statement part in the helper function.

int temp = backtrack2Helper(nums, sum - nums[i], count, i + 1);
count[0] += temp;
```

<p>and </p>

<pre class="lang-java prettyprint-override"><code>count[0] += backtrack2Helper(nums, sum - nums[i], count, i + 1);
</code>```

should be equivalent, right?

But the second one does not work correctly.
I was really confused and I debugged it step by step, finding that when the method in the second approach hit the return statement at last, count[0] was not added by the returned 0, but set to 0.

What's happening?

答:
The difference results from the fact that backtrack2Helper() changes count[0].

Suppose, for example, that backtrack2Helper(nums, sum - nums[i], count, i + 1) changes that value of count[0] from 0 to 1 and returns 1.

In one snippet you are adding the changed value of count[0] to the value returned by the recursive call:

```<code>int temp = backtrack2Helper(nums, sum - nums[i], count, i + 1); // == 1
count[0] += temp; // == 1 + 1 == 2
</code>```

But in the other snippet you are adding the original value of count[0] to the value returned by the recursive call:

```<code>count[0] += backtrack2Helper(nums, sum - nums[i], count, i + 1); // == 0 + 1 == 1
</code>```

EDIT:

You can write a more elegant solution without the count[] array:

```<code>private static int backtrack2(int[] nums, int sum) {
    return backtrack2Helper(nums, sum, 0);
}

private static int backtrack2Helper(int[] nums, int sum, int pos) {
    if (0 == sum)
        return 1;
    if (pos == nums.length)
        return 0;
    int count = 0;
    for (int i = pos; i < nums.length; ++i) {
        if (sum - nums[i] >= 0) {
            count += backtrack2Helper(nums, sum - nums[i], i + 1);
        }
    }

    return count;
}
</code>```

EDIT:

To improve the explanation regarding the difference of the two snippets, here's a simpler code that produces the same behavior:

```<code>int method2 (int[] arr)
{
   arr[0] = 5;
   return 0;
}
</code>```

First snippet:

```<code>void method1 ()
{
    int[] arr = new int[1]; // arr[0] is 0
    int temp = method2 (arr); // temp is assigned 0, arr[0] is changed to 5 by method2
    arr[0] += temp // arr[0] = arr[0] + temp == 5 + 0 == 5
}
</code>```

Second snippet:

```<code>void method1 ()
{
    int[] arr = new int[1]; // arr[0] is 0
    arr[0] += method2 (arr); // arr[0] = arr[0] + method2 (arr) == 0 + 0 == 0
}
</code>```

Body:
I'm working on a classic DP question, Count Subset Sum.

The problem statement is as follows if you are not sure about the problem:
Given a set of positive numbers, find the total number of subsets whose sum is equal to a given number ‘S’.

I'm trying to work solve it with backtracking approach.

Assume the given array is [1, 1, 2, 3] and the sum is 4, so the expected result is 3

The weird thing is the code blow works fine, and it generates the correct result.

  private int backtrack2(int[] nums, int sum) {
    int[] count = new int[1];
    backtrack2Helper(nums, sum, count, 0);
    return count[0];
  }

  private int backtrack2Helper(int[] nums, int sum, int[] count, int pos) {
    if (0 == sum) return 1;
    if (pos == nums.length) return 0;

    for (int i = pos; i < nums.length; ++i) {
      if (sum - nums[i] >= 0) {
        int temp = backtrack2Helper(nums, sum - nums[i], count, i + 1);
        count[0] += temp;
      }
    }

    return 0;
  }

However, the code below can not generate the correct result:

  private int backtrack2(int[] nums, int sum) {
    int[] count = new int[1];
    backtrack2Helper(nums, sum, count, 0);
    return count[0];
  }

  private int backtrack2Helper(int[] nums, int sum, int[] count, int pos) {
    if (0 == sum) return 1;
    if (pos == nums.length) return 0;

    for (int i = pos; i < nums.length; ++i) {
      if (sum - nums[i] >= 0) {
        count[0] += backtrack2Helper(nums, sum - nums[i], count, i + 1);
      }
    }

    return 0;
  }

The only difference is the if statement part in the helper function.

int temp = backtrack2Helper(nums, sum - nums[i], count, i + 1);
count[0] += temp;

and

count[0] += backtrack2Helper(nums, sum - nums[i], count, i + 1);

should be equivalent, right?

But the second one does not work correctly.
I was really confused and I debugged it step by step, finding that when the method in the second approach hit the return statement at last, count[0] was not added by the returned 0, but set to 0.

What's happening?

Body:
The difference results from the fact that backtrack2Helper() changes count[0].

Suppose, for example, that backtrack2Helper(nums, sum - nums[i], count, i + 1) changes that value of count[0] from 0 to 1 and returns 1.

In one snippet you are adding the changed value of count[0] to the value returned by the recursive call:

int temp = backtrack2Helper(nums, sum - nums[i], count, i + 1); // == 1
count[0] += temp; // == 1 + 1 == 2

But in the other snippet you are adding the original value of count[0] to the value returned by the recursive call:

count[0] += backtrack2Helper(nums, sum - nums[i], count, i + 1); // == 0 + 1 == 1

EDIT:

You can write a more elegant solution without the count[] array:

private static int backtrack2(int[] nums, int sum) {
    return backtrack2Helper(nums, sum, 0);
}

private static int backtrack2Helper(int[] nums, int sum, int pos) {
    if (0 == sum)
        return 1;
    if (pos == nums.length)
        return 0;
    int count = 0;
    for (int i = pos; i < nums.length; ++i) {
        if (sum - nums[i] >= 0) {
            count += backtrack2Helper(nums, sum - nums[i], i + 1);
        }
    }

    return count;
}

EDIT:

To improve the explanation regarding the difference of the two snippets, here's a simpler code that produces the same behavior:

int method2 (int[] arr)
{
   arr[0] = 5;
   return 0;
}

First snippet:

void method1 ()
{
    int[] arr = new int[1]; // arr[0] is 0
    int temp = method2 (arr); // temp is assigned 0, arr[0] is changed to 5 by method2
    arr[0] += temp // arr[0] = arr[0] + temp == 5 + 0 == 5
}

Second snippet:

void method1 ()
{
    int[] arr = new int[1]; // arr[0] is 0
    arr[0] += method2 (arr); // arr[0] = arr[0] + method2 (arr) == 0 + 0 == 0
}


问:
Memory Limit Exceed in Vector C++
I'm getting memory limit exceeded error for this code. I can't find the way to resolve it. If I'm taking  a long long int it gives the same error.

Why this error happening?

```<code>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
    ///1000000000000 500000000001 getting memory limit exceed for this test case.

    ll n,k;
    cin>>n>>k;
    vector<ll> v;
    vector<ll> arrange;

    for(ll i=0;i<n;i++)
    {
        v.push_back(i+1);
    }

    //Arranging vector like 1,3,5,...2,4,6,....
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2!=0)
        {
            arrange.push_back(v[i]);
        }
    }
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2==0)
        {
            arrange.push_back(v[i]);
        }
    }
    cout<<arrange[k-1]<<endl; // Found the kth number.

    return 0;
}
</code>```

答:
Assume long long int is a 8 byte type. This is a commonly valid assumptions.
For every entry in the array, you are requesting to allocate 8 byte.

If you request to allocate 1000000000000 items, your are requesting to allocate 8 Terabyte of memory.

Moreover you are using two arrays and you are requesting to allocate more than 8 Terabyte.

Just use a lower number of items for your arrays and it will work.

Title: Memory Limit Exceed in Vector C++

Body:
I'm getting memory limit exceeded error for this code. I can't find the way to resolve it. If I'm taking  a long long int it gives the same error.

Why this error happening?

#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
    ///1000000000000 500000000001 getting memory limit exceed for this test case.

    ll n,k;
    cin>>n>>k;
    vector<ll> v;
    vector<ll> arrange;

    for(ll i=0;i<n;i++)
    {
        v.push_back(i+1);
    }

    //Arranging vector like 1,3,5,...2,4,6,....
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2!=0)
        {
            arrange.push_back(v[i]);
        }
    }
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2==0)
        {
            arrange.push_back(v[i]);
        }
    }
    cout<<arrange[k-1]<<endl; // Found the kth number.

    return 0;
}


问:
My bootstrap navbar toggler is not working
Please check the code to help me finding error. When I click on the toggle button it doesn't work i.e. doesn't show menu bar.</p>

```<code><body>
<!--navigation bar-->
<nav class="navbar navbar-expand-sm navbar-dark bg-danger pl-5 fixed-top">
<div class="container">
<a class="navbar-brand " href="index.php">E-SERVICE</a>
<span class="navbar-text">our service your happiness</span>
<button type="button" class="navbar-toggler" data-toggle="collapse" date-target="#myMenu">
<span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse" id="myMenu">
 <ul  class="nav-list navbar-nav pl-5">
    <li  class="nav-item"><a  class="nav-link" href="index.php">Home</a></li>
    <li  class="nav-item"><a  class="nav-link" href="#Services">Services</a></li>
    <li  class="nav-item"><a  class="nav-link" href="#Registration">Registration</a></li>
    <li  class="nav-item"><a  class="nav-link" href="#Login">Login</a></li>
    <li  class="nav-item"><a  class="nav-link" href="#Contact">Contact</a></li>
</ul>
</div>
</div>
</div>

</nav>
</code>```

```<code><!--javascript-->
<script src="js/jquery.min.js"></script>
<script src="js/pooper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/all.min.js"></script>
</body>
</code>```

答:
You just have a typo error and it shall work after you change the following.

Change

```<code>date-target="#myMenu"
</code>```

to

```<code>data-target="#myMenu"
</code>```

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

      E-SERVICE
      our service your happiness
      <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#myMenu">

</button>

Home

Services

Registration

Login

Contact

  ```

Body:
Please check the code to help me finding error. When I click on the toggle button it doesn't work i.e. doesn't show menu bar.

E-SERVICE
our service your happiness
<button type="button" class="navbar-toggler" data-toggle="collapse" date-target="#myMenu">

</button>

Home

Services

Registration

Login

Contact

Body:
You just have a typo error and it shall work after you change the following.

Change

date-target="#myMenu"

to

data-target="#myMenu"

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

<body>
  <!--navigation bar-->
  <nav class="navbar navbar-expand-sm navbar-dark bg-danger pl-5 fixed-top">
    <div class="container">
      <a class="navbar-brand " href="index.php">E-SERVICE</a>
      <span class="navbar-text">our service your happiness</span>
      <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#myMenu">
<span class="navbar-toggler-icon"></span>
</button>

      <div class="collapse navbar-collapse" id="myMenu">
        <ul class="nav-list navbar-nav pl-5">
          <li class="nav-item"><a class="nav-link" href="index.php">Home</a></li>
          <li class="nav-item"><a class="nav-link" href="#Services">Services</a></li>
          <li class="nav-item"><a class="nav-link" href="#Registration">Registration</a></li>
          <li class="nav-item"><a class="nav-link" href="#Login">Login</a></li>
          <li class="nav-item"><a class="nav-link" href="#Contact">Contact</a></li>
        </ul>
      </div>
    </div>
    </div>

  </nav>


问:
How can you iterate over the elements of an std::tuple?
How can I iterate over a tuple (using C++11)? I tried the following:

```<code>for(int i=0; i<std::tuple_size<T...>::value; ++i)
  std::get<i>(my_tuple).do_sth();
</code>```

but this doesn't work:

Error 1: sorry, unimplemented: cannot expand ‘Listener ...’ into a fixed-length argument list.

  Error 2: i cannot appear in a constant expression.

So, how do I correctly iterate over the elements of a tuple?

答:
Expanding on @Stypox answer, we can make their solution more generic (C++17 onward). By adding a callable function argument:

```<code>template<size_t I = 0, typename... Tp, typename F>
void for_each_apply(std::tuple<Tp...>& t, F &&f) {
    f(std::get<I>(t));
    if constexpr(I+1 != sizeof...(Tp)) {
        for_each_apply<I+1>(t, std::forward<F>(f));
    }
}
</code>```

Then, we need a strategy to visit each type.

Let start with some helpers (first two taken from cppreference):

```<code>template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
template<class ... Ts> struct variant_ref { using type = std::variant<std::reference_wrapper<Ts>...>; };
</code>```

variant_ref is used to allow tuples' state to be modified.

Usage:

```<code>std::tuple<Foo, Bar, Foo> tuples;

for_each_apply(tuples,
               [](variant_ref<Foo, Bar>::type &&v) {
                   std::visit(overloaded {
                       [](Foo &arg) { arg.foo(); },
                       [](Bar const &arg) { arg.bar(); },
                   }, v);
               });
</code>```

Result:

```<code>Foo0
Bar
Foo0
Foo1
Bar
Foo1
</code>```

For completeness, here are my Bar & Foo:

```<code>struct Foo {
    void foo() {std::cout << "Foo" << i++ << std::endl;}
    int i = 0;
};
struct Bar {
    void bar() const {std::cout << "Bar" << std::endl;}
};
</code>```

Body:
How can I iterate over a tuple (using C++11)? I tried the following:

for(int i=0; i<std::tuple_size<T...>::value; ++i)
  std::get(my_tuple).do_sth();

but this doesn't work:

Error 1: sorry, unimplemented: cannot expand ‘Listener ...’ into a fixed-length argument list.

  Error 2: i cannot appear in a constant expression.

So, how do I correctly iterate over the elements of a tuple?

Body:
Expanding on @Stypox answer, we can make their solution more generic (C++17 onward). By adding a callable function argument:

template<size_t I = 0, typename... Tp, typename F>
void for_each_apply(std::tuple<Tp...>& t, F &&f) {
    f(std::get<I>(t));
    if constexpr(I+1 != sizeof...(Tp)) {
        for_each_apply<I+1>(t, std::forward<F>(f));
    }
}

Then, we need a strategy to visit each type.

Let start with some helpers (first two taken from cppreference):

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
template<class ... Ts> struct variant_ref { using type = std::variant<std::reference_wrapper<Ts>...>; };

variant_ref is used to allow tuples' state to be modified.

Usage:

std::tuple<Foo, Bar, Foo> tuples;

for_each_apply(tuples,
               [](variant_ref<Foo, Bar>::type &&v) {
                   std::visit(overloaded {
                       [](Foo &arg) { arg.foo(); },
                       [](Bar const &arg) { arg.bar(); },
                   }, v);
               });

Result:

Foo0
Bar
Foo0
Foo1
Bar
Foo1

For completeness, here are my Bar & Foo:

struct Foo {
    void foo() {std::cout << "Foo" << i++ << std::endl;}
    int i = 0;
};
struct Bar {
    void bar() const {std::cout << "Bar" << std::endl;}
};


问:
How to avoid memory leaks with complex RxJS pipes in Angular 9?
I have this little bit complex pipe structure in my Angular + RxJS app:

remote-data.service.ts:

getAll(url): Observable<any[]> {
  return this.http.get(url, this.options)
    .pipe(map((result: any[]) => result));
}
```

<p><strong>proxy.service.ts:</strong></p>

<pre class="lang-js prettyprint-override"><code>// localDataService use my LocalDataService
// remoteDataService use my RemoteDataService

getAll(model): Observable<any[]> {
  if (model.use_localstorage) {
    return this.localDataService.getAll(model)
      .pipe(map((result: any[]) => result));
  } else {
    return this.remoteDataService.getAll(model.url)
      .pipe(map((result: any[]) => result));
  }
}
</code>```

helper.service.ts:

getAll(model): Observable<any[]> {
  // do some general fancy things...
  return this.proxyService.getAll(model)
      .pipe(map((result: any) => result));
  }
}
```

<p>Then in my <strong>component</strong>:</p>

<pre class="lang-js prettyprint-override"><code>export class MyComponent {
  helperService = new HelperService();
  model = new MyModel();

  getAll() {
    this.helperService.getAll().subscribe((result: any[]) => {
      // parse result
    });
  }
}
</code>```

As you see I build a pipeline from remote data service, proxy service, helper servcice and the component. Of course the reason is to separate each functions from eachother and make my services more reuseable.

My goal is to avoid the memory leaks.

And the question is: if I want to put a take(1) RxJS operator into my pipeline it's enough to put it into the end of pipeline, before the .subscribe() or need to put it every services and component too?

What is the best practice in this case to avoid memory leaks?

答:
It depends. pipe(take(1)) ensures you get a "single Value observable" meaning, that it will emit one value then completes, and closes the subscription, hence no memoryleak.
If your Service or function per se emits only a Single value pipe(take(1)) does nothing.

For Example if you have a REST call, with httpclient.get(...) it may have a delay. Then you should use pipe(timeout(3000)) or pipe(takeUntil(...)) to make sure to not have a subscritpion alive, if your component or whatever is destroyed you don't have a memory leak or unexpeced behaviour of the logic inside the subsription. Even with pipe(take(1)) a memoryleak can exist because it will only complete after exactly one value or error is emitted.

So if you have a http.get() and it has a network delay. And you would use "pipe(take(1))" it would still cause a memory leak because it waits for exactly one value, and the subscription will be triggered when the value arrives, even if the Component in wich you made the call is destroyed or you have navigated to an other View of your application.

takeUntil(...) is usefull for components, if they are destroyed you could trigger the ending of a subscription in ngDestroy().

```<code>  public isActive = new Subject();

  public ngOnDestroy(): void {
    this.isActive.next(false);
  }

  public fun():void{
    this.fooService.getValue()
                     .pipe(takeUntil(this.isActive))
                     .subscribe( value => console.log(value));
  }
</code>```

If the Observable/Subject completes there should be no memoryleak after the last value is emitted.

You need to take care of those cases, if you are not sure, there is a "complete()" or if it emits only One value but the latency could be problematic.

The memoryleaks are btw the secondary problem, and not even that big. MOre problematic is, that the logic of your subscribe could be triggered, when you don't want to anymore.
Sometimes you want to trigger the logic in the subscription (for example a notification to tell the user something was successful) even though the user already left the view.
So it depends.

Also you could store All subscritions in on Single Subscription and unsubscribe if you want to dispose them.

```<code>  public subs = new Subscription();

  public ngOnDestroy(): void {
    this.subs.unsubscribe();
  }

  public fun():void{
    const bar: Subscription = this.fooService.getValue()
                     .subscribe( value => console.log(value));
    this.subs.add(bar);
  }
</code>```

Body:
I have this little bit complex pipe structure in my Angular + RxJS app:

remote-data.service.ts:

getAll(url): Observable<any[]> {
  return this.http.get(url, this.options)
    .pipe(map((result: any[]) => result));
}

proxy.service.ts:

// localDataService use my LocalDataService
// remoteDataService use my RemoteDataService

getAll(model): Observable<any[]> {
  if (model.use_localstorage) {
    return this.localDataService.getAll(model)
      .pipe(map((result: any[]) => result));
  } else {
    return this.remoteDataService.getAll(model.url)
      .pipe(map((result: any[]) => result));
  }
}

helper.service.ts:

getAll(model): Observable<any[]> {
  // do some general fancy things...
  return this.proxyService.getAll(model)
      .pipe(map((result: any) => result));
  }
}

Then in my component:

export class MyComponent {
  helperService = new HelperService();
  model = new MyModel();

  getAll() {
    this.helperService.getAll().subscribe((result: any[]) => {
      // parse result
    });
  }
}

As you see I build a pipeline from remote data service, proxy service, helper servcice and the component. Of course the reason is to separate each functions from eachother and make my services more reuseable.

My goal is to avoid the memory leaks.

And the question is: if I want to put a take(1) RxJS operator into my pipeline it's enough to put it into the end of pipeline, before the .subscribe() or need to put it every services and component too?

What is the best practice in this case to avoid memory leaks?

Body:
It depends. pipe(take(1)) ensures you get a "single Value observable" meaning, that it will emit one value then completes, and closes the subscription, hence no memoryleak.
If your Service or function per se emits only a Single value pipe(take(1)) does nothing.

For Example if you have a REST call, with httpclient.get(...) it may have a delay. Then you should use pipe(timeout(3000)) or pipe(takeUntil(...)) to make sure to not have a subscritpion alive, if your component or whatever is destroyed you don't have a memory leak or unexpeced behaviour of the logic inside the subsription. Even with pipe(take(1)) a memoryleak can exist because it will only complete after exactly one value or error is emitted.

So if you have a http.get() and it has a network delay. And you would use "pipe(take(1))" it would still cause a memory leak because it waits for exactly one value, and the subscription will be triggered when the value arrives, even if the Component in wich you made the call is destroyed or you have navigated to an other View of your application.

takeUntil(...) is usefull for components, if they are destroyed you could trigger the ending of a subscription in ngDestroy().

  public isActive = new Subject();

  public ngOnDestroy(): void {
    this.isActive.next(false);
  }

  public fun():void{
    this.fooService.getValue()
                     .pipe(takeUntil(this.isActive))
                     .subscribe( value => console.log(value));
  }

If the Observable/Subject completes there should be no memoryleak after the last value is emitted.

You need to take care of those cases, if you are not sure, there is a "complete()" or if it emits only One value but the latency could be problematic.

The memoryleaks are btw the secondary problem, and not even that big. MOre problematic is, that the logic of your subscribe could be triggered, when you don't want to anymore.
Sometimes you want to trigger the logic in the subscription (for example a notification to tell the user something was successful) even though the user already left the view.
So it depends.

Also you could store All subscritions in on Single Subscription and unsubscribe if you want to dispose them.

  public subs = new Subscription();

  public ngOnDestroy(): void {
    this.subs.unsubscribe();
  }

  public fun():void{
    const bar: Subscription = this.fooService.getValue()
                     .subscribe( value => console.log(value));
    this.subs.add(bar);
  }


问:
If a station simultaneously maintains three TCP connections,can use the same TCP port for the three connections?
If a station simultaneously maintains three TCP connections,can use the same TCP port  for the three connections? If yes how it could distinguish packets?</p>

答:
Each connection is made of the below parameters.

(source ip,source port destination ip, destination port, protocol).

Thus, the station can distinguish packets.


问:
Having trouble outputting the menu from a php json file to html
I was given a task which basically takes a json file and outputs the contents to a menu via javascript.  I have some code drawn out but it is not working.  The task needs to output the JSON file to html via api so that a customer can order.  Also it has to save the order as a JSON string to localstorage(browser). And finally it needs to basically spit out their order with the button (onClick).  So right now my problem is a.  when I add the id of "order" to the container div element my page goes white.  I dunno why that happens, but I would like to keep this format(design) if possible.  Secondly, well there is no second since output whites out my page lol.  But I need to get past this first hurdle first.  I will share my code (html, js, and css).  Any help or pointers would be appreciated!

//get menu from api
var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
  "pepperoni": ".25",
  "meatballs": ".35",
  "mushrooms": ".40",
  "olives": ".20"
},
"sides": {
  "potato salad": "1.25",
  "hummus": "2.50",
  "caesar salad": "3.50",
  "garden salad": "2.25"
},
"drinks": {
  "soda": {
    "small": "1.95",
    "medium": "2.20",
    "large": "2.50"
  },
  "juice": "2.00",
  "water": "1.25"
   }
   }
  }
 */

getJSON('https://mm214.com/menu.php', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {

    var content = '';

    for (x in data.menu) {
      if (typeof(data.menu[x]) == 'object') {
        for (y in data.menu[x]) {
          if (typeof(data.menu[x][y]) == 'object') {
            for (z in data.menu[x][y]) {
              content += z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '">
';
            }
          } else {
            content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '">
';
          }
        } //closes y in data

      } else {
        content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '">
';

      } //else for data.menu[x] if not an object
    }
  } //closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  document.getElementById("menuOutput").innerHTML = content;
  localStorage.setItem('order', JSON.stringify(data));
  console.log(a + ':' + order[a]);

  var order = JSON.parse(localStorage.getItem('order'));
  console.log(typeof(order));
  for (a in order) {}

});

function storeOrder() {
  var pizzaqty = document.getElementById('qty_slice of pizza').value;
  localStorage.setItem('pizza', pizzaqty);
  var price = pizzaqty * 2;
}

function retrieveOrder() {
  var pizzaordered = localStorage.getItem('pizza');
}

//output html
//
//document.getElementById("menuOutput").innerHTML = "Here is the menu:
" + data.menu;
//why in't this working?

//style menu for ordering
//save order as json string
//save in local storage
//your order button

//onclick: show order
document.getElementById('order').innerHTML = localStorage.getItem('order1');
```

<pre class="lang-html prettyprint-override"><code><h1 class="menu">Menu</h1>
<div class="grid">
  <div class="two">
    <h2>Pizza by the slice ($2)</h2>
    <input type="number" id="qty_slice of pizza">
    <h2>Toppings</h2>
    <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
    <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
    <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
    <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
  </div>

  <div class="one">
    <h2>Sides</h2>
    <p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
    <p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
    <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
    <p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
  </div>

  <div class="three">
    <h2>Drinks</h2>
    <div>

      <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
      <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
      <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
    </div>
    <hr>
    <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
    <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

  </div>
</div><br>
<div class="button">
  <button class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<script src="./run.js"></script>
</code>```

答:
Here is a start.

You could do a more elegant recurse, but that is much harder than a little non-dry code

You will need to add checkboxes and/or quantity fields

When you do, you need to use addEventListener("input") on the fields

You then need to loop/map the content of the inputs and use JSON.stringify("order",order) and reverse that in the load event handler

const getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

const fNum = str => {
  str = str.trim()
  return str && !isNaN(str) ? "$" + Number(str).toFixed(2) : str;
};

getJSON('https://mm214.com/menu.php', function(err, data) {
  // console.log(data)
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    const container = document.getElementById("menuOutput");
    const menu = data.menu;
    Object.keys(menu).forEach(key => {
      const div = document.createElement("div");
      const header = document.createElement("h2");
      header.textContent = key
      div.appendChild(header)
      const sub = menu[key];
      if (typeof sub === 'object') {
        Object.keys(sub).forEach(subKey => {
          const subDiv = document.createElement("div")
          const subHeader = document.createElement("h3")
          subHeader.textContent = subKey;
          subDiv.appendChild(subHeader)
          const subsub = sub[subKey];
          if (typeof subsub === 'object') {
            Object.keys(subsub).forEach(subsubKey => {
              const p = document.createElement("p")
              p.textContent = subsubKey + ": " + fNum(subsub[subsubKey]);
              subDiv.appendChild(p)
            });
          } else {
            subHeader.appendChild(document.createTextNode(": " + fNum(subsub)))
          }

          div.appendChild(subDiv)
        })
      } else {
        header.appendChild(document.createTextNode(": " + fNum(sub)))
      }

      container.appendChild(div)
    })

  } //closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  // document.getElementById("menuOutput").innerHTML = content;
  // localStorage.setItem('order', JSON.stringify(data));
  // console.log(a + ':' + order[a]);

  //  var order = JSON.parse(localStorage.getItem('order'));
  //  console.log(typeof(order));
  // for (a in order) {}

});

//style menu for ordering
//save order as json string
//save in local storage
//your order button

//onclick: show order
//document.getElementById('order').innerHTML = localStorage.getItem('order1');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2,
h3 {
  text-transform: capitalize
}</code>```

Menu

  <button class="button" id="submitOrder">Review Order</button>

```

Body:
I was given a task which basically takes a json file and outputs the contents to a menu via javascript.  I have some code drawn out but it is not working.  The task needs to output the JSON file to html via api so that a customer can order.  Also it has to save the order as a JSON string to localstorage(browser). And finally it needs to basically spit out their order with the button (onClick).  So right now my problem is a.  when I add the id of "order" to the container div element my page goes white.  I dunno why that happens, but I would like to keep this format(design) if possible.  Secondly, well there is no second since output whites out my page lol.  But I need to get past this first hurdle first.  I will share my code (html, js, and css).  Any help or pointers would be appreciated!

//get menu from api
var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
  "pepperoni": ".25",
  "meatballs": ".35",
  "mushrooms": ".40",
  "olives": ".20"
},
"sides": {
  "potato salad": "1.25",
  "hummus": "2.50",
  "caesar salad": "3.50",
  "garden salad": "2.25"
},
"drinks": {
  "soda": {
    "small": "1.95",
    "medium": "2.20",
    "large": "2.50"
  },
  "juice": "2.00",
  "water": "1.25"
   }
   }
  }
 */

getJSON('https://mm214.com/menu.php', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {

    var content = '';

    for (x in data.menu) {
      if (typeof(data.menu[x]) == 'object') {
        for (y in data.menu[x]) {
          if (typeof(data.menu[x][y]) == 'object') {
            for (z in data.menu[x][y]) {
              content += z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '">
';
            }
          } else {
            content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '">
';
          }
        } //closes y in data

      } else {
        content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '">
';

      } //else for data.menu[x] if not an object
    }
  } //closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  document.getElementById("menuOutput").innerHTML = content;
  localStorage.setItem('order', JSON.stringify(data));
  console.log(a + ':' + order[a]);

  var order = JSON.parse(localStorage.getItem('order'));
  console.log(typeof(order));
  for (a in order) {}

});

function storeOrder() {
  var pizzaqty = document.getElementById('qty_slice of pizza').value;
  localStorage.setItem('pizza', pizzaqty);
  var price = pizzaqty * 2;
}

function retrieveOrder() {
  var pizzaordered = localStorage.getItem('pizza');
}

//output html
//
//document.getElementById("menuOutput").innerHTML = "Here is the menu:
" + data.menu;
//why in't this working?

//style menu for ordering
//save order as json string
//save in local storage
//your order button

//onclick: show order
document.getElementById('order').innerHTML = localStorage.getItem('order1');

Menu

Pizza by the slice ($2)

    <input type="number" id="qty_slice of pizza">

Toppings

Per Pepperoni($0.25):
 <input type="number" id="qty_pepperoni">

Per Meatball($0.35):
 <input type="number" id="qty_meatballs">

Per Mushhroom($0.40):
 <input type="number" id="qty_mushrooms">

Per Olive($0.20):
 <input type="number" id="qty_olives">

Sides

Potato Salad($1.25):
 <input type="number" id="qty_potato salad">

Humus($2.50):
 <input type="number" id="qty_hummus">

Caesar Salad($3.50):
 <input type="number" id="qty_caesar salad">

Garden Salad($2.25):
 <input type="number" id="qty_garden salad">

Drinks

Small Soda($1.95):
 <input type="number" id="qty_small">

Medium Soda($2.20):
 <input type="number" id="qty_medium">

Large Soda($2.50):
 <input type="number" id="qty_large">

Juice($2.00):
 <input type="number" id="qty_juice">

Water($1.25):
 <input type="number" id="qty_water">

  <button class="button" id="submitOrder">Review Order</button>

Body:
Here is a start.

You could do a more elegant recurse, but that is much harder than a little non-dry code

You will need to add checkboxes and/or quantity fields

When you do, you need to use addEventListener("input") on the fields

You then need to loop/map the content of the inputs and use JSON.stringify("order",order) and reverse that in the load event handler

const getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

const fNum = str => {
  str = str.trim()
  return str && !isNaN(str) ? "$" + Number(str).toFixed(2) : str;
};

getJSON('https://mm214.com/menu.php', function(err, data) {
  // console.log(data)
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    const container = document.getElementById("menuOutput");
    const menu = data.menu;
    Object.keys(menu).forEach(key => {
      const div = document.createElement("div");
      const header = document.createElement("h2");
      header.textContent = key
      div.appendChild(header)
      const sub = menu[key];
      if (typeof sub === 'object') {
        Object.keys(sub).forEach(subKey => {
          const subDiv = document.createElement("div")
          const subHeader = document.createElement("h3")
          subHeader.textContent = subKey;
          subDiv.appendChild(subHeader)
          const subsub = sub[subKey];
          if (typeof subsub === 'object') {
            Object.keys(subsub).forEach(subsubKey => {
              const p = document.createElement("p")
              p.textContent = subsubKey + ": " + fNum(subsub[subsubKey]);
              subDiv.appendChild(p)
            });
          } else {
            subHeader.appendChild(document.createTextNode(": " + fNum(subsub)))
          }

          div.appendChild(subDiv)
        })
      } else {
        header.appendChild(document.createTextNode(": " + fNum(sub)))
      }

      container.appendChild(div)
    })

  } //closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  // document.getElementById("menuOutput").innerHTML = content;
  // localStorage.setItem('order', JSON.stringify(data));
  // console.log(a + ':' + order[a]);

  //  var order = JSON.parse(localStorage.getItem('order'));
  //  console.log(typeof(order));
  // for (a in order) {}

});

//style menu for ordering
//save order as json string
//save in local storage
//your order button

//onclick: show order
//document.getElementById('order').innerHTML = localStorage.getItem('order1');

h2,
h3 {
  text-transform: capitalize
}

<h1 class="menu">Menu</h1>
<div class="grid">
  <!-- div class="two">
    <h2>Pizza by the slice ($2)</h2>
    <input type="number" id="qty_slice of pizza">
    <h2>Toppings</h2>
    <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
    <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
    <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
    <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
  </div>

  <div class="one">
    <h2>Sides</h2>
    <p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
    <p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
    <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
    <p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
  </div>

  <div class="three">
    <h2>Drinks</h2>
    <div>

      <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
      <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
      <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
    </div>
    <hr>
    <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
    <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

  </div-->
</div><br>
<div class="button">
  <button class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<div id="menuOutput"></div>


问:
How to sort digits after certain characters (-) in mysql
Can sort digits after certain characters in mysql.

Thank you for help,,

答:
You can extract each of the 3 parts of id_coba with the function substring_index() and convert each part to a number and then sort:

```<code>order by
  id_coba + 0,
  substring_index(substring_index(id_coba, '_', -1), '-', 1) + 0,
  substring_index(id_coba, '-', -1) + 0
</code>```

See the demo.

Results:

```<code>| id  | id_coba  |
| --- | -------- |
| 1   | 1_20-1   |
| 2   | 1_20-8   |
| 3   | 1_20-15  |
| 4   | 1_20-120 |
| 9   | 1_21-8   |
| 10  | 1_21-15  |
| 7   | 2_20-9   |
| 5   | 2_20-23  |
</code>```

Body:
You can extract each of the 3 parts of id_coba with the function substring_index() and convert each part to a number and then sort:

order by
  id_coba + 0,
  substring_index(substring_index(id_coba, '_', -1), '-', 1) + 0,
  substring_index(id_coba, '-', -1) + 0

See the demo.

Results:

| id  | id_coba  |
| --- | -------- |
| 1   | 1_20-1   |
| 2   | 1_20-8   |
| 3   | 1_20-15  |
| 4   | 1_20-120 |
| 9   | 1_21-8   |
| 10  | 1_21-15  |
| 7   | 2_20-9   |
| 5   | 2_20-23  |


问:
How to disable file colouring in git-enabled folder in pycharm?
I use dark mode in pycharm. When folders are enabled with git, the coloring of the files at the left-hand-side project folder looks dark in dark mode. How can I disable file colouring in git-enabled folder in pycharm? It is straining the eyes.

I am using Pycharm community 2020.1

答: You cannot disable dark mode for a portion of the PyCharm UI separately. The problem you are facing might be due to wrong installation or something like that. Reinstallation or update of PyCharm might help. </p>


问:
How to retain on client end when getting access token using REST API using Laravel Passport
I stucked in a logic & unable to find till yet that how to resolve it. Please find the below details for the same:

I am developing an application in Laravel 7. In this laravel section i have developed:

Admin section using the Laravel's AUTH module with bootstrap 4.

Developed REST API using Passport package. (The point to be noted in the API's, that these API's will be consumed via cross-domain by our external users or clients) .

Access Token is generated perfectly on the basis of Unique Client Id & Secret Key which we are providing to each clients specifically.

Now comes to the part where external users trying consuming our API's built under the LARAVEL 7 using Passport authentication. Please find the steps:

Client is using pure jQuery (3.x) & JavaScript to achieve it.

Client hits the login API by using Client Id & Secret Key via jQuery Ajax.

After validating the keys we return the token value to the client.

Post getting the Bearer Token, client able to access the other secured data via API's by setting that Bearer token at header in AJAX. Client consuming our API's via jQuery AJAX only.

The problem arises when client refreshes the web page. As client refreshes the web page the client won't be able to retain the received token. As client is already authenticated and received the token in the 2&3 step, but as client refreshes the web page client won't be able to find that generated access token.

So, is there any way we maintain the same token, instead of generating the new token each time without revoking the last generated access token, when client refreshes the web page. Shall we maintain that token using session cookies i.e.; it retains the token value until client closes the browser.

答:
Yes, you can store the token in the browser using Cookies, sesisonStorage or localStorage

Cookies

using cookie

```<code>document.cookie = "access_token=my_access_token";
</code>```

browsers cookies are not very easy to handle directly, there is already a question with many answers here on how to set, update and delete cookies

Session Storage

Using sessionStorage (easier to handle compared to cookie) keeps the token till session ends (or close browser)

```<code>sessionStorage.setItem('access_token', 'my_access_token');
let access_token = sessionStorage.getItem('access_token');
</code>```

Local Storage

Using localstorage, you can persist the token, it would be available even after browser is closed and reopened

```<code>localStorage.setItem('access_token', 'my_access_token');
let access_token = localStorage.getItem('access_token');
</code>```

Just note that you would need to delete the token from localStorage, it won't auto expire. You should also revoke tokens on the server when user logs out

Body:
Yes, you can store the token in the browser using Cookies, sesisonStorage or localStorage

Cookies

using cookie

document.cookie = "access_token=my_access_token";

browsers cookies are not very easy to handle directly, there is already a question with many answers here on how to set, update and delete cookies

Session Storage

Using sessionStorage (easier to handle compared to cookie) keeps the token till session ends (or close browser)

sessionStorage.setItem('access_token', 'my_access_token');
let access_token = sessionStorage.getItem('access_token');

Local Storage

Using localstorage, you can persist the token, it would be available even after browser is closed and reopened

localStorage.setItem('access_token', 'my_access_token');
let access_token = localStorage.getItem('access_token');

Just note that you would need to delete the token from localStorage, it won't auto expire. You should also revoke tokens on the server when user logs out


问:
linux recv() function flag parameter?
What will happen if I use recv(sockfd, buffer, len, 0); on a non-blocking socket?

If the socket sockfd is closed or nothing to be read, does the recv() block? (note: the flag in recv () is 0).

答:
If the socket is marked non blocking, recv will never block. period.

If the socket is fine but there is no data to be read you will get -1 as return value and errno will be set to EAGAIN.

If there is an error (closed socket etc.), you still get a -1 return value but errno will be set to the appropriate value.

Title: linux recv() function flag parameter?