问:
Deserialize List with newtonsoft json problem
I am learning the Newtonsoft JSON library in C#.

I have a class called "enemy" that descends from the "Ente" class.
I have a list of type "Ente".
In this list I add some instances of the "enemy" class and serialize the list, all correct.
Then, with the list empty, I read the JSON file from disk, deserialize it and assign the result to the list of type "Ente".
All correct but ... enemy objects are created using the constructor of the class "Ente", this is the problem, the objects should be created by calling the constructor of the class "Enemy", that is to say, objects "Enemy" must be created and not "Ente" objects.

**Edit 1:

I have other classes that also descend from "Ente" and the instances must be saved in the "EnteList" list.
For example, these are other classes that descend from "Ente":

Enemy: Ente

BallOfFire: Ente

Troll: Ente

etc...

In the example I simplified it to the maximum and thought that it was not necessary to give that information.
I think the newtonsoft library should do this automatically because I am specifying to save the object type that is in the list in the JSON file when serializing it.**

The question is: What do I need to do to make the "Enemy" object constructor run at the time of deserialization?

List:

public List< Ente > EnteList { get; set; } = new List< Ente >();

Code serialization and deserialization:

```<code>        EnteList.Add( new Enemy( ) );
        JsonSerializerSettings setting = new JsonSerializerSettings();
        setting.TypeNameHandling = TypeNameHandling.Objects;
        string json = JsonConvert.SerializeObject( EnteList, Formatting.Indented, setting );
        EnteList.Clear();
        EnteList = JsonConvert.DeserializeObject< List< Ente > >( json );
</code>```

Class Ente and Enemy:

```<code>public class Ente
{
    public Ente()
    {
        Console.WriteLine( "\n Constructor of Ente executed" );
    }
}

public class Enemy : Ente
{
    public Enemy()
    {
        Console.WriteLine( "\n Constructor of Enemy executed" );
    }
}
</code>```

答:
EDITED

I've understood you.

try this:

```<code>class Program
{
    public static List<Ente> EnteList { get; set; } = new List<Ente>();

    static void Main(string[] args)
    {
        EnteList.Add(new Enemy() { EnemyName = "Frodo" });
        EnteList.Add(new Troll() { TrollName = "Bilbo" });
        JsonSerializerSettings setting = new JsonSerializerSettings();
        setting.TypeNameHandling = TypeNameHandling.Objects;
        string json = JsonConvert.SerializeObject(EnteList, Formatting.Indented, setting);
        EnteList.Clear();

        List<Ente> result = JsonConvert.DeserializeObject<List<Ente>>(json, new JsonEnteConverter());

        Console.ReadLine();
    }
}

public class Ente
{
    public virtual string Type { get; set; }

    public Ente()
    {
        Console.WriteLine("\n Constructor of Ente executed");
    }
}

public class Enemy : Ente
{
    public override string Type { get => "Enemy"; }

    public string EnemyName { get; set; }

    public Enemy()
    {
        Console.WriteLine("\n Constructor of Enemy executed");
    }
}

public class Troll : Ente
{
    public override string Type { get => "Troll"; }

    public string TrollName { get; set; }

    public Troll()
    {
        Console.WriteLine("\n Constructor of Troll executed");
    }
}

public class JsonEnteConverter : Newtonsoft.Json.Converters.CustomCreationConverter<Ente>
{
    public override Ente Create(Type objectType)
    {
        throw new NotImplementedException();
    }

    public Ente Create(JObject jObject)
    {
        var type = jObject.Property("Type").ToString(); //get property Type from your json
        switch (type)
        {
            case "Enemy":
                return new Enemy();
            case "Troll":
                return new Troll();
        }
        throw new ApplicationException(String.Format("Type not found", type));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);
        var targetObject = Create(jObject); // Create your object based on JObject
        serializer.Populate(jObject.CreateReader(), targetObject);
        return targetObject;
    }
}
</code>```

The main thing is - you have to write your custom JsonConverter

Body:
I am learning the Newtonsoft JSON library in C#.

I have a class called "enemy" that descends from the "Ente" class.
I have a list of type "Ente".
In this list I add some instances of the "enemy" class and serialize the list, all correct.
Then, with the list empty, I read the JSON file from disk, deserialize it and assign the result to the list of type "Ente".
All correct but ... enemy objects are created using the constructor of the class "Ente", this is the problem, the objects should be created by calling the constructor of the class "Enemy", that is to say, objects "Enemy" must be created and not "Ente" objects.

**Edit 1:

I have other classes that also descend from "Ente" and the instances must be saved in the "EnteList" list.
For example, these are other classes that descend from "Ente":

Enemy: Ente

BallOfFire: Ente

Troll: Ente

etc...

In the example I simplified it to the maximum and thought that it was not necessary to give that information.
I think the newtonsoft library should do this automatically because I am specifying to save the object type that is in the list in the JSON file when serializing it.**

The question is: What do I need to do to make the "Enemy" object constructor run at the time of deserialization?

List:

public List< Ente > EnteList { get; set; } = new List< Ente >();

Code serialization and deserialization:

        EnteList.Add( new Enemy( ) );
        JsonSerializerSettings setting = new JsonSerializerSettings();
        setting.TypeNameHandling = TypeNameHandling.Objects;
        string json = JsonConvert.SerializeObject( EnteList, Formatting.Indented, setting );
        EnteList.Clear();
        EnteList = JsonConvert.DeserializeObject< List< Ente > >( json );

Class Ente and Enemy:

public class Ente
{
    public Ente()
    {
        Console.WriteLine( "\n Constructor of Ente executed" );
    }
}

public class Enemy : Ente
{
    public Enemy()
    {
        Console.WriteLine( "\n Constructor of Enemy executed" );
    }
}

Body:
EDITED

I've understood you.

try this:

class Program
{
    public static List<Ente> EnteList { get; set; } = new List<Ente>();

    static void Main(string[] args)
    {
        EnteList.Add(new Enemy() { EnemyName = "Frodo" });
        EnteList.Add(new Troll() { TrollName = "Bilbo" });
        JsonSerializerSettings setting = new JsonSerializerSettings();
        setting.TypeNameHandling = TypeNameHandling.Objects;
        string json = JsonConvert.SerializeObject(EnteList, Formatting.Indented, setting);
        EnteList.Clear();

        List<Ente> result = JsonConvert.DeserializeObject<List<Ente>>(json, new JsonEnteConverter());

        Console.ReadLine();
    }
}

public class Ente
{
    public virtual string Type { get; set; }

    public Ente()
    {
        Console.WriteLine("\n Constructor of Ente executed");
    }
}

public class Enemy : Ente
{
    public override string Type { get => "Enemy"; }

    public string EnemyName { get; set; }

    public Enemy()
    {
        Console.WriteLine("\n Constructor of Enemy executed");
    }
}

public class Troll : Ente
{
    public override string Type { get => "Troll"; }

    public string TrollName { get; set; }

    public Troll()
    {
        Console.WriteLine("\n Constructor of Troll executed");
    }
}

public class JsonEnteConverter : Newtonsoft.Json.Converters.CustomCreationConverter<Ente>
{
    public override Ente Create(Type objectType)
    {
        throw new NotImplementedException();
    }

    public Ente Create(JObject jObject)
    {
        var type = jObject.Property("Type").ToString(); //get property Type from your json
        switch (type)
        {
            case "Enemy":
                return new Enemy();
            case "Troll":
                return new Troll();
        }
        throw new ApplicationException(String.Format("Type not found", type));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);
        var targetObject = Create(jObject); // Create your object based on JObject
        serializer.Populate(jObject.CreateReader(), targetObject);
        return targetObject;
    }
}

The main thing is - you have to write your custom JsonConverter


来源: stackexchange

问:
Android Retrofit - Putting the response into an arraylist
Hey guys I have retrofit successfully getting data from a rest API and its printing into the log. However when I try and capture this response into an array list I'm getting an error stating : "Cannot infer arguments (unable to resolve constructor). This error shows in the array list brackets <>

```<code>// Executes the network request on a background thread
        try {
            Response response = getWeather(locationCode, apiKey).execute();
            if (cancelRequest) {
                return;
            }
            if (response.code() == 200) {

                //  Weather weather = response.body().getWeather();
                Log.d(TAG, "onResponse: " + response.body().toString());

                List<Weather> list = new ArrayList<>(((Weather)response.body()));
                //mWeather.postValue(response);
</code>```

GSON Response

```<code> {
"coord": {
    "lon": -5.93,
    "lat": 54.58
},
"weather": [
    {
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04d"
    }
],
"base": "stations",
"main": {
    "temp": 291.56,
    "feels_like": 286.36,
    "temp_min": 291.15,
    "temp_max": 292.15,
    "pressure": 1024,
    "humidity": 45
},
</code>```

If anyone could help me root cause this it would be greatly appreciated.

答:
To convert the response to a usable java object, you will have to use Gson or use Retrofit to do it automatically. Since you are getting the generic Response from the call, it means you will have to do it yourself. So first convert the json schema to a POJO then instead of

```<code>List<Weather> list = new ArrayList<>(((Weather)response.body()));
</code>```

use

```<code>ResponsePojo responsePojo = gson.fromJson(response.body().toString(), ResponsePojo.class);
</code>```

However, instead of doing it manually, you should set up Retrofit correctly so that it does the conversion for you. Then you will get back your object directly from the retrofit call -

```<code>Response<ResponsePojo> response = getWeather(locationCode, apiKey).execute();
ResponsePojo responsePojo = response.body()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hey guys I have retrofit successfully getting data from a rest API and its printing into the log. However when I try and capture this response into an array list I'm getting an error stating : "Cannot infer arguments (unable to resolve constructor). This error shows in the array list brackets <>

// Executes the network request on a background thread
        try {
            Response response = getWeather(locationCode, apiKey).execute();
            if (cancelRequest) {
                return;
            }
            if (response.code() == 200) {

                //  Weather weather = response.body().getWeather();
                Log.d(TAG, "onResponse: " + response.body().toString());

                List<Weather> list = new ArrayList<>(((Weather)response.body()));
                //mWeather.postValue(response);

GSON Response

 {
"coord": {
    "lon": -5.93,
    "lat": 54.58
},
"weather": [
    {
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04d"
    }
],
"base": "stations",
"main": {
    "temp": 291.56,
    "feels_like": 286.36,
    "temp_min": 291.15,
    "temp_max": 292.15,
    "pressure": 1024,
    "humidity": 45
},

If anyone could help me root cause this it would be greatly appreciated.

Body:
To convert the response to a usable java object, you will have to use Gson or use Retrofit to do it automatically. Since you are getting the generic Response from the call, it means you will have to do it yourself. So first convert the json schema to a POJO then instead of

List<Weather> list = new ArrayList<>(((Weather)response.body()));

use

ResponsePojo responsePojo = gson.fromJson(response.body().toString(), ResponsePojo.class);

However, instead of doing it manually, you should set up Retrofit correctly so that it does the conversion for you. Then you will get back your object directly from the retrofit call -

Response<ResponsePojo> response = getWeather(locationCode, apiKey).execute();
ResponsePojo responsePojo = response.body()


问:
android cardview showing border around card
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

```<code>         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>
</code>```

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.

答: try adding card_view:cardPreventCornerOverlap="false" to XML code

ContentLicense: CC BY-SA 3.0

Body:
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.


问:
How to efficiently find correspondences between two point sets without nested for loop in Pytorch?
I now have two point sets (tensor) A and B that shape like

A.size() >>(50, 3) , example: [ [0, 0, 0], [0, 1, 2], ..., [1, 1, 1]]

B.size() >>(10, 3)

where the first dimension stands for number of points and the second dim stands for coordinates (x,y,z)

To some extent, the question could also be simplified into " Finding common elements between two tensors ". Is there a quick way to do this without nested loop ?

答:
You can quickly compute all the 50x10 distances using:

d2 = ((A[:, None, :] - B[None, ...])**2).sum(dim=2)
```

<p>Once you have all the pair-wise distances, you can select "similar" ones if the distance does not exceed a threshold <code>thr</code>:</p>

<pre class="lang-py prettyprint-override"><code>(d2 < thr).nonzero()
</code>```

returns pairs of a-idx, b-idx of "similar" points.

If you want to match the points exactly, you can do instead:

((a[:, None, :] == b[None, ...]).all(dim=2)).nonzero()
```

Body:
You can quickly compute all the 50x10 distances using:

d2 = ((A[:, None, :] - B[None, ...])**2).sum(dim=2)

Once you have all the pair-wise distances, you can select "similar" ones if the distance does not exceed a threshold thr:

(d2 < thr).nonzero()

returns pairs of a-idx, b-idx of "similar" points.

If you want to match the points exactly, you can do instead:

((a[:, None, :] == b[None, ...]).all(dim=2)).nonzero()


问:
QuickFix C# or Python
We are about to implement a small automated securities trader. The trader will be build on top of the excellent quickfix FIX engine.

After due though, we narrowed our options down to implementing it in C# or in Python. Please specify the pros and cons of each language for this task, in term of:

Performance (The fact that Python uses a GIL troubles me in terms of thread concurrency)

Productivity

Scalability (We may need to scale this trader to a fully-sized platform)

EDIT
I've rephrased the question to make it less "C# vs. Python" (which I find irrelevant - both languages have their merits), but I'm simply trying to draw a comparison table before I make the decision.

答:
I like both languages and a think both would be a good choice. The GIL might really be the most important difference. But I'm not sure if it's a problem in your case. The GIL only affects code running in pure Python. I assume that your tool depends more on I/O than on raw number crunching. If your I/O libraries handle the GIL correctly, they can execute concurrent code without problems. And even for number crunching you still have numpy.

My choice would depend on your existing knowledge. If you have experienced C# developers at hand I would go for C#. If you start absolutly from scratch and it's really 50:50, then I would go for Python. It's easier to learn, free and in many cases more productive.

And just to mention it: You might also have a look at IronPython. ;-)

Title: QuickFix C# or Python


问:
Regex matching everything except what is between [ ... ]
I'm looking for two Regex which given a string like the following one:

I want [I]  cAptUre this [don't] number [want to] 9 and [be captured] this Word

(A)  return only the string inside each [] (brackets included). I've solved this with \[(.*?)\]

(B) return everything except what is inside [] (brackets excluded from the end result). So the opposite of the previous one.

Expected result:

(A) ["[I]", "[don't]", "[want to]", "[be captured]"]

(B) "I want CaptUre this number 9 and this Word"

How can I do it?

答:
Concerning (A), you can use a Match.Group and the pattern @"(\[[^]]+\])"  suggested by Gilles Quenot.
Concerning (B), you can use Regex.Replace to replace your text brackets:

```<code>var input = "I want[I]  cAptUre this[don't] number [want to] 9 and [be captured] this Word";
var pattern = @"(\[[^]]+\])";

var result = Regex.Replace(input, pattern, "");
Console.WriteLine(result);
</code>```

The output is

```<code>I want  cAptUre this number  9 and  this Word
</code>```

If you want to avoid duplicate white spaces in the output you can replace them too:

```<code>result = Regex.Replace(result, @"(\s\s+)", " ");
</code>```

Body:
Concerning (A), you can use a Match.Group and the pattern @"(\[[^]]+\])"  suggested by Gilles Quenot.
Concerning (B), you can use Regex.Replace to replace your text brackets:

var input = "I want[I]  cAptUre this[don't] number [want to] 9 and [be captured] this Word";
var pattern = @"(\[[^]]+\])";

var result = Regex.Replace(input, pattern, "");
Console.WriteLine(result);

The output is

I want  cAptUre this number  9 and  this Word

If you want to avoid duplicate white spaces in the output you can replace them too:

result = Regex.Replace(result, @"(\s\s+)", " ");


问:
How can I make a list of all the matching patterns to the Regex objects using Python 3?
I just started coding and I came across a problem: I have to find the number of streaks (receiving head or tail for a three or more times in a row) when the coin is flipped for a given times. This is what I got so far:

```<code>    import random, re
    lst=[]
    def coin_flip(b):
         for i in range(b):
              a=random.randint(0,1)
              if a==0:
                   lst.append("H")
              else:
                   lst.append("T")
    def check_for_streak(l):
         string="".join(l)
         Head=[]
         Tail=[]
         Head=re.compile(r'(H){3,}').findall(string)
         Tail=re.compile(r'(T){3,}').findall(string)
         return "The number of streaks is "+str(len(Head)+len(tail))
</code>```

So the problem here is that I expected the lists Head and Tail to contain the streak of H or T rather than the "H" and "T" in a streak itself ( Head=["HHHHH","HHHH",...] instead of Head=["H","H",...]) but it does not seem to be the case. Is there anyway to fix that?

答:
For your regex, use (H{3,}) instead of (H){3,}:

```<code>import random, re

def coin_flip(b):
    lst=[]
    for i in range(b):
        if random.randint(0,1):
            lst.append("H")
        else:
            lst.append("T")
    return lst

def check_for_streak(l):
     string="".join(l)

     head = re.compile(r'(H{3,})').findall(string)
     tail = re.compile(r'(T{3,})').findall(string)
     print(string)
     print(head)
     print(tail)
     return "The number of streaks is "+str(len(head)+len(tail))

lst = coin_flip(100)

print( check_for_streak(lst) )
</code>```

Prints (for example):

```<code>THTTTTHHHTHHHHHHHTHTTTTHHHTHTHTTHTHTTTTTTHHTTTTHTTHTHTTTHTHTTHHHTHTHHHTHHHTTTTHHTTHTHHHTTTHHTTTHHHHT
['HHH', 'HHHHHHH', 'HHH', 'HHH', 'HHH', 'HHH', 'HHH', 'HHHH']
['TTTT', 'TTTT', 'TTTTTT', 'TTTT', 'TTT', 'TTTT', 'TTT', 'TTT']
The number of streaks is 16
</code>```

Body:
I just started coding and I came across a problem: I have to find the number of streaks (receiving head or tail for a three or more times in a row) when the coin is flipped for a given times. This is what I got so far:

    import random, re
    lst=[]
    def coin_flip(b):
         for i in range(b):
              a=random.randint(0,1)
              if a==0:
                   lst.append("H")
              else:
                   lst.append("T")
    def check_for_streak(l):
         string="".join(l)
         Head=[]
         Tail=[]
         Head=re.compile(r'(H){3,}').findall(string)
         Tail=re.compile(r'(T){3,}').findall(string)
         return "The number of streaks is "+str(len(Head)+len(tail))

So the problem here is that I expected the lists Head and Tail to contain the streak of H or T rather than the "H" and "T" in a streak itself ( Head=["HHHHH","HHHH",...] instead of Head=["H","H",...]) but it does not seem to be the case. Is there anyway to fix that?

Body:
For your regex, use (H{3,}) instead of (H){3,}:

import random, re

def coin_flip(b):
    lst=[]
    for i in range(b):
        if random.randint(0,1):
            lst.append("H")
        else:
            lst.append("T")
    return lst

def check_for_streak(l):
     string="".join(l)

     head = re.compile(r'(H{3,})').findall(string)
     tail = re.compile(r'(T{3,})').findall(string)
     print(string)
     print(head)
     print(tail)
     return "The number of streaks is "+str(len(head)+len(tail))

lst = coin_flip(100)

print( check_for_streak(lst) )

Prints (for example):

THTTTTHHHTHHHHHHHTHTTTTHHHTHTHTTHTHTTTTTTHHTTTTHTTHTHTTTHTHTTHHHTHTHHHTHHHTTTTHHTTHTHHHTTTHHTTTHHHHT
['HHH', 'HHHHHHH', 'HHH', 'HHH', 'HHH', 'HHH', 'HHH', 'HHHH']
['TTTT', 'TTTT', 'TTTTTT', 'TTTT', 'TTT', 'TTTT', 'TTT', 'TTT']
The number of streaks is 16


问:
JSON with JavaScript and HTML
From this url: http://api.open-notify.org/astros.json, I am trying to get the name and craft of each person in space. I can't get it working with my URL, but it works with others... Any ideas?

My code:

```<code><html>
<body>
<table id="personDataTable">
    <tr>
        <th>Name</th>
        <th>Craft</th>
    </tr>

</table>

<style>
table {
  border: 2px solid #666;
    width: 100%;
}
th {
  background: #f8f8f8;
  font-weight: bold;
    padding: 2px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>

$.ajax({
    url: 'http://api.open-notify.org/astros.json',
    type: "get",
    dataType: "json",

    success: function(data) {
        drawTable(data);
    }
});

function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row);
    row.append($("<td>" + rowData.people.name + "</td>"));
    row.append($("<td>" + rowData.people.craft + "</td>"));
}
</script>

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

答:
If you notice the JSON structure it is like below

```<code>{"people": [{"craft": "ISS", "name": "Chris Cassidy"}, {"craft": "ISS", "name": "Anatoly Ivanishin"}, {"craft": "ISS", "name": "Ivan Vagner"}, {"craft": "Crew Dragon C206", "name": "Doug Hurley"}, {"craft": "Crew Dragon C206", "name": "Bob Behnken"}], "number": 5, "message": "success"}

</code>```

Why you are doing data.length in function drawTable?

It should be data.people.length in for loop and drawRow and drawTable function should be like below

```<code>function drawTable(data) {
    for (var i = 0; i < data.people.length; i++) {
        drawRow(data.people[i]);
    }
}

function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row);
    row.append($("<td>" + rowData.name + "</td>"));
    row.append($("<td>" + rowData.craft + "</td>"));
}

</code>```

As per one more ask, the number from the JSON can be fetched simply in your success function of ajax call

```<code>success: function(data) {
        var number = data.number;   //Like this you can fetch
        drawTable(data);
    }

</code>```

Title: JSON with JavaScript and HTML

Body:
From this url: http://api.open-notify.org/astros.json, I am trying to get the name and craft of each person in space. I can't get it working with my URL, but it works with others... Any ideas?

My code:

        Name
        Craft

Body:
If you notice the JSON structure it is like below

{"people": [{"craft": "ISS", "name": "Chris Cassidy"}, {"craft": "ISS", "name": "Anatoly Ivanishin"}, {"craft": "ISS", "name": "Ivan Vagner"}, {"craft": "Crew Dragon C206", "name": "Doug Hurley"}, {"craft": "Crew Dragon C206", "name": "Bob Behnken"}], "number": 5, "message": "success"}

Why you are doing data.length in function drawTable?

It should be data.people.length in for loop and drawRow and drawTable function should be like below

function drawTable(data) {
    for (var i = 0; i < data.people.length; i++) {
        drawRow(data.people[i]);
    }
}

function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row);
    row.append($("<td>" + rowData.name + "</td>"));
    row.append($("<td>" + rowData.craft + "</td>"));
}

As per one more ask, the number from the JSON can be fetched simply in your success function of ajax call

success: function(data) {
        var number = data.number;   //Like this you can fetch
        drawTable(data);
    }


问:
unique "key" / table should have a unique `key` prop, or set `rowKey
Question: How to pass / create and pass unique key to Radio Button , also i have a Table component that takes data(arra) and it also says that [antd: Table] Each record in dataSource of table should have a unique key prop, or set rowKey . Thank you in advance.

```<code>    const userRoles = [
    {
        key: "ROLE_ADMIN",
        name: "Admin"
    },
    {
        key: "ROLE_USER",
        name: "User",
    }
];

class RoleUpdate extends PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            userRole: props.role,
        }
    }

    handleChange = (event) => {
        this.setState({
            userRole: {
                role: event.target.value
            }
        });
        this.props.onRoleChange(event.target.value);
    };

    render() {
        return (
            <Radio.Group value={this.state.userRole.role} onChange={this.handleChange}>
                {userRoles.map(role => {
                    return <Radio.Button value={role.key}>{role.name}</Radio.Button>
                })}
            </Radio.Group>

        )
    };

}

export default RoleUpdate;

<Table size={"middle"}
      columns={columns}
      dataSource={this.state.results}
                   />
</code>```

答:
You must pass a key attribute to elements returned from within the loop or map. Assuming userRoles has key property which is unique it can be used as a key like key={role.key} on Radio.Button

```<code>render() {
    return (
        <Radio.Group value={this.state.userRole.role} onChange={this.handleChange}>
            {userRoles.map(role => {
                return <Radio.Button key={role.key} value={role.key}>{role.name}</Radio.Button>
            })}
        </Radio.Group>

    )
};
</code>```

and for the table you need to specify which key from within the data needs to be taken as a key by specifying the rowKey attribute

```<code><Table size={"middle"}
  columns={columns}
   rowKey={"id"} // specify any key which has unique value within this.state.resukts
  dataSource={this.state.results}
/>
</code>```

Body:
Question: How to pass / create and pass unique key to Radio Button , also i have a Table component that takes data(arra) and it also says that [antd: Table] Each record in dataSource of table should have a unique key prop, or set rowKey . Thank you in advance.

    const userRoles = [
    {
        key: "ROLE_ADMIN",
        name: "Admin"
    },
    {
        key: "ROLE_USER",
        name: "User",
    }
];

class RoleUpdate extends PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            userRole: props.role,
        }
    }

    handleChange = (event) => {
        this.setState({
            userRole: {
                role: event.target.value
            }
        });
        this.props.onRoleChange(event.target.value);
    };

    render() {
        return (
            <Radio.Group value={this.state.userRole.role} onChange={this.handleChange}>
                {userRoles.map(role => {
                    return <Radio.Button value={role.key}>{role.name}</Radio.Button>
                })}
            </Radio.Group>

        )
    };

}

export default RoleUpdate;

Body:
You must pass a key attribute to elements returned from within the loop or map. Assuming userRoles has key property which is unique it can be used as a key like key={role.key} on Radio.Button

render() {
    return (
        <Radio.Group value={this.state.userRole.role} onChange={this.handleChange}>
            {userRoles.map(role => {
                return <Radio.Button key={role.key} value={role.key}>{role.name}</Radio.Button>
            })}
        </Radio.Group>

    )
};

and for the table you need to specify which key from within the data needs to be taken as a key by specifying the rowKey attribute

<Table size={"middle"}
  columns={columns}
   rowKey={"id"} // specify any key which has unique value within this.state.resukts
  dataSource={this.state.results}
/>


问:
How can I scrape "view" count of a comment with BeautifulSoup?
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

```<code>headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})
</code>```

The count of the complaints:

I try to get the number "479" with this code:

```<code>site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})
</code>```

It returns:

```<code>print(time[0])
<span class="count">-</span>

print(time[0].text)
-
</code>```

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance

答:
Than count most probably is rendered by javascript to DOM and is not present in original html. Check html source  instead of inspector. I've checked the source of page 3 (view-source:https://www.sikayetvar.com/sikayetler?brand=bosch&page=3) and count is really just a - while the page shows 377.
This answer might help you how to pre-render.

Body:
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})

The count of the complaints:

I try to get the number "479" with this code:

site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})

It returns:

print(time[0])
-

print(time[0].text)
-

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance


问:
Bloc Library state
In my simple app, I am using Bloc Library.
To load data from firestore i am using stream. Problem is  when I navigate to another page or return back my data doesnt display, need to use hot reload. Its look like nn HomeScreen BlocProvider.of<DataBloc>(context)..add(LoadData()); this event works at once.  How to solve it?

Main widget.

```<code>Widget build(BuildContext context) {
return MultiBlocProvider(
  providers: [
    BlocProvider(
      create: (context) => DataBloc(),
    ),
  ],
  child: MaterialApp(
    home: HomeScreenTest(),
  ),
 );
}
</code>```

HomeScreen.

```<code>class HomeScreenTest extends StatelessWidget {
 @override
  Widget build(BuildContext context) {
    BlocProvider.of<DataBloc>(context)..add(LoadData());
    return Scaffold(
      backgroundColor: Colors.grey.shade600,
      body: Column(
            children: <Widget>[
             BlocBuilder<DataBloc, DataState>(
                  builder: (context, state) {
                    if (state is DataLoadedState) {
                      return dataColumn(context, state.dataTest);
                    } else {
                      return Container();
                    }
                  },
                ),
              )
            ],
          );
        }
      }
</code>```

Bloc.

```<code> class DataBloc extends Bloc<DataEvent, DataState> {

  StreamSubscription streamSubscription;

  @override
  DataState get initialState => DataState();

  @override
  Stream<DataState> mapEventToState(DataEvent event) async* {
    if (event is LoadData) {
      streamSubscription = Data().dataTest.listen(
          (data) => add(DataLoaded(dataTest: data)));
    } else if (event is DataLoaded) {
      yield DataLoadedState(
          dataTest: event.dataTest);
    }
  }
}
</code>```

Event.

```<code>abstract class DataEvent extends Equatable {
 const DataEvent();
}

class LoadData extends DataEvent {
  List<DataTest> dataTest;
  LoadData({this.dataTest});
  @override
  List<Object> get props => [dataTest];
}

class DataLoaded extends DataEvent {
  List<DataTest> dataTest;
  DataLoaded({this.dataTest});
  @override
  List<Object> get props => [dataTest];
}
</code>```

State.

```<code>class DataState extends Equatable {
  @override
  List<Object> get props => [];
}

class DataLoadedState extends DataState {
  List<DataTest> dataTest;
  DataLoadedState({this.dataTest});
  @override
  List<Object> get props => [dataTest];
}
</code>```

答:
update your code like this:</p>

```<code>class HomeScreenTest extends StatelessWidget {
  List<DataTest> dataTest = [];
 @override
 void initState(){
   BlocProvider.of<DataBloc>(context)..add(LoadData());
 }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.grey.shade600,
      body: Column(
            children: <Widget>[
             BlocBuilder<DataBloc, DataState>(
                  builder: (context, state) {
                    if (state is DataLoadedState) {
                      dataTest =state.dataTest;
                    }
                    return dataTest.isEmpty
                      ? Container()
                      : dataColumn(context, state.dataTest);
                  },
                ),
              )
            ],
          );
        }
      }
</code>```

Title: Bloc Library state

Body:
In my simple app, I am using Bloc Library.
To load data from firestore i am using stream. Problem is  when I navigate to another page or return back my data doesnt display, need to use hot reload. Its look like nn HomeScreen BlocProvider.of<DataBloc>(context)..add(LoadData()); this event works at once.  How to solve it?

Main widget.

Widget build(BuildContext context) {
return MultiBlocProvider(
  providers: [
    BlocProvider(
      create: (context) => DataBloc(),
    ),
  ],
  child: MaterialApp(
    home: HomeScreenTest(),
  ),
 );
}

HomeScreen.

class HomeScreenTest extends StatelessWidget {
 @override
  Widget build(BuildContext context) {
    BlocProvider.of<DataBloc>(context)..add(LoadData());
    return Scaffold(
      backgroundColor: Colors.grey.shade600,
      body: Column(
            children: <Widget>[
             BlocBuilder<DataBloc, DataState>(
                  builder: (context, state) {
                    if (state is DataLoadedState) {
                      return dataColumn(context, state.dataTest);
                    } else {
                      return Container();
                    }
                  },
                ),
              )
            ],
          );
        }
      }

Bloc.

 class DataBloc extends Bloc<DataEvent, DataState> {

  StreamSubscription streamSubscription;

  @override
  DataState get initialState => DataState();

  @override
  Stream<DataState> mapEventToState(DataEvent event) async* {
    if (event is LoadData) {
      streamSubscription = Data().dataTest.listen(
          (data) => add(DataLoaded(dataTest: data)));
    } else if (event is DataLoaded) {
      yield DataLoadedState(
          dataTest: event.dataTest);
    }
  }
}

Event.

abstract class DataEvent extends Equatable {
 const DataEvent();
}

class LoadData extends DataEvent {
  List<DataTest> dataTest;
  LoadData({this.dataTest});
  @override
  List<Object> get props => [dataTest];
}

class DataLoaded extends DataEvent {
  List<DataTest> dataTest;
  DataLoaded({this.dataTest});
  @override
  List<Object> get props => [dataTest];
}

State.

class DataState extends Equatable {
  @override
  List<Object> get props => [];
}

class DataLoadedState extends DataState {
  List<DataTest> dataTest;
  DataLoadedState({this.dataTest});
  @override
  List<Object> get props => [dataTest];
}

Body:
update your code like this:

class HomeScreenTest extends StatelessWidget {
  List<DataTest> dataTest = [];
 @override
 void initState(){
   BlocProvider.of<DataBloc>(context)..add(LoadData());
 }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.grey.shade600,
      body: Column(
            children: <Widget>[
             BlocBuilder<DataBloc, DataState>(
                  builder: (context, state) {
                    if (state is DataLoadedState) {
                      dataTest =state.dataTest;
                    }
                    return dataTest.isEmpty
                      ? Container()
                      : dataColumn(context, state.dataTest);
                  },
                ),
              )
            ],
          );
        }
      }


问:
Is the namespace created when free variables are used?
```<code>x = 2
def my_func():
    print(x)
    print(dir())

my_func()
</code>```

The output by the statement print(dir()) is an empty list []. Was the local namespace created but didn't contain any name or it wasn't created at all?

Body:
x = 2
def my_func():
    print(x)
    print(dir())

my_func()

The output by the statement print(dir()) is an empty list []. Was the local namespace created but didn't contain any name or it wasn't created at all?

Body:
If you pass any args inside dir(), like:

x = 2
def my_func():
    print(x)
    print(dir(1))

my_func()

Run this file and you might get the answer like this:

2
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']


问:
Looping through list of columns
I have a large data frame, one column shows the province where the respondent is coming from. I would like to see differences of values between respondents from provinces in some columns, based on column name (e.g. for the columns Hope, Responsibility, Efficacy).

```<code>Province  Hope  Responsibility  Efficacy Age
   A       4         3            2      24
   A       2         1            4      23
   C       5         3            5      20
   B       3         2            3      29
   A       1         1            4      23
   B       3         3            2      25
</code>```

So far I looped through differences between all combinations of provinces for each column:

```<code>list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')

for (i in list1){
  for (j in list2){
    t <- t.test(dt[Province == i, Hope], dt[Province == j, Hope])
    if (t$p.value <= 0.05){
      print(paste("Results:",i,"and",j))
      print(t)
    }}}
</code>```

How can I create a loop that loops through a list of columns based on the column name, e.g. something like this (which does not work).

THIS PART IS EDITED

```<code>list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')
list3 = list('Hope', 'Responsibility', 'Efficacy')

for (c in list3){
  for (i in list1){
    for (j in list2){
      t <- t.test(dt[Province == i, c], dt[Province == j, c])
      if (t$p.value <= 0.05){
        print(paste("Results:",i,"and",j))
        print(t)
      }}}}
</code>```

答:
I don't know what you want to achieve, I'm sorry. However, there are two errors in your code and logic, as far as I can see.

First, how you select rows and columns

dt[Province == i, Hope]
```

<p>This can only work if you have defined <code>Province</code> somewhere. However, based on your logic, it seems that this does not make sense since you want to select rows of <code>dt</code>. The same is true for <code>Hope</code>. If you want to select column <code>Hope</code>, you need to pass in a character. This leads to the following code.</p>

<pre class="lang-r prettyprint-override"><code>dt[dt$Province == i, "Hope"]
</code>```

That said, I think what you really wanted is

dt[dt$Province == i, c]
```

<p>because you have defined list <code>list3</code> and loop over it, but you don't use it.</p>

<p>Second, your call to <code>t.test</code>. Based on the observations above, we have</p>

<pre class="lang-r prettyprint-override"><code>t.test(dt[dt$Province == i, c], dt[dt$Province == j, c])
</code>```

This can not work, because this produces vectors of different lengths. For example, in the first loop of the loops you would have

```<code>dt[dt$Province == "A", "Hope"] = (4, 2, 1)
dt[dt$Province == "B", "Hope"] = (3, 3)
</code>```

And this can not work because t.test assumes two vectors of equal length.

I hope this helps. Also, check out @Ronak Shah answer.

Title: Looping through list of columns

Body:
I have a large data frame, one column shows the province where the respondent is coming from. I would like to see differences of values between respondents from provinces in some columns, based on column name (e.g. for the columns Hope, Responsibility, Efficacy).

Province  Hope  Responsibility  Efficacy Age
   A       4         3            2      24
   A       2         1            4      23
   C       5         3            5      20
   B       3         2            3      29
   A       1         1            4      23
   B       3         3            2      25

So far I looped through differences between all combinations of provinces for each column:

list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')

for (i in list1){
  for (j in list2){
    t <- t.test(dt[Province == i, Hope], dt[Province == j, Hope])
    if (t$p.value <= 0.05){
      print(paste("Results:",i,"and",j))
      print(t)
    }}}

How can I create a loop that loops through a list of columns based on the column name, e.g. something like this (which does not work).

THIS PART IS EDITED

list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')
list3 = list('Hope', 'Responsibility', 'Efficacy')

for (c in list3){
  for (i in list1){
    for (j in list2){
      t <- t.test(dt[Province == i, c], dt[Province == j, c])
      if (t$p.value <= 0.05){
        print(paste("Results:",i,"and",j))
        print(t)
      }}}}

Body:
I don't know what you want to achieve, I'm sorry. However, there are two errors in your code and logic, as far as I can see.

First, how you select rows and columns

dt[Province == i, Hope]

This can only work if you have defined Province somewhere. However, based on your logic, it seems that this does not make sense since you want to select rows of dt. The same is true for Hope. If you want to select column Hope, you need to pass in a character. This leads to the following code.

dt[dt$Province == i, "Hope"]

That said, I think what you really wanted is

dt[dt$Province == i, c]

because you have defined list list3 and loop over it, but you don't use it.

Second, your call to t.test. Based on the observations above, we have

t.test(dt[dt$Province == i, c], dt[dt$Province == j, c])

This can not work, because this produces vectors of different lengths. For example, in the first loop of the loops you would have

dt[dt$Province == "A", "Hope"] = (4, 2, 1)
dt[dt$Province == "B", "Hope"] = (3, 3)

And this can not work because t.test assumes two vectors of equal length.

I hope this helps. Also, check out @Ronak Shah answer.


问:
How to access the real 100vh on iOS in CSS
This is a self Q&A

If you've ever tried to use 100vh in CSS on iOS you will have found that it isn't actually 100vh when the browser chrome is expanded. It's a well documented bug that Apple decided was actually a feature! This is a good read to explain the bug.

So what is the best way to get around this "feature"? Ideally the answer requires no JavaScript (but that seems unlikely), should be clean, not require a bunch of inline styles, and ideally can be opted into in CSS (sometimes you might want the default 100vh).

答:
CSS Grid is the solution.</p>

```<code>.grid-container {
  height: 100vh;
  grid-template-columns: 1fr;
  grid-template-rows: 30px 1fr 30px
}
</code>```

Body:
CSS Grid is the solution.

.grid-container {
  height: 100vh;
  grid-template-columns: 1fr;
  grid-template-rows: 30px 1fr 30px
}


问:
How to Copy the fill pattern of a cell to a shape?
I have been writing a code that is copying the color of the cell and pasting it to the relevant shape. I am able to copy the color. However, it seems more complicated to copy the fill pattern of the cell.
The problem i have faced is that the pattern parameter of a cell is, for example, "xlLightHorizontal" and the same pattern for a shape is "msoPatternNarrowHorizontal". Both draw the same fill pattern but have different names.

How i copy the color and fill pattern of the cell:

```<code>modelText(3, 1) = Sheets("Orders").Cells(row, j + 1).Interior.Color
modelText(3, 2) = Sheets("Orders").Cells(row, j + 1).Interior.Pattern
modelText(3, 3) = Sheets("Orders").Cells(row, j + 1).Interior.PatternColor

</code>```

How i assign the color and the fill pattern to the shape:

```<code> With Selection.ShapeRange.Fill
        .ForeColor.RGB = modelText(3, 1)
        .BackColor.RGB = modelText(3, 3)
        .Patterned (msoPatternLightHorizontal)
 End With
</code>```

Note that:

Cells(row, j + 1).Interior.Pattern  returns xlLightHorizontal

Where

ShapeRange.Fill.Patterned  does not accept xlLightHorizontal as an input parameter

Is there anyway that you know to copy the fill pattern of a cell to a shape?

答:
I tried to find a solution. It looks like that the two set of enumeration are not matching. I hope you do have a very limited set of pattern you would like to use. In this case I would make a table of pairs (numbers to the same or at least similar pattern) of the enums to make the conversion. I have not better idea. Sorry.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.core.msopatterntype?view=office-pia and
https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.constants?view=excel-pia

Body:
I have been writing a code that is copying the color of the cell and pasting it to the relevant shape. I am able to copy the color. However, it seems more complicated to copy the fill pattern of the cell.
The problem i have faced is that the pattern parameter of a cell is, for example, "xlLightHorizontal" and the same pattern for a shape is "msoPatternNarrowHorizontal". Both draw the same fill pattern but have different names.

How i copy the color and fill pattern of the cell:

modelText(3, 1) = Sheets("Orders").Cells(row, j + 1).Interior.Color
modelText(3, 2) = Sheets("Orders").Cells(row, j + 1).Interior.Pattern
modelText(3, 3) = Sheets("Orders").Cells(row, j + 1).Interior.PatternColor

How i assign the color and the fill pattern to the shape:

 With Selection.ShapeRange.Fill
        .ForeColor.RGB = modelText(3, 1)
        .BackColor.RGB = modelText(3, 3)
        .Patterned (msoPatternLightHorizontal)
 End With

Note that:

Cells(row, j + 1).Interior.Pattern  returns xlLightHorizontal

Where

ShapeRange.Fill.Patterned  does not accept xlLightHorizontal as an input parameter

Is there anyway that you know to copy the fill pattern of a cell to a shape?


问:
Flutter Android license status unknown
```<code>$ flutter doctor
</code>```

Doctor summary (to see all details, run flutter doctor -v):

[✓] Flutter (Channel stable, v1.2.1, on Linux, locale en_US.UTF-8)

[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3) ✗ Android license status unknown.

[✓] Android Studio (version 3.3)

[!] IntelliJ IDEA Ultimate Edition (version 2018.3)

✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.

[!] VS Code (version 1.31.1)

✗ Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

答:
1. I run $ flutter doctor --android-licenses - It runs SDK manager to accept licenses.

After that, I got some classException that is due to JDK.

2. Downloaded and Installed Java 8, set path to C:\Program Files \Java\jdk1.8.0_111\bin.

Problem solved...
I got the command from here - 7 Flutter Commands

Title: Flutter Android license status unknown

Body:
$ flutter doctor

Doctor summary (to see all details, run flutter doctor -v):

[✓] Flutter (Channel stable, v1.2.1, on Linux, locale en_US.UTF-8)

[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3) ✗ Android license status unknown.

[✓] Android Studio (version 3.3)

[!] IntelliJ IDEA Ultimate Edition (version 2018.3)

✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.

[!] VS Code (version 1.31.1)

✗ Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available


问:
Progress Dialog not Shown
I have this code snippet, the problem with this code is that when I click the 'done' button
the ProgressDialog is not showing.Please help</p>

```<code>public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send);

        done = (Button)findViewById(R.id.sendbut);

        done.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                 showProgressDialog();
                 query_str = getString();
                         startUploading();
            }
        });
 }

 public void showProgressDialog(){
     GlobalClass.printLine("Showing progress dialog");
     progressDialog = new ProgressDialog(Send.this);
     progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     progressDialog.setMessage("Sending...");
     progressDialog.setCancelable(false);
     progressDialog.show();
     // Start lengthy operation in a background thread
     new Thread(new Runnable() {
         public void run() {
                 // Update the progress bar
                 mHandler.post(new Runnable() {
                     public void run() {
                         progressDialog.setProgress(mProgressStatus);
                         Toast.makeText(getApplicationContext(), "Herererererer",Toast.LENGTH_LONG).show();
                         if(mProgressStatus == 100){
                             Toast.makeText(getApplicationContext(), "Done",Toast.LENGTH_LONG).show();
                             progressDialog.dismiss();
                         }
                     }
                 });
             }
     }).start();
 }
</code>```

答:
You should use AsyncTask which is also known as Painless threading.

Now, to show progressbar while processing in background, here is an example:

```<code>    // ASync Task Begin to perform
 private class performBackgroundTask extends Async Task < Void, Void, Void >
 {
    private ProgressDialog Dialog = new ProgressDialog( this);

    protected void onPreExecute()
    {
           // here you have place code which you want to show in UI thread like progressbar or dialog or any layout .
           Dialog.setMessage(" please wait...");
           Dialog.show();
    }

    protected Void doInBackground(Void... params)
    {
       // write here the code to download  or to perform any background task.
   return null;
  }

  protected void onPostExecute(Void unused) {
     Dialog.dismiss();  // here we have to dismiss the progress dialog
   // To display fetched data in textview, imageview, or any

  }

 }
</code>```

Title: Progress Dialog not Shown

Body:
I have this code snippet, the problem with this code is that when I click the 'done' button
the ProgressDialog is not showing.Please help

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send);

        done = (Button)findViewById(R.id.sendbut);

        done.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                 showProgressDialog();
                 query_str = getString();
                         startUploading();
            }
        });
 }

 public void showProgressDialog(){
     GlobalClass.printLine("Showing progress dialog");
     progressDialog = new ProgressDialog(Send.this);
     progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     progressDialog.setMessage("Sending...");
     progressDialog.setCancelable(false);
     progressDialog.show();
     // Start lengthy operation in a background thread
     new Thread(new Runnable() {
         public void run() {
                 // Update the progress bar
                 mHandler.post(new Runnable() {
                     public void run() {
                         progressDialog.setProgress(mProgressStatus);
                         Toast.makeText(getApplicationContext(), "Herererererer",Toast.LENGTH_LONG).show();
                         if(mProgressStatus == 100){
                             Toast.makeText(getApplicationContext(), "Done",Toast.LENGTH_LONG).show();
                             progressDialog.dismiss();
                         }
                     }
                 });
             }
     }).start();
 }

Body:
You should use AsyncTask which is also known as Painless threading.

Now, to show progressbar while processing in background, here is an example:

    // ASync Task Begin to perform
 private class performBackgroundTask extends Async Task < Void, Void, Void >
 {
    private ProgressDialog Dialog = new ProgressDialog( this);

    protected void onPreExecute()
    {
           // here you have place code which you want to show in UI thread like progressbar or dialog or any layout .
           Dialog.setMessage(" please wait...");
           Dialog.show();
    }

    protected Void doInBackground(Void... params)
    {
       // write here the code to download  or to perform any background task.
   return null;
  }

  protected void onPostExecute(Void unused) {
     Dialog.dismiss();  // here we have to dismiss the progress dialog
   // To display fetched data in textview, imageview, or any

  }

 }


问:
Loading nested array into spark dataframe column
I have a nested array which looks like

```<code>a = [[1,2],[2,3]]
</code>```

i have a streaming dataframe which looks like

```<code>|system    |level|

+----------+-----+

|Test1     |1    |

|Test2     |3    |
</code>```

I want to include the array into third column as a nested array.

```<code>|system    |level| Data |

+----------+-----+------+

|Test1     |1    |[[1,2],[2,3]]
</code>```

I tried with column and array function. But i am not sure how to use nested array.

Any help would be appreciated.

答:
In scala API, we can use "typedLit" function to add the Array or map values in the column.

// Ref : https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

Here is the sample code to add an Array as a column value.

```<code>import org.apache.spark.sql.functions.typedLit

val a = Seq((1,2),(2,3))
val df1 = Seq(("Test1", 1), ("Test3", 3)).toDF("a", "b")

df1.withColumn("new_col", typedLit(a)).show()
</code>```

// Output

```<code>+-----+---+----------------+
|    a|  b|         new_col|
+-----+---+----------------+
|Test1|  1|[[1, 2], [2, 3]]|
|Test3|  3|[[1, 2], [2, 3]]|
+-----+---+----------------+
</code>```

I hope this helps.

Body:
I have a nested array which looks like

a = [[1,2],[2,3]]

i have a streaming dataframe which looks like

|system    |level|

+----------+-----+

|Test1     |1    |

|Test2     |3    |

I want to include the array into third column as a nested array.

|system    |level| Data |

+----------+-----+------+

|Test1     |1    |[[1,2],[2,3]]

I tried with column and array function. But i am not sure how to use nested array.

Any help would be appreciated.

Body:
In scala API, we can use "typedLit" function to add the Array or map values in the column.

// Ref : https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

Here is the sample code to add an Array as a column value.

import org.apache.spark.sql.functions.typedLit

val a = Seq((1,2),(2,3))
val df1 = Seq(("Test1", 1), ("Test3", 3)).toDF("a", "b")

df1.withColumn("new_col", typedLit(a)).show()

// Output

+-----+---+----------------+
|    a|  b|         new_col|
+-----+---+----------------+
|Test1|  1|[[1, 2], [2, 3]]|
|Test3|  3|[[1, 2], [2, 3]]|
+-----+---+----------------+

I hope this helps.


问:
R Get Sum of Data frame Column By Another Column Variable
So I need to take the sum of a dataframe with two particulars columns of interest

Col1 : Numeric Data

Col2 : Years

So I need to take the sum of Numeric Data by the years mentioned in the Years Column.
Then I need to plot the aggregates on y-axis and the years on x-axis.

I tried the following:

agg <- tapply(Col1, Col2, FUN=sum)

but I'm unable to get the year names displayed in the x-axis in the plot.

In one of the solutions I found, the following formula was used:

aggregate(Col1 ~ Col2,Dataframe, FUN=sum)

Can someone explain how this formula works?
I understand the use of ~ in plotting, but not in this formula.

答:
Here is a dplyr solution:

```<code>library(ggplot2);library(dplyr)
</code>```

Data

```<code>data = tibble(year = c(sample(c(2000:2020), size = 20)), numericData = runif(20, 0, 100))
</code>```

Aggregate and Make Plot

```<code>data %>%
  group_by(year) %>%
  summarise(aggregated = sum(numericData)) %>%
  ggplot(aes(year, aggregated)) +
  geom_line()
</code>```

PS: It is always helpful to provide some sample code or data.

Body:
Here is a dplyr solution:

library(ggplot2);library(dplyr)

Data

data = tibble(year = c(sample(c(2000:2020), size = 20)), numericData = runif(20, 0, 100))

Aggregate and Make Plot

data %>%
  group_by(year) %>%
  summarise(aggregated = sum(numericData)) %>%
  ggplot(aes(year, aggregated)) +
  geom_line()

PS: It is always helpful to provide some sample code or data.


问:
symlink everyday automatically change to a new source
I have a similar request as per this superuser question

Mine is like this.

I have a folder called journals

Inside I will create a new note everyday of this format.

YYYY-MM-DD dddd.md a markdown file.

Basically, the filenames are

..../journals/2020-05-29 Friday.md

..../journals/2020-05-30 Saturday.md

and so on.

And they are all in the same folder.

What I would like is a symlink in the same folder called today.md

Which everyday will point to the right file.

If the file does not exist, simply create an empty markdown file of the same format before assigning the symlink.

How do I do this? Bash script? I am using a macOS

答:
Yes, you can use a short shell script for this like the following:

#!/usr/bin/env bash

date=`date +"%Y-%m-%d %A"`
folder="$HOME/journals" # replace with full path to desired folder
file="$folder/$date.md"

if [ ! -f "$file" ]; then
    touch "$file"
    echo "Created file: $file"
fi

ln -sf "$file" "$folder/today.md"
echo "Created link to file: $file"
```

Copy the script into a new file in your home directory, or wherever you like, and save it with a .sh extension like makeSym.sh. Then open the Terminal app, navigate to where you saved the file, and run chmod +x makeSym.sh so it is executable. Now you can run the script by typing ./makeSym.sh.

To have the script launch automatically when you log in, and then regularly every hour (or however often you want), follow this short tutorial on how to use launchd.

Body:
Yes, you can use a short shell script for this like the following:

#!/usr/bin/env bash

date=`date +"%Y-%m-%d %A"`
folder="$HOME/journals" # replace with full path to desired folder
file="$folder/$date.md"

if [ ! -f "$file" ]; then
    touch "$file"
    echo "Created file: $file"
fi

ln -sf "$file" "$folder/today.md"
echo "Created link to file: $file"

Copy the script into a new file in your home directory, or wherever you like, and save it with a .sh extension like makeSym.sh. Then open the Terminal app, navigate to where you saved the file, and run chmod +x makeSym.sh so it is executable. Now you can run the script by typing ./makeSym.sh.

To have the script launch automatically when you log in, and then regularly every hour (or however often you want), follow this short tutorial on how to use launchd.


问:
Use of conditional function, condition in definition
I have a seemingly trivial problem. I write a definition and I don't know how to introduce conditional functions.

I have a definition that works:

```<code>def function_1 (kot):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")
</code>```

It wokrs good

```<code>function_1 (False)
</code>```

No:

or

```<code>function_1 (True)
</code>```

Yes:

But I would like to have such a thing in my definition

```<code>def function_1 (kot = True):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")
</code>```

and it doesn't work any more.

答:
Because you need to call the function as you did in the above example

```<code>def function_1 (kot=True):
 if kot == True:
     print ("Yes:")
 else:
     print ("NO:")

function_1()
</code>```

output:

```<code>Yes:
</code>```

Body:
I have a seemingly trivial problem. I write a definition and I don't know how to introduce conditional functions.

I have a definition that works:

def function_1 (kot):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")

It wokrs good

function_1 (False)

No:

or

function_1 (True)

Yes:

But I would like to have such a thing in my definition

def function_1 (kot = True):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")

and it doesn't work any more.

Body:
Because you need to call the function as you did in the above example

def function_1 (kot=True):
 if kot == True:
     print ("Yes:")
 else:
     print ("NO:")

function_1()

output:

Yes:


问:
Flutter - Determine time to go to sleep with hour i want to wake up
I'm new to Dart and Flutter and i am looking for some help. I'm trying to do this :

-The user pick a hour and minute in a Cupertino date picker (it's hour he want to wake up in the morning)

-I would like to determine the exact time he need to go to sleep to have 7 hour of good sleeping.

(This function is working but i can't figurate how to add minutes to hour and then determine the right calculation)

```<code>void Bed(int Heure, int Minute) {

    if (Heure - Cycle <= 0) {
      result = Heure - Cycle + 24;

    } else {

      result = Heure - Cycle;
    }
  }
</code>```

Thank you for your help !

答:
I would just only calculate in minutes. So take your hours*60 , do you calculation with only minutes, and then convert back to hours in the end.</p>

```<code>  double total = 140; //Your total time converted to minutes

  double mins = total % 60; //your minutes

  double hrs = (total - mins) / 60; // your hours

  print(mins);
  print(hrs);
</code>```

Body:
I'm new to Dart and Flutter and i am looking for some help. I'm trying to do this :

-The user pick a hour and minute in a Cupertino date picker (it's hour he want to wake up in the morning)

-I would like to determine the exact time he need to go to sleep to have 7 hour of good sleeping.

(This function is working but i can't figurate how to add minutes to hour and then determine the right calculation)

void Bed(int Heure, int Minute) {

    if (Heure - Cycle <= 0) {
      result = Heure - Cycle + 24;

    } else {

      result = Heure - Cycle;
    }
  }

Thank you for your help !

Body:
I would just only calculate in minutes. So take your hours*60 , do you calculation with only minutes, and then convert back to hours in the end.

  double total = 140; //Your total time converted to minutes

  double mins = total % 60; //your minutes

  double hrs = (total - mins) / 60; // your hours

  print(mins);
  print(hrs);


问:
What is a good way to apply multiple sanitizers in cmake with gcc
GCC has many sanitizers (e.g., leak, address, thread). But many of them require instumentation of the code and cannot be used together with others. So if in practice I want to apply all the sanitizers to make sure my code works well, what is a recommended procedure to use all these sanitizers?

I manage my project using CMake

答: Some sanitizers can be combined together in the same run: Asan+UBsan+Lsan (and optionally Isan, if your program does not have intentional unsigned overflows). All other sanitizers (e.g. Tsan or Msan) require separate QA runs (which implies rebuilding SW for every run). Also you'll most likely want a dedicated CI run for Valgrind (it can detect some errors which Asan can't and it can not be applied to sanitized code due to implementation details).</p>


问:
Read data in activity of recyclerview adapter
I have a recyclerview with a card and spinners in it, the values selected in the spinner I need to send it to the next activity to calculate estimated price. I have a button in the activity which is not of the recyclerview, that takes me to next activity where I need the values. So when I click this button I need it to collect the data and send it to next activity, how can I achieve that.

I have attached a picture. RED ARROW(data i need in next activity), BLUE ARROW(button press which takes me to next activity)

Screenshot of screen

I'm using this method to read the values

```<code>findMerchantTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (int i = 0; i < totalCards; i++) {
                    Spinner printColorSpinner = mRecyclerView.findViewHolderForLayoutPosition(i).itemView.findViewById(R.id.printColorSpinner);
                    Spinner printSidesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.printSidesSpinner);
                    Spinner printSizeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.paperSizeSpinner);
                    Spinner pagesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.pagesSpinner);
                    Spinner orientationSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.orientationSpinner);
                    Spinner bindingTypeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.bindingTypeSpinner);
                    MaterialTextView copiesTextView = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.copiesNumberText);
                    String color = printColorSpinner.getSelectedItem().toString().trim();
                    String sides = printSidesSpinner.getSelectedItem().toString().trim();
                    String size = printSizeSpinner.getSelectedItem().toString().trim();
                    String pages = pagesSpinner.getSelectedItem().toString().trim();
                    String orientation = orientationSpinner.getSelectedItem().toString().trim();
                    String bindingType = bindingTypeSpinner.getSelectedItem().toString().trim();
                    String totalCopies = copiesTextView.getText().toString().trim();
                }
            }
        });
</code>```

But when i becomes 2, findViewHolderForLayoutPosition returns NullPointerException. I searched and got to know that the views are recycled and only the views that are laid out on screen will be readable.

What will be the alternative to get these values? Thanks!

答:
Assuming one item is picked per spinner:

In the adapter of your RecyclerView:

```<code>class MyAdapter extends ...........{

//have these as member fields
public String color = "default";
public String sides = "default";
public String size = "default";
public String pages = "default";
public String orientation = "default";
public String bindingType = "default";
public String totalCopies = "default";
.......
.......

//when you interact with the spinners in onBindViewHolder

@Override
public void onBindViewHolder(........){

//on selecting color spinner item

holder.colorSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

      //set the color here
      color =
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {

    }

});

//on selecting sides spinner item

holder.sidesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

      //set the sides here
      sides =
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {

    }

});

// you get the idea, do the rest here..........

}

}
</code>```

In the activity that contains the Button that you want to click to send data:

```<code>class YourActivity extends .........{

//lets say you initialized the adapter like this

MyAdapter adapter = new MyAdapter(.....);

//when you click the button:

findMerchantTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent intent = new Intent(YourActivity.this , TheOtherActivityName.class);
intent.putExtra("color" , adapter.color);
intent.putExtra("sides" , adapter.sides);
intent.putExtra("size" , adapter.size);
intent.putExtra("pages" , adapter.pages);
intent.putExtra("orientation" , adapter.orientation);
intent.putExtra("bindingType" , adapter.bindingType);
intent.putExtra("totalCopies" , adapter.totalCopies);
startActivity(intent);

}

});

}
</code>```

In the activity that you want to read the data passed by the button:

```<code>class TheOtherActivityName extends .....{

//in onCreate()

String color = getIntent.getStringExtra("color");
String sides = getIntent.getStringExtra("sides");
String size = getIntent.getStringExtra("size");
........
........
........

}
</code>```

Body:
I have a recyclerview with a card and spinners in it, the values selected in the spinner I need to send it to the next activity to calculate estimated price. I have a button in the activity which is not of the recyclerview, that takes me to next activity where I need the values. So when I click this button I need it to collect the data and send it to next activity, how can I achieve that.

I have attached a picture. RED ARROW(data i need in next activity), BLUE ARROW(button press which takes me to next activity)

Screenshot of screen

I'm using this method to read the values

findMerchantTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (int i = 0; i < totalCards; i++) {
                    Spinner printColorSpinner = mRecyclerView.findViewHolderForLayoutPosition(i).itemView.findViewById(R.id.printColorSpinner);
                    Spinner printSidesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.printSidesSpinner);
                    Spinner printSizeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.paperSizeSpinner);
                    Spinner pagesSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.pagesSpinner);
                    Spinner orientationSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.orientationSpinner);
                    Spinner bindingTypeSpinner = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.bindingTypeSpinner);
                    MaterialTextView copiesTextView = mRecyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.copiesNumberText);
                    String color = printColorSpinner.getSelectedItem().toString().trim();
                    String sides = printSidesSpinner.getSelectedItem().toString().trim();
                    String size = printSizeSpinner.getSelectedItem().toString().trim();
                    String pages = pagesSpinner.getSelectedItem().toString().trim();
                    String orientation = orientationSpinner.getSelectedItem().toString().trim();
                    String bindingType = bindingTypeSpinner.getSelectedItem().toString().trim();
                    String totalCopies = copiesTextView.getText().toString().trim();
                }
            }
        });

But when i becomes 2, findViewHolderForLayoutPosition returns NullPointerException. I searched and got to know that the views are recycled and only the views that are laid out on screen will be readable.

What will be the alternative to get these values? Thanks!

Body:
Assuming one item is picked per spinner:

In the adapter of your RecyclerView:

class MyAdapter extends ...........{

//have these as member fields
public String color = "default";
public String sides = "default";
public String size = "default";
public String pages = "default";
public String orientation = "default";
public String bindingType = "default";
public String totalCopies = "default";
.......
.......

//when you interact with the spinners in onBindViewHolder

@Override
public void onBindViewHolder(........){

//on selecting color spinner item

holder.colorSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

      //set the color here
      color =
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {

    }

});

//on selecting sides spinner item

holder.sidesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

      //set the sides here
      sides =
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {

    }

});

// you get the idea, do the rest here..........

}

}

In the activity that contains the Button that you want to click to send data:

class YourActivity extends .........{

//lets say you initialized the adapter like this

MyAdapter adapter = new MyAdapter(.....);

//when you click the button:

findMerchantTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent intent = new Intent(YourActivity.this , TheOtherActivityName.class);
intent.putExtra("color" , adapter.color);
intent.putExtra("sides" , adapter.sides);
intent.putExtra("size" , adapter.size);
intent.putExtra("pages" , adapter.pages);
intent.putExtra("orientation" , adapter.orientation);
intent.putExtra("bindingType" , adapter.bindingType);
intent.putExtra("totalCopies" , adapter.totalCopies);
startActivity(intent);

}

});

}

In the activity that you want to read the data passed by the button:

class TheOtherActivityName extends .....{

//in onCreate()

String color = getIntent.getStringExtra("color");
String sides = getIntent.getStringExtra("sides");
String size = getIntent.getStringExtra("size");
........
........
........

}


问:
Angular Typescript why can assign a Promise<ClassA> to object of classA
I just start to learn angular and I found my company project has the following code:

```<code>currentCDFlow: CDCurrentFlowDTO;

this.currentCDFlow = await this.serivce.getCDMaster();
</code>```

and the getCDMaster() code is

```<code>public async getCDMaster(): Promise<CDCurrentFlowDTO> {
    return await this.http.post<CDCurrentFlowDTO>(Constants.BASE_HREF + '/getCDMaster', null, this.RequestJson).toPromise().catch(err => { throw err });
  }
</code>```

as getCDMaster() is returning Promise<CDCurrentFlowDTO> (a Promise object), why it can assign to object of CDCurrentFlowDTO? I expect it can only assign to object of Promise<CDCurrentFlowDTO>, but not just CDCurrentFlowDTO (without enclosed by Promise<...>).

As in java,

String a = new ArrayList<String>();

should have compile error...

Is this typescript feature?

答:
Answer to your original question

await

Using await unwraps the returned value from the promise.

So this line of code

```<code>this.currentCDFlow = await this.serivce.getCDMaster();
</code>```

actually assigns the resolved Promise value from the method to this.currentCDFlow.

If you don't use await in the assignment, TS will complain since you are trying to assign a promise to a non promise object.

```<code>currentCDFlow: CDCurrentFlowDTO;
this.currentCDFlow = this.serivce.getCDMaster(); //TS error
</code>```

Answer to your second question in your comment

async

When you declare a function with the async keyword, it will always return a Promise, no matter what you do inside (so including a return await ...).

Have a look here:

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Depending on which version of JS is used, it will either be handled natively by JS (starting from ES8) or in transpiled TS code.

So all functions below, for instance, will return a Promise. You can try them in your browser's console

```<code>async function test()
{
    return "value";
}

async function test2()
{
    return Promise.resolve("value");
}

async function test3()
{
    return await Promise.resolve("value");
}

console.log(test()); //Promise {<resolved>: "value"}
console.log(test2()); //Promise {<resolved>: "value"}
console.log(test3()); //Promise {<resolved>: "value"}
</code>```

So return myPromise and return await myPromise are often the same, with some exceptions like try/catch blocks, as explained here.

Body:
I just start to learn angular and I found my company project has the following code:

currentCDFlow: CDCurrentFlowDTO;

this.currentCDFlow = await this.serivce.getCDMaster();

and the getCDMaster() code is

public async getCDMaster(): Promise<CDCurrentFlowDTO> {
    return await this.http.post<CDCurrentFlowDTO>(Constants.BASE_HREF + '/getCDMaster', null, this.RequestJson).toPromise().catch(err => { throw err });
  }

as getCDMaster() is returning Promise<CDCurrentFlowDTO> (a Promise object), why it can assign to object of CDCurrentFlowDTO? I expect it can only assign to object of Promise<CDCurrentFlowDTO>, but not just CDCurrentFlowDTO (without enclosed by Promise<...>).

As in java,

String a = new ArrayList<String>();

should have compile error...

Is this typescript feature?

Body:
Answer to your original question

await

Using await unwraps the returned value from the promise.

So this line of code

this.currentCDFlow = await this.serivce.getCDMaster();

actually assigns the resolved Promise value from the method to this.currentCDFlow.

If you don't use await in the assignment, TS will complain since you are trying to assign a promise to a non promise object.

currentCDFlow: CDCurrentFlowDTO;
this.currentCDFlow = this.serivce.getCDMaster(); //TS error

Answer to your second question in your comment

async

When you declare a function with the async keyword, it will always return a Promise, no matter what you do inside (so including a return await ...).

Have a look here:

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Depending on which version of JS is used, it will either be handled natively by JS (starting from ES8) or in transpiled TS code.

So all functions below, for instance, will return a Promise. You can try them in your browser's console

async function test()
{
    return "value";
}

async function test2()
{
    return Promise.resolve("value");
}

async function test3()
{
    return await Promise.resolve("value");
}

console.log(test()); //Promise {<resolved>: "value"}
console.log(test2()); //Promise {<resolved>: "value"}
console.log(test3()); //Promise {<resolved>: "value"}

So return myPromise and return await myPromise are often the same, with some exceptions like try/catch blocks, as explained here.


问:
JSON with JavaScript and HTML
From this url: http://api.open-notify.org/astros.json, I am trying to get the name and craft of each person in space. I can't get it working with my URL, but it works with others... Any ideas?

My code:

```<code><html>
<body>
<table id="personDataTable">
    <tr>
        <th>Name</th>
        <th>Craft</th>
    </tr>

</table>

<style>
table {
  border: 2px solid #666;
    width: 100%;
}
th {
  background: #f8f8f8;
  font-weight: bold;
    padding: 2px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>

$.ajax({
    url: 'http://api.open-notify.org/astros.json',
    type: "get",
    dataType: "json",

    success: function(data) {
        drawTable(data);
    }
});

function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row);
    row.append($("<td>" + rowData.people.name + "</td>"));
    row.append($("<td>" + rowData.people.craft + "</td>"));
}
</script>

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

答:
Your Code is Ok But some mistake in access values:

Total Access into name is => data.people[index].name

"data" is Json Object Access values by key "people";

sub-level "people" is Json Array Access value by "index";

sub-level is Json Object Access value by key "name";

drawRow(data[i]) => drawRow(data.people[i]);

row.append($("" + rowData.people.name + "	")); => row.append($("" + rowData.name + "	"));

Note: Some way in HTML Use some variable by Let and try it in the console of browser to find mistakes, here you can put it like below :

Title: JSON with JavaScript and HTML

Body:
From this url: http://api.open-notify.org/astros.json, I am trying to get the name and craft of each person in space. I can't get it working with my URL, but it works with others... Any ideas?

My code:

        Name
        Craft

Body:
Your Code is Ok But some mistake in access values:

Total Access into name is => data.people[index].name

"data" is Json Object Access values by key "people";

sub-level "people" is Json Array Access value by "index";

sub-level is Json Object Access value by key "name";

drawRow(data[i]) => drawRow(data.people[i]);

row.append($("<td>" + rowData.people.name + "</td>")); => row.append($("<td>" + rowData.name + "</td>"));

Note: Some way in HTML Use some variable by Let and try it in the console of browser to find mistakes, here you can put it like below :

<script>
     let myJson; <============ Here
$.ajax({

and

success: function(data) {
     myJson = data; <============ Here
        drawTable(data);

Now you can access your Variable 'myJson' in the console of browser.

GoodLuck