问:
How to jump to a particular line in a huge text file?
Are there any alternatives to the code below:

```<code>startFromLine = 141978 # or whatever line I need to jump to

urlsfile = open(filename, "rb", 0)

linesCounter = 1

for line in urlsfile:
    if linesCounter > startFromLine:
        DoSomethingWithThisLine(line)

    linesCounter += 1
</code>```

If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.

答:
Here's an example using readlines(sizehint) to read a chunk of lines at a time. DNS pointed out that solution. I wrote this example because the other examples here are single-line oriented.

```<code>def getlineno(filename, lineno):
    if lineno < 1:
        raise TypeError("First line is line 1")
    f = open(filename)
    lines_read = 0
    while 1:
        lines = f.readlines(100000)
        if not lines:
            return None
        if lines_read + len(lines) >= lineno:
            return lines[lineno-lines_read-1]
        lines_read += len(lines)

print getlineno("nci_09425001_09450000.smi", 12000)
</code>```

Body:
Are there any alternatives to the code below:

startFromLine = 141978 # or whatever line I need to jump to

urlsfile = open(filename, "rb", 0)

linesCounter = 1

for line in urlsfile:
    if linesCounter > startFromLine:
        DoSomethingWithThisLine(line)

    linesCounter += 1

If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.

Body:
Here's an example using readlines(sizehint) to read a chunk of lines at a time. DNS pointed out that solution. I wrote this example because the other examples here are single-line oriented.

def getlineno(filename, lineno):
    if lineno < 1:
        raise TypeError("First line is line 1")
    f = open(filename)
    lines_read = 0
    while 1:
        lines = f.readlines(100000)
        if not lines:
            return None
        if lines_read + len(lines) >= lineno:
            return lines[lineno-lines_read-1]
        lines_read += len(lines)

print getlineno("nci_09425001_09450000.smi", 12000)


来源: stackexchange

问:
Regarding broadcast receiver android
Can an activity be invoked using a BroadcastReceiver? The onReceive for BroadCast receiver will be triggered whenever the user presses the power button.

答:
Yes we can invoke try below code</p>

```<code>Intent mIntent = new Intent(getBaseContext(), Activity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(mIntent);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regarding broadcast receiver android

Body:
Yes we can invoke try below code

Intent mIntent = new Intent(getBaseContext(), Activity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(mIntent);


问:
Amending sum_range in nested INDIRECT returns #Value error (SUMPRODUCT/SUMIFS)
Original, working formula

```<code>=SUMPRODUCT(SUMIFS(INDIRECT("'"&INVOICE&"'!"&"H48"), INDIRECT("'"&INVOICE&"'!"&"G11"),">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),"<="EOMONTH(C19,0)))
</code>```

Breakdown:

```<code>=SUMPRODUCT(
    SUMIFS(
        INDIRECT("'"&INVOICE&"'!"&"H48"),
        INDIRECT("'"&INVOICE&"'!"&"G11"),
        ">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),
        "<="EOMONTH(C19,0)
    )
)
</code>```

This above formula works pretty well to sum up all the amount (H48), I enter a month in C19, and sum is done against the invoice list of that month.

Formula which returns #Value Error

Currently having a problem where this Excel formula below returns a #Value! error

```<code>=SUMPRODUCT(SUMIFS(INDIRECT("'"&INVOICE&"'!"&"H19:H46"), INDIRECT("'"&INVOICE&"'!"&"G11"),">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),"<="EOMONTH(C19,0)))
</code>```

Breadown:

```<code>=SUMPRODUCT(
    SUMIFS(
        INDIRECT("'"&INVOICE&"'!"&"H19:H46"),   <== H48 replaced by H19:H46
        INDIRECT("'"&INVOICE&"'!"&"G11"),
        ">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),
        "<="EOMONTH(C19,0)
    )
)
</code>```

The only thing changed is the sum_range (H19:H46) which is the same total amount of value in H48.

Can anyone explain the #Value! in that 2nd formula and any solutions to it?

Any help is much appreciated :))

答:
This formula you can use multiple criteria, multiple sheet, with month-wise:  </p>

```<code>=SUMPRODUCT(SUMIFS(INDIRECT("'"&powerpp&"'!v2:v500"),INDIRECT("'"&powerpp&"'!$D$2:d500"),$D30,INDIRECT("'"&powerpp&"'!$e$2:e500"),$H$3,INDIRECT("'"&powerpp&"'!$c$2:c500"),">="&$P$25,INDIRECT("'"&powerpp&"'!$c$2:c500"),"<=" &EOMONTH($P$25,0)))
</code>```

Body:
Original, working formula

=SUMPRODUCT(SUMIFS(INDIRECT("'"&INVOICE&"'!"&"H48"), INDIRECT("'"&INVOICE&"'!"&"G11"),">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),"<="EOMONTH(C19,0)))

Breakdown:

=SUMPRODUCT(
    SUMIFS(
        INDIRECT("'"&INVOICE&"'!"&"H48"),
        INDIRECT("'"&INVOICE&"'!"&"G11"),
        ">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),
        "<="EOMONTH(C19,0)
    )
)

This above formula works pretty well to sum up all the amount (H48), I enter a month in C19, and sum is done against the invoice list of that month.

Formula which returns #Value Error

Currently having a problem where this Excel formula below returns a #Value! error

=SUMPRODUCT(SUMIFS(INDIRECT("'"&INVOICE&"'!"&"H19:H46"), INDIRECT("'"&INVOICE&"'!"&"G11"),">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),"<="EOMONTH(C19,0)))

Breadown:

=SUMPRODUCT(
    SUMIFS(
        INDIRECT("'"&INVOICE&"'!"&"H19:H46"),   <== H48 replaced by H19:H46
        INDIRECT("'"&INVOICE&"'!"&"G11"),
        ">="&C19,INDIRECT("'"&INVOICE&"'!"&"G11"),
        "<="EOMONTH(C19,0)
    )
)

The only thing changed is the sum_range (H19:H46) which is the same total amount of value in H48.

Can anyone explain the #Value! in that 2nd formula and any solutions to it?

Any help is much appreciated :))

Body:
This formula you can use multiple criteria, multiple sheet, with month-wise:

=SUMPRODUCT(SUMIFS(INDIRECT("'"&powerpp&"'!v2:v500"),INDIRECT("'"&powerpp&"'!$D$2:d500"),$D30,INDIRECT("'"&powerpp&"'!$e$2:e500"),$H$3,INDIRECT("'"&powerpp&"'!$c$2:c500"),">="&$P$25,INDIRECT("'"&powerpp&"'!$c$2:c500"),"<=" &EOMONTH($P$25,0)))

ContentLicense: CC BY-SA 4.0


问:
Styled Components / React - Style on Fragment element
I have a question with StyledComponents, it's possible to create a style using a React.Fragment or any other existing component?

I use this example (The intention is the Style ContainerFragment paints the background on blue and use all the styles)

Codepen

If it's not possible, exists another workaround? Explicit using Fragment as an example.

Update: I made a specific question with my real problem on this question

答:
key is the only attribute that can be passed to Fragment.
In the future, we may add support for additional attributes, such as event handlers.


问:
Can we say “If an API is following 6 constraints of REST then it’s a RESTful API”?
Can we say “If an API is following 6 constraints of REST then it’s a RESTful API”?
or my statement is completely wrong?</p>

答:
Well, you are half right.
Yes, there are 6 constraints that Mr. Roy Fielding described in his phD publication.
But, the last one "Code On Demand" is optional

Ref: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm


问:
Inline conditional rendering fail
I am trying to do an inline conditional rendering like the following:

```<code> {var && <MyComponent />}
</code>```

but it throws me this error:

Text strings must be rendered within a <Text> component

However when I do it like this:

{var !== '' && <MyComponent/ >}
It works perfectly fine.

Any idea why this happens?

答: That's because empty string will be rendered in the component as it's a falsy value (because && will return short-circuit value). And in react-native you can't render a string without wrapping it in Text component.

Title: Inline conditional rendering fail

Body:
I am trying to do an inline conditional rendering like the following:

 {var && <MyComponent />}

but it throws me this error:

Text strings must be rendered within a <Text> component

However when I do it like this:

{var !== '' && <MyComponent/ >}
It works perfectly fine.

Any idea why this happens?


问:
Number of consumers in kafka comsumer-group
If a producer has 3 topics and 4 partitions each topic, should the consumer group contains 4 or 12 consumers?
I want to achieve ideal consumption.</p>

答: There should be one consumer each partition for ideal consumption. So, for your case, 12 consumers should be ideal.


问:
How do I add a reaction emoji to the message the bot sends after doing the user's command?
I get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'message'--when trying to do await self.client.message.add_reaction(emoji).

I tried changing it to await ctx.message.add_reaction(emoji), and I realized that it reacted to the command the user sent rather than the bot's new message.

```<code>import discord
from discord.ext import commands

class MovieNight(commands.Cog):
    """Polls for Movie Night."""

    def __init__(self, client):
        self.client = client

    @commands.command(aliases=['m'])
    async def movie(self, ctx, year, *movie):
        movie_title = ' '.join(movie[:-1])
        await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")
        emoji = ''
        await self.client.message.add_reaction(emoji)

def setup(client):
    client.add_cog(MovieNight(client))
</code>```

答:
Adding onto Patrick's answer here from what you said in the comment.

await self.client.message.add_reaction(emoji) won't work because the bot doesn't know what message you're referring to, and client doesn't have an attribute called message.

Adding reactions requires a discord.Message object, which in your case can be either the command that the user executed (e.g. !movie 2020 movie title) which you can retrieve via ctx.message, or a message which you're making the bot send.

If you wanted to get the message object from the message that the bot sent, you can assign it to a variable:

msg = await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")
```

<p>And this allows you to then add a reaction to it or access any other message attributes you would like:</p>

<pre class="lang-py prettyprint-override"><code>emoji = ''
await msg.add_reaction(emoji)
</code>```

References:

discord.Message

Message.add_reaction()

TextChannel.send() - Here you can see it returns the message that was sent

Body:
I get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'message'--when trying to do await self.client.message.add_reaction(emoji).

I tried changing it to await ctx.message.add_reaction(emoji), and I realized that it reacted to the command the user sent rather than the bot's new message.

import discord
from discord.ext import commands

class MovieNight(commands.Cog):
    """Polls for Movie Night."""

    def __init__(self, client):
        self.client = client

    @commands.command(aliases=['m'])
    async def movie(self, ctx, year, *movie):
        movie_title = ' '.join(movie[:-1])
        await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")
        emoji = ''
        await self.client.message.add_reaction(emoji)

def setup(client):
    client.add_cog(MovieNight(client))

Body:
Adding onto Patrick's answer here from what you said in the comment.

await self.client.message.add_reaction(emoji) won't work because the bot doesn't know what message you're referring to, and client doesn't have an attribute called message.

Adding reactions requires a discord.Message object, which in your case can be either the command that the user executed (e.g. !movie 2020 movie title) which you can retrieve via ctx.message, or a message which you're making the bot send.

If you wanted to get the message object from the message that the bot sent, you can assign it to a variable:

msg = await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")

And this allows you to then add a reaction to it or access any other message attributes you would like:

emoji = ''
await msg.add_reaction(emoji)

References:

discord.Message

Message.add_reaction()

TextChannel.send() - Here you can see it returns the message that was sent


问:
NullPointerException when using FirebaseUI and RecyclerView
I followed this guide How to display data from Firestore in a RecyclerView with Android?, but am facing a NullPointerException in the setter in the ViewHolder. I'm also actually very unsure of what to do in the setter in the ViewHolder...

![database]https://imgur.com/a/wquZ08f

Model:

```<code>public class FoodModel {
    private String foodName;
    private String foodType;
    private String foodQty;
    private String foodExpDate;

    public FoodModel() {}

    public FoodModel(String name, String type, String qty, String expDate) {
        this.foodName = name;
        this.foodType = type;
        this.foodQty = qty;
        this.foodExpDate = expDate;
    }

    public String getFoodName() {return foodName;}
    public void setFoodName(String name) {foodName = name;}

    public String getFoodType() {return foodType;}
    public void setFoodType(String type) {foodType = type;}

    public String getFoodQty() {return foodQty;}
    public void setFoodQty(String qty) {foodQty = qty;}

    public String getFoodExpDate() {return foodExpDate;}
    public void setFoodExpDate(String expDate) {foodExpDate = expDate;}
}
</code>```

Activity code:

```<code>recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        Query foodQuery = db.collection("Food")
                .orderBy("food_name", Query.Direction.ASCENDING);

        FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>()
                .setQuery(foodQuery, FoodModel.class)
                .build();

        adapter = new FirestoreRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull FoodViewHolder holder, int position, @NonNull FoodModel model) {
                holder.setFoodName(model.getFoodName());
            }
            @NonNull
            @Override
            public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup group, int viewType) {
                View view = LayoutInflater.from(group.getContext()).inflate(R.layout.recycler_view_row, group, false);
                return new FoodViewHolder(view);
            }
        };
        recyclerView.setAdapter(adapter);
    }
    private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;

        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        void setFoodName(String foodName) {
            TextView textView = view.findViewById(R.id.editName);
            textView.setText(foodName);
        }
    }
</code>```

xml of recycler_view_row:

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

    <TextView
        android:id="@+id/foodListRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

errors:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.qremind, PID: 17735
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.qremind.FoodList$FoodViewHolder.setFoodName(FoodList.java:91)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:70)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:67)
        at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:158)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1897)
        at androidx.recyclerview.widget.RecyclerView$1.run(RecyclerView.java:414)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:878)
        at android.view.Choreographer.doCallbacks(Choreographer.java:690)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:864)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:185)
        at android.app.ActivityThread.main(ActivityThread.java:6473)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:806)
</code>```

答:
In FoodViewHolder class:

This method:

```<code>    void setFoodName(String foodName) {
         //here is your problem
        TextView textView = view.findViewById(R.id.editName);
        textView.setText(foodName);
    }
</code>```

Must be like this, you are pointing to the wrong ID:

```<code>    void setFoodName(String foodName) {

        TextView textView = view.findViewById(R.id.foodListRow);
        textView.setText(foodName);
    }
</code>```

Body:
I followed this guide How to display data from Firestore in a RecyclerView with Android?, but am facing a NullPointerException in the setter in the ViewHolder. I'm also actually very unsure of what to do in the setter in the ViewHolder...

![database]https://imgur.com/a/wquZ08f

Model:

public class FoodModel {
    private String foodName;
    private String foodType;
    private String foodQty;
    private String foodExpDate;

    public FoodModel() {}

    public FoodModel(String name, String type, String qty, String expDate) {
        this.foodName = name;
        this.foodType = type;
        this.foodQty = qty;
        this.foodExpDate = expDate;
    }

    public String getFoodName() {return foodName;}
    public void setFoodName(String name) {foodName = name;}

    public String getFoodType() {return foodType;}
    public void setFoodType(String type) {foodType = type;}

    public String getFoodQty() {return foodQty;}
    public void setFoodQty(String qty) {foodQty = qty;}

    public String getFoodExpDate() {return foodExpDate;}
    public void setFoodExpDate(String expDate) {foodExpDate = expDate;}
}

Activity code:

recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        Query foodQuery = db.collection("Food")
                .orderBy("food_name", Query.Direction.ASCENDING);

        FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>()
                .setQuery(foodQuery, FoodModel.class)
                .build();

        adapter = new FirestoreRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull FoodViewHolder holder, int position, @NonNull FoodModel model) {
                holder.setFoodName(model.getFoodName());
            }
            @NonNull
            @Override
            public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup group, int viewType) {
                View view = LayoutInflater.from(group.getContext()).inflate(R.layout.recycler_view_row, group, false);
                return new FoodViewHolder(view);
            }
        };
        recyclerView.setAdapter(adapter);
    }
    private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;

        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        void setFoodName(String foodName) {
            TextView textView = view.findViewById(R.id.editName);
            textView.setText(foodName);
        }
    }

xml of recycler_view_row:

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

    <TextView
        android:id="@+id/foodListRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

errors:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.qremind, PID: 17735
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.qremind.FoodList$FoodViewHolder.setFoodName(FoodList.java:91)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:70)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:67)
        at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:158)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1897)
        at androidx.recyclerview.widget.RecyclerView$1.run(RecyclerView.java:414)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:878)
        at android.view.Choreographer.doCallbacks(Choreographer.java:690)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:864)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:185)
        at android.app.ActivityThread.main(ActivityThread.java:6473)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:806)

Body:
In FoodViewHolder class:

This method:

    void setFoodName(String foodName) {
         //here is your problem
        TextView textView = view.findViewById(R.id.editName);
        textView.setText(foodName);
    }

Must be like this, you are pointing to the wrong ID:

    void setFoodName(String foodName) {

        TextView textView = view.findViewById(R.id.foodListRow);
        textView.setText(foodName);
    }


问:
How to make this with a for-loop?
Trying to make a batteship game and want to make the code more smooth...

```<code>#Board:
A = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"]
B = ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"]
C = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
D = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"]
E = ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"]
F = ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"]
G = ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"]
H = ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"]
I = ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"]
J = ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"]
print("\n",A,"\n",B,"\n",C,"\n",D,"\n",E,"\n",F,"\n",G,"\n",H,"\n",I,"\n",J)

#Variables
A_set = set(A)
B_set = set(B)
C_set = set(C)
D_set = set(D)
E_set = set(E)
F_set = set(F)
G_set = set(G)
H_set = set(H)
I_set = set(I)
J_set = set(J)
</code>```

When i check if the placed codinate are within the board I use this code:

```<code>def user_ship1():
    global nr1_user_ship
    nr1_user_ship = []
    print("Hide a ship within the board.")
    user_ship1 = input("")

    user_ship1 = user_ship1.capitalize()

    battlefield_check = set(user_ship1.split())

    within_battlefield0 = battlefield_check.intersection(A_set)
    within_battlefield1 = battlefield_check.intersection(B_set)
    within_battlefield2 = battlefield_check.intersection(C_set)
    within_battlefield3 = battlefield_check.intersection(D_set)
    within_battlefield4 = battlefield_check.intersection(E_set)
    within_battlefield5 = battlefield_check.intersection(F_set)
    within_battlefield6 = battlefield_check.intersection(G_set)
    within_battlefield7 = battlefield_check.intersection(H_set)
    within_battlefield8 = battlefield_check.intersection(I_set)
    within_battlefield9 = battlefield_check.intersection(J_set)

    if((within_battlefield0 == set()) and (within_battlefield1 == set()) and (within_battlefield2 == set()) and (within_battlefield3 == set()) and (within_battlefield4 == set()) and (within_battlefield5 == set()) and (within_battlefield6 == set()) and (within_battlefield7 == set()) and (within_battlefield8 == set()) and (within_battlefield9 == set())):
        print("Ship needs to be within the board.")
        exit()
    else:
        print("Great! Place another ship.")
    nr1_user_ship.append(user_ship1)
</code>```

So how can I use this in a forloop instead and how do I change the code so I don't use the "global" variable

答:
In terms of refactoring the code and making it "more smooth", I would start by switching to a different data structure like a list or dictionary instead of opting for creating many variables with prefixes.

For the board for example, how about making the board a 2D array?

```<code>board = [ ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"],
          ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"],
          ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"],
          ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"],
          ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"],
          ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"],
          ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"],
          ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"],
          ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"],
          ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"] ]

print "\n".join(board)
</code>```

As can be seen, each board item value is quite formulaic: "[row letter][column number 0 indexed]". So how about looping through each letter row and column and generating the board dynamically, like this?

```<code>board = [[None] * 10] * 10
for letterIdx, letter in enumerate(list("ABCDEFGHIJ")):
    for columnNum in range(10):
        board[letterIdx][columnNum] = letter + str(columnNum)
</code>```

After refactoring this part, you can automatically generate the sets for each letter row like this for example:

```<code>boardSets = [None] * 10
for rowIdx, row in enumerate(board):
    boardSets[rowIdx] = set(row)
</code>```

For the "within_battlefield" prefixed variables, you could put all of those in a list as well.

```<code>withinBattlefield = []
for rowSetIdx, rowSet in enumerate(boardSets):
    withinBattlefield[rowSetIdx] = battlefield_check.intersection(rowSet)
</code>```

Now that everything is in a list, you could simply use a for loop and single conditional instead of the long if statement:

```<code>inBoard = true
for rowInBattlefield in withinBattlefield:
    if(rowInBattlefield == set()):
        inBoard = false

if(not inBoard):
    print("Ship needs to be within the board.")
    exit()
else:
    print("Great! Place another ship.")
</code>```

This is just one example of how to refactor this code to be cleaner. Of course, this can be further refactored to be cleaner by adding variables for letters, board size, by putting some common functionality within functions, and so on.

I hope this answers your question and I wish you good luck on the battleship project!

Title: How to make this with a for-loop?

Body:
Trying to make a batteship game and want to make the code more smooth...

#Board:
A = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"]
B = ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"]
C = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
D = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"]
E = ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"]
F = ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"]
G = ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"]
H = ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"]
I = ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"]
J = ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"]
print("\n",A,"\n",B,"\n",C,"\n",D,"\n",E,"\n",F,"\n",G,"\n",H,"\n",I,"\n",J)

#Variables
A_set = set(A)
B_set = set(B)
C_set = set(C)
D_set = set(D)
E_set = set(E)
F_set = set(F)
G_set = set(G)
H_set = set(H)
I_set = set(I)
J_set = set(J)

When i check if the placed codinate are within the board I use this code:

def user_ship1():
    global nr1_user_ship
    nr1_user_ship = []
    print("Hide a ship within the board.")
    user_ship1 = input("")

    user_ship1 = user_ship1.capitalize()

    battlefield_check = set(user_ship1.split())

    within_battlefield0 = battlefield_check.intersection(A_set)
    within_battlefield1 = battlefield_check.intersection(B_set)
    within_battlefield2 = battlefield_check.intersection(C_set)
    within_battlefield3 = battlefield_check.intersection(D_set)
    within_battlefield4 = battlefield_check.intersection(E_set)
    within_battlefield5 = battlefield_check.intersection(F_set)
    within_battlefield6 = battlefield_check.intersection(G_set)
    within_battlefield7 = battlefield_check.intersection(H_set)
    within_battlefield8 = battlefield_check.intersection(I_set)
    within_battlefield9 = battlefield_check.intersection(J_set)

    if((within_battlefield0 == set()) and (within_battlefield1 == set()) and (within_battlefield2 == set()) and (within_battlefield3 == set()) and (within_battlefield4 == set()) and (within_battlefield5 == set()) and (within_battlefield6 == set()) and (within_battlefield7 == set()) and (within_battlefield8 == set()) and (within_battlefield9 == set())):
        print("Ship needs to be within the board.")
        exit()
    else:
        print("Great! Place another ship.")
    nr1_user_ship.append(user_ship1)

So how can I use this in a forloop instead and how do I change the code so I don't use the "global" variable

Body:
In terms of refactoring the code and making it "more smooth", I would start by switching to a different data structure like a list or dictionary instead of opting for creating many variables with prefixes.

For the board for example, how about making the board a 2D array?

board = [ ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"],
          ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"],
          ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"],
          ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"],
          ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"],
          ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"],
          ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"],
          ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"],
          ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"],
          ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"] ]

print "\n".join(board)

As can be seen, each board item value is quite formulaic: "[row letter][column number 0 indexed]". So how about looping through each letter row and column and generating the board dynamically, like this?

board = [[None] * 10] * 10
for letterIdx, letter in enumerate(list("ABCDEFGHIJ")):
    for columnNum in range(10):
        board[letterIdx][columnNum] = letter + str(columnNum)

After refactoring this part, you can automatically generate the sets for each letter row like this for example:

boardSets = [None] * 10
for rowIdx, row in enumerate(board):
    boardSets[rowIdx] = set(row)

For the "within_battlefield" prefixed variables, you could put all of those in a list as well.

withinBattlefield = []
for rowSetIdx, rowSet in enumerate(boardSets):
    withinBattlefield[rowSetIdx] = battlefield_check.intersection(rowSet)

Now that everything is in a list, you could simply use a for loop and single conditional instead of the long if statement:

inBoard = true
for rowInBattlefield in withinBattlefield:
    if(rowInBattlefield == set()):
        inBoard = false

if(not inBoard):
    print("Ship needs to be within the board.")
    exit()
else:
    print("Great! Place another ship.")

This is just one example of how to refactor this code to be cleaner. Of course, this can be further refactored to be cleaner by adding variables for letters, board size, by putting some common functionality within functions, and so on.

I hope this answers your question and I wish you good luck on the battleship project!


问:
How to merge elements of a collection in one array using Eloquent
I'm trying the following:

I'm getting all clinic_tests related to my patients using the following function:

```<code>public function getPatientsClinicTests(Specialist $id)
  {
        $patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); });

        $result = [];
        foreach ($patientClinicTests as $array) {
            $result = array_merge($result, $array->toArray());
        }

        return $result;
    }
</code>```

First group of code:

```<code>$patientClinicTests = $id->patients()
                ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
                ->get()
                ->pluck('PatientClinicTests')
                ->filter(function ($value) { return !empty($value); });
</code>```

Brings me a collection of arrays as follows:

```<code>[
  [
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    .....
  ],
  [
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
  ]
]
</code>```

As I need to return one array of elements I combine the arrays I got as follows:

```<code>$result = [];
    foreach ($patientClinicTests as $array) {
        $result = array_merge($result, $array->toArray());
    }

    return $result;
</code>```

This returns one array as follows:

```<code>[
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
]
</code>```

I would like to know if there is a smarter option to return as one array of elements using Eloquent instead a foreach statement.

Thanks a lot for your help!

答:
maybe you can use a collect method over the array to allign it in a single array

https://laravel.com/docs/7.x/collections

the link may be helpful

```<code>$collection = collect($patientClinicTests);
$collections = $collection->values()->all();
</code>```

maybe this will work

Body:
I'm trying the following:

I'm getting all clinic_tests related to my patients using the following function:

public function getPatientsClinicTests(Specialist $id)
  {
        $patientClinicTests = $id->patients()
            ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
            ->get()
            ->pluck('PatientClinicTests')
            ->filter(function ($value) { return !empty($value); });

        $result = [];
        foreach ($patientClinicTests as $array) {
            $result = array_merge($result, $array->toArray());
        }

        return $result;
    }

First group of code:

$patientClinicTests = $id->patients()
                ->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
                ->get()
                ->pluck('PatientClinicTests')
                ->filter(function ($value) { return !empty($value); });

Brings me a collection of arrays as follows:

[
  [
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    .....
  ],
  [
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
  ]
]

As I need to return one array of elements I combine the arrays I got as follows:

$result = [];
    foreach ($patientClinicTests as $array) {
        $result = array_merge($result, $array->toArray());
    }

    return $result;

This returns one array as follows:

[
    {
      "id": 16,
      "patient_id": 7,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 7,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Austen Wiegand",
        }
      }
    },
    {
      "id": 22,
      "patient_id": 1,
      "medical_condition_id": null,
      "patient": {
        "id": 7,
        "user_id": 1,
        "pigment_id": 14,
        "id_medical_history": "6219116421",
        "user": {
          "id": 7,
          "name": "Gregor Wiegand",
        }
      }
    },
    .......
]

I would like to know if there is a smarter option to return as one array of elements using Eloquent instead a foreach statement.

Thanks a lot for your help!

Body:
maybe you can use a collect method over the array to allign it in a single array

https://laravel.com/docs/7.x/collections

the link may be helpful

$collection = collect($patientClinicTests);
$collections = $collection->values()->all();

maybe this will work


问:
Problem with A Sync callback function in GWT
What I'm doing is:

```<code>getSecroleByOrgNID(orgList[i-2],cu.currentUser.getProfileObj());
System.out.println("Value of sec role is "+ secondryRole);
</code>```

where the getSecroleByOrgNID function is:

```<code>private String getSecroleByOrgNID(COrganization srOrg, CProfile srUser) {
    analyticsSrvc.getSecroleByOrgNID(srOrg, srUser,
        new AsyncCallback<String>() {
            @Override
            public void onFailure(Throwable caught) {
            }

            @Override
            public void onSuccess(String result) {
                secondryRole = result;
                System.out.println("Assigned role is " + secondryRole);
            }
        });
    return null;
}
</code>```

where secondryRole is

```<code>String secondryRole = " ";
</code>```

The output is:

```<code>Value of sec role is
Assigned role is Admin
</code>```

Query is why the "value of sec role is " statement prints before "Assigned role is Admin" since the function is called before print statement of "value of sec role is ".
And why does the value of secondryRole remain " " even though its value is reassigned inside the function?

答:
As GWT docs says, in GWT you have to "embrace asynchronous transactions" and forget about synchronous ones.

The problem is that getSecroleByOrgNID() invoke an asynchronous call to the server but this call doesn't stop execution, so it continues his work (server needs more time to return). You are asking for secondryRole when server doesn't response yet.

You should call a method always inside onSuccess() that work with server response.

Body:
What I'm doing is:

getSecroleByOrgNID(orgList[i-2],cu.currentUser.getProfileObj());
System.out.println("Value of sec role is "+ secondryRole);

where the getSecroleByOrgNID function is:

private String getSecroleByOrgNID(COrganization srOrg, CProfile srUser) {
    analyticsSrvc.getSecroleByOrgNID(srOrg, srUser,
        new AsyncCallback<String>() {
            @Override
            public void onFailure(Throwable caught) {
            }

            @Override
            public void onSuccess(String result) {
                secondryRole = result;
                System.out.println("Assigned role is " + secondryRole);
            }
        });
    return null;
}

where secondryRole is

String secondryRole = " ";

The output is:

Value of sec role is
Assigned role is Admin

Query is why the "value of sec role is " statement prints before "Assigned role is Admin" since the function is called before print statement of "value of sec role is ".
And why does the value of secondryRole remain " " even though its value is reassigned inside the function?


问:
Bokeh callbacks with CustomJS: is there a way to trigger a callback with CustomJS from inside another callback with custom JS?
Bokeh callbacks with CustomJS: is there a way to trigger a callback with CustomJS from inside another callback with custom JS? Additionally and related to the first question: is there a way to prevent triggering a callback when modifying the property or producing the event that triggers that callback? I have been trying to find information or a way to do this from the Bokeh docs but I can't find anything.</p>

答:
Calling CustomJS from CustomJS - yes, absolutely. CustomJS is an object with an execute method that accepts cb_obj and cb_data. Just call it like a regular method and that's it.

Setting a property without triggering callbacks - it's possible in JavaScript, but it's an implementation detail that you should not rely on. If you're interested, look up the source of the HasProps class in BokehJS source code, it has a setv method. And I don't think it's possible at all in Python.


问:
razor MVC EF how to show and hide a div based on model condition
Total noob here :)
I have simple form on my index.cshtml that submits values to m y controller and which also displays the results. I would like this form to be hidden @if (Model != null). It looks like this:

    <form id="certlookup" class="form-inline" role="form" method="get">

<input class="form-control" name="prefix" placeholder="99" maxlength="2" type="number" required />

<select class="form-control dropdown" name="type" id="type"><option value="A">A</option><option value="B">B</option></select>

                <input class="form-control" name="suffix" placeholder="9999" maxlength="4" type="number" required />

                <input class="btn btn-primary" type="submit" value="Go!" />

    </form>

@if (Model != null)
{...}```

I'm not sure what the best way to do this is. I tried to set a variable after my Model != null statement, setting the class=@hidden, but that variable wasn't available in the form above.

Is this going to be possible? This is for a mobile first site so I'd like the form input to go away after the results are provided but ideally I don't want to use a separate page for form and results.
Thanks!

答:
You can use this condition in MVC view  with FirstOrDefault() or without

this was solved my issue :

```<code>@if (Model.Table_Name.FirstOrDefault().Column_Name.HasValue == true)

<div>

// your code

</div>
</code>```

Body:
Total noob here :)
I have simple form on my index.cshtml that submits values to m y controller and which also displays the results. I would like this form to be hidden @if (Model != null). It looks like this:

    <form id="certlookup" class="form-inline" role="form" method="get">

<input class="form-control" name="prefix" placeholder="99" maxlength="2" type="number" required />

<select class="form-control dropdown" name="type" id="type"><option value="A">A</option><option value="B">B</option></select>

                <input class="form-control" name="suffix" placeholder="9999" maxlength="4" type="number" required />

                <input class="btn btn-primary" type="submit" value="Go!" />

    </form>

@if (Model != null)
{...}

I'm not sure what the best way to do this is. I tried to set a variable after my Model != null statement, setting the class=@hidden, but that variable wasn't available in the form above.

Is this going to be possible? This is for a mobile first site so I'd like the form input to go away after the results are provided but ideally I don't want to use a separate page for form and results.
Thanks!

Body:
You can use this condition in MVC view  with FirstOrDefault() or without

this was solved my issue :

@if (Model.Table_Name.FirstOrDefault().Column_Name.HasValue == true)

<div>

// your code

</div>


问:
Python converting waterfall figure to plotly
I am using the waterfall_chart package in Python to create a waterfall figure. The package mainly uses matplotlib in the backend, so I was trying to use the tls.mpl_to_plotly(mpl_fig) function to covert the matplotlib figure into plotly. But when converting, an error pops up. Is there a way to convert waterfall_chart into plotly or is there an easy way to create the chart directly in plotly? I saw some previous discussion on similar chart in plotly, but it involved pretty manual coding of the chart number.

You could use the following code to recreate the chart.

```<code>import waterfall_chart
import matplotlib.pyplot as plt
import plotly.tools as tls

a = ['sales','returns','credit fees','rebates','late charges','shipping']
b = [10,-30,-7.5,-25,95,-7]
mpl_fig = plt.figure()
waterfall_chart.plot(a, b)

plt.show()
</code>```

waterfall chart

But when I try to convert to plotly using mpl_to_plotly(), there is an error:

```<code>plotly_fig = tls.mpl_to_plotly(mpl_fig)

ValueError: min() arg is an empty sequence
</code>```

The detail of the waterfall_chart package could be found here: https://github.com/chrispaulca/waterfall/blob/master/waterfall_chart.py

答:
List a has a length of 6, list b has a length of 5.
Matplotlib refuses to display an empty array, list or whatever.
Solve it to add a number or 0 to b or add an if to your code, to avoid matplotlib gets an empty sequence.</p>

Body:
I am using the waterfall_chart package in Python to create a waterfall figure. The package mainly uses matplotlib in the backend, so I was trying to use the tls.mpl_to_plotly(mpl_fig) function to covert the matplotlib figure into plotly. But when converting, an error pops up. Is there a way to convert waterfall_chart into plotly or is there an easy way to create the chart directly in plotly? I saw some previous discussion on similar chart in plotly, but it involved pretty manual coding of the chart number.

You could use the following code to recreate the chart.

import waterfall_chart
import matplotlib.pyplot as plt
import plotly.tools as tls

a = ['sales','returns','credit fees','rebates','late charges','shipping']
b = [10,-30,-7.5,-25,95,-7]
mpl_fig = plt.figure()
waterfall_chart.plot(a, b)

plt.show()

waterfall chart

But when I try to convert to plotly using mpl_to_plotly(), there is an error:

plotly_fig = tls.mpl_to_plotly(mpl_fig)

ValueError: min() arg is an empty sequence

The detail of the waterfall_chart package could be found here: https://github.com/chrispaulca/waterfall/blob/master/waterfall_chart.py


问:
Matplotlib axes confused
I'm trying to figure out where I went wrong with this plot, I'm trying to get the axes to go from 0-1 but this one is going from 0.1-0-1, and I'm not too sure where I'm going wrong.
the csv file is in the following format:

dishwasher,60,1,1,0,1,0,0.1

```<code>import matplotlib.pyplot as plt
import numpy as np
import csv

x = np.array([1,2,3,4,5,6])
with open('Test 5.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=rows[0][2:]
y2=rows[1][2:]

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.legend()
plt.show()
</code>```

the plot comes out as followed:

The only solution I could think of was to invert the axes or to outline the scale for the y-axis but neither worked

答:
Your y values are most seemingly strings that's why your y-axis is out of order. Convert them to floats before plotting using the following list comprehension way

```<code>y1=rows[0][2:]
y2=rows[1][2:]

y1 = [float(i) for i in y1] # <--- convert to float
y2 = [float(i) for i in y2] # <--- convert to float

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
</code>```

You can also use a map function as following

```<code>y1 = list(map(float, y1))
y2 = list(map(float, y2))
</code>```

Title: Matplotlib axes confused

Body:
I'm trying to figure out where I went wrong with this plot, I'm trying to get the axes to go from 0-1 but this one is going from 0.1-0-1, and I'm not too sure where I'm going wrong.
the csv file is in the following format:

dishwasher,60,1,1,0,1,0,0.1

import matplotlib.pyplot as plt
import numpy as np
import csv

x = np.array([1,2,3,4,5,6])
with open('Test 5.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=rows[0][2:]
y2=rows[1][2:]

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.legend()
plt.show()

the plot comes out as followed:

The only solution I could think of was to invert the axes or to outline the scale for the y-axis but neither worked

Body:
Your y values are most seemingly strings that's why your y-axis is out of order. Convert them to floats before plotting using the following list comprehension way

y1=rows[0][2:]
y2=rows[1][2:]

y1 = [float(i) for i in y1] # <--- convert to float
y2 = [float(i) for i in y2] # <--- convert to float

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')

You can also use a map function as following

y1 = list(map(float, y1))
y2 = list(map(float, y2))


问:
Infinite cycle due to QTextStream
So, I get infinite cycle while trying to read lines from file (line by line). I was trying to use do{}while(); cycle like that:

```<code>QTextStream stream(stdin);
QString line;
do {
    line = stream.readLine();
} while (!line.isNull());
</code>```

but I get empty string.

Sure, I checked file path (it is right). I was trying to use /Users/user/tts.txt path but without changes. I was trying to read other files (like m3u). And it's not working on macOS Catalina, Windows 10, Linux (Debian).

So, why did I get infinite cycle?

```<code>QStringList Manager::GetLinesFromFile(const QString &nameOfFile)
{
    QStringList lines = {};

    //path to file
    const QString path = QCoreApplication::applicationDirPath() + "/bin/" + "tts.txt";
    //"/Users/user/tts.txt"

    QFile buffer;
    buffer.QFile::setFileName(path);

    #ifndef Q_DEBUG
    qDebug() << path;
    #endif

    if(buffer.QFile::exists())
    {
        if(!buffer.QIODevice::open(QIODevice::ReadOnly))
        {
            #ifndef Q_DEBUG
            qCritical() << "error: can't open file";
            #endif
        }
        else
        {
            QTextStream stream(&buffer);

             // both conditions
            // (!stream.QTextStream::atEnd())
            while(!buffer.QFileDevice::atEnd())
                lines.QList::push_back(stream.QTextStream::readLine());

            buffer.QFile::close();
        }
    }
    else
    {
        #ifndef Q_DEBUG
        qCritical() << "error: file not exists";
        #endif
    }

    return lines;
}
</code>```

答: Have a look at the QTextstream documentation https://doc.qt.io/qt-5/qtextstream.html. There is an example of reading line by line. Your while loop should read until the stream reaches the end of the buffer and many of the in built read functions will return false when his happens</p>

Title: Infinite cycle due to QTextStream

Body:
So, I get infinite cycle while trying to read lines from file (line by line). I was trying to use do{}while(); cycle like that:

QTextStream stream(stdin);
QString line;
do {
    line = stream.readLine();
} while (!line.isNull());

but I get empty string.

Sure, I checked file path (it is right). I was trying to use /Users/user/tts.txt path but without changes. I was trying to read other files (like m3u). And it's not working on macOS Catalina, Windows 10, Linux (Debian).

So, why did I get infinite cycle?

QStringList Manager::GetLinesFromFile(const QString &nameOfFile)
{
    QStringList lines = {};

    //path to file
    const QString path = QCoreApplication::applicationDirPath() + "/bin/" + "tts.txt";
    //"/Users/user/tts.txt"

    QFile buffer;
    buffer.QFile::setFileName(path);

    #ifndef Q_DEBUG
    qDebug() << path;
    #endif

    if(buffer.QFile::exists())
    {
        if(!buffer.QIODevice::open(QIODevice::ReadOnly))
        {
            #ifndef Q_DEBUG
            qCritical() << "error: can't open file";
            #endif
        }
        else
        {
            QTextStream stream(&buffer);

             // both conditions
            // (!stream.QTextStream::atEnd())
            while(!buffer.QFileDevice::atEnd())
                lines.QList::push_back(stream.QTextStream::readLine());

            buffer.QFile::close();
        }
    }
    else
    {
        #ifndef Q_DEBUG
        qCritical() << "error: file not exists";
        #endif
    }

    return lines;
}


问:
Adjustable lambda to different lists
I am sorting different lists. For example:

One list has 3 integers: [[3, 4, 2], [3, 5, 3]]

The other has 4: [[3, 4, 2, 4], [3, 5,3 ,2]]

Like this there are more, ranging from two to five integers.

I could do this manually for every list, but since I'm still learning I could ask how this is done automatically!

So I have this code for rearranging the list in descending order

```<code>l.sort(key=lambda x: [x[0], x[1], x[2], x[3]], reverse = True)
</code>```

This would work for the second example, but for the first example it would give:

```<code>IndexError: list index out of range
</code>```

So my thought was something like this:

```<code>key = lambda x: [x[i] for i in range(len(l[0]))]
</code>```

but it didn't work..

Does anybody knows if in this situation you can have an adjustable lambda?

答:
I'm not quite sure if I get your question correctly, as you talk about one list in each case but then again show lists looking like lists of lists.

So for the simple case of a normal list, python provides sorting already, you don't need lambda:

```<code>>>> a = [3,2,7,1,11]
>>> b = sorted(a)
>>> b
[1, 2, 3, 7, 11]
>>> b = sorted(a, reverse=True)
>>> b
[11, 7, 3, 2, 1]
>>>
</code>```

Check here for more options on sorting: https://docs.python.org/3/howto/sorting.html

Now if you have a list of lists, you could go for something like this:

```<code>>>> a = [[1,5,2],[3,4,1]]
>>> a
[[1, 5, 2], [3, 4, 1]]
>>> for idx,ls in enumerate(a):
    a[idx] = sorted(ls, reverse=True)

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

which you could then use in a map function if you wanted to use a lambda:

```<code>>>> a = [[1,5,2],[3,4,1]]
>>> b = map(lambda x: sorted(x, reverse=True),a)
>>> b
<map object at 0x03C0F220>
>>> list(b)
[[5, 2, 1], [4, 3, 1]]
>>>
</code>```

Note to put the list keyword infront of the map object to make it a list.

Title: Adjustable lambda to different lists

Body:
I am sorting different lists. For example:

One list has 3 integers: [[3, 4, 2], [3, 5, 3]]

The other has 4: [[3, 4, 2, 4], [3, 5,3 ,2]]

Like this there are more, ranging from two to five integers.

I could do this manually for every list, but since I'm still learning I could ask how this is done automatically!

So I have this code for rearranging the list in descending order

l.sort(key=lambda x: [x[0], x[1], x[2], x[3]], reverse = True)

This would work for the second example, but for the first example it would give:

IndexError: list index out of range

So my thought was something like this:

key = lambda x: [x[i] for i in range(len(l[0]))]

but it didn't work..

Does anybody knows if in this situation you can have an adjustable lambda?

Body:
I'm not quite sure if I get your question correctly, as you talk about one list in each case but then again show lists looking like lists of lists.

So for the simple case of a normal list, python provides sorting already, you don't need lambda:

>>> a = [3,2,7,1,11]
>>> b = sorted(a)
>>> b
[1, 2, 3, 7, 11]
>>> b = sorted(a, reverse=True)
>>> b
[11, 7, 3, 2, 1]
>>>

Check here for more options on sorting: https://docs.python.org/3/howto/sorting.html

Now if you have a list of lists, you could go for something like this:

>>> a = [[1,5,2],[3,4,1]]
>>> a
[[1, 5, 2], [3, 4, 1]]
>>> for idx,ls in enumerate(a):
    a[idx] = sorted(ls, reverse=True)

>>> a
[[5, 2, 1], [4, 3, 1]]

which you could then use in a map function if you wanted to use a lambda:

>>> a = [[1,5,2],[3,4,1]]
>>> b = map(lambda x: sorted(x, reverse=True),a)
>>> b
<map object at 0x03C0F220>
>>> list(b)
[[5, 2, 1], [4, 3, 1]]
>>>

Note to put the list keyword infront of the map object to make it a list.


问:
How to change touch position when passing a UITouch object?
```<code>- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  if(touchDelegate_)
  {

    // before passing the event, I want to scale touch position by 2, how can i do it?

    // that is, if touch position is (5, 5), I want touchDelegate_ see it as (10, 10)

    [touchDelegate_ touchesBegan:touches withEvent:event];

  }
}
</code>```

答: It's not possible. UITouch is a readonly object. There is no public API that allows you to manipulate it at the moment.


问:
My javascript function for clearing a form text input field is not working
Even though a lot of work is left, the basic calculator is done, everything is working just fine except the clear function. I can not get it to clear the viewer. need immediate help please.

(i put everything in one file so it is easy for everyone to understand the full thing)

Please avoid the styling tho.

So basically i made this extremely simple calculator with the function clear()
Any ideas on how i can make this function in order to clear the viewer?

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

<head>

<script>
  function insert(num) {
    document.view.viewer.value = document.view.viewer.value+num
  }
  function equal() {
    document.view.viewer.value = eval(document.view.viewer.value);
  }
  function clear() {
    document.view.viewer.value = "";
  }
</script>

<style>
body {
  background-image: url("peepee.png");
}
*{
  margin: 0px;
  padding: 0px;
}
.button {
  height:100px;
  width:100px;
  background-color:grey;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.clear {
  height:100px;
  width:400px;
  background-color: red;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.viewer {
  height: 100px;
  width: 430px;
  font-size: 50px;
  margin: 2px
}
</style>

</head>

<body>
  <div class= "main">
    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>
    <table>
      <tr>
        <td><input class="button" value="7" onclick= "insert(7)"></td>
        <td><input class="button" value="8" onclick= "insert(8)"></td>
        <td><input class="button" value="9" onclick= "insert(9)"></td>
        <td><input class="button" value="-" onclick= "insert('/')"></td>
      </tr>
      <tr>
        <td><input class="button" value="4" onclick= "insert(4)"></td>
        <td><input class="button" value="5" onclick= "insert(5)"></td>
        <td><input class="button" value="6" onclick= "insert(6)"></td>
        <td><input class="button" value="x" onclick= "insert('*')"></td>
      </tr>
      <tr>
        <td><input class="button" value="1" onclick= "insert(1)"></td>
        <td><input class="button" value="2" onclick= "insert(2)"></td>
        <td><input class="button" value="3" onclick= "insert(3)"></td>
        <td><input class="button" value="-" onclick= "insert('-')"></td>
      </tr>
      <tr>
        <td><input class="button" value="0" onclick= "insert(0)"></td>
        <td><input class="button" value="." onclick= "insert('.')"></td>
        <td><input class="button" value="=" onclick= "equal()"></td>
        <td><input class="button" value="+" onclick= "insert('+')"></td>
      </tr>
    </table>
    <table>
      <tr>
        <td><input class= "clear" value="Clear" onclick= "clear()"></td>
      </tr>
    </table>
  </div>
</body>

</html>
</code>```

答:
function insert(num) {

    document.view.viewer.value = document.view.viewer.value+num
  }
  function equal() {
    document.view.viewer.value = eval(document.view.viewer.value);
  }
  function clearInput() {
  document.view.viewer.value = "";
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-image: url("peepee.png");
}
*{
  margin: 0px;
  padding: 0px;
}
.button {
  height:100px;
  width:100px;
  background-color:grey;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.clear {
  height:100px;
  width:400px;
  background-color: red;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.viewer {
  height: 100px;
  width: 430px;
  font-size: 50px;
  margin: 2px
}</code>```

<!DOCTYPE html>

    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>

        <input class="button" value="7" onclick= "insert(7)">
        <input class="button" value="8" onclick= "insert(8)">
        <input class="button" value="9" onclick= "insert(9)">
        <input class="button" value="-" onclick= "insert('/')">

        <input class="button" value="4" onclick= "insert(4)">
        <input class="button" value="5" onclick= "insert(5)">
        <input class="button" value="6" onclick= "insert(6)">
        <input class="button" value="x" onclick= "insert('*')">

        <input class="button" value="1" onclick= "insert(1)">
        <input class="button" value="2" onclick= "insert(2)">
        <input class="button" value="3" onclick= "insert(3)">
        <input class="button" value="-" onclick= "insert('-')">

        <input class="button" value="0" onclick= "insert(0)">
        <input class="button" value="." onclick= "insert('.')">
        <input class="button" value="=" onclick= "equal()">
        <input class="button" value="+" onclick= "insert('+')">

        <input class= "clear" value="Clear" onclick= "clearInput()" type="button" />

```

Body:
Even though a lot of work is left, the basic calculator is done, everything is working just fine except the clear function. I can not get it to clear the viewer. need immediate help please.

(i put everything in one file so it is easy for everyone to understand the full thing)

Please avoid the styling tho.

So basically i made this extremely simple calculator with the function clear()
Any ideas on how i can make this function in order to clear the viewer?

<!DOCTYPE html>

    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>

        <input class="button" value="7" onclick= "insert(7)">
        <input class="button" value="8" onclick= "insert(8)">
        <input class="button" value="9" onclick= "insert(9)">
        <input class="button" value="-" onclick= "insert('/')">

        <input class="button" value="4" onclick= "insert(4)">
        <input class="button" value="5" onclick= "insert(5)">
        <input class="button" value="6" onclick= "insert(6)">
        <input class="button" value="x" onclick= "insert('*')">

        <input class="button" value="1" onclick= "insert(1)">
        <input class="button" value="2" onclick= "insert(2)">
        <input class="button" value="3" onclick= "insert(3)">
        <input class="button" value="-" onclick= "insert('-')">

        <input class="button" value="0" onclick= "insert(0)">
        <input class="button" value="." onclick= "insert('.')">
        <input class="button" value="=" onclick= "equal()">
        <input class="button" value="+" onclick= "insert('+')">

        <input class= "clear" value="Clear" onclick= "clear()">

Body:
function insert(num) {

    document.view.viewer.value = document.view.viewer.value+num
  }
  function equal() {
    document.view.viewer.value = eval(document.view.viewer.value);
  }
  function clearInput() {
  document.view.viewer.value = "";
  }

body {
  background-image: url("peepee.png");
}
*{
  margin: 0px;
  padding: 0px;
}
.button {
  height:100px;
  width:100px;
  background-color:grey;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.clear {
  height:100px;
  width:400px;
  background-color: red;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.viewer {
  height: 100px;
  width: 430px;
  font-size: 50px;
  margin: 2px
}

<!DOCTYPE html>
<html>

<head>

<script>

</script>

<style>

</style>

</head>

<body>
  <div class= "main">
    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>
    <table>
      <tr>
        <td><input class="button" value="7" onclick= "insert(7)"></td>
        <td><input class="button" value="8" onclick= "insert(8)"></td>
        <td><input class="button" value="9" onclick= "insert(9)"></td>
        <td><input class="button" value="-" onclick= "insert('/')"></td>
      </tr>
      <tr>
        <td><input class="button" value="4" onclick= "insert(4)"></td>
        <td><input class="button" value="5" onclick= "insert(5)"></td>
        <td><input class="button" value="6" onclick= "insert(6)"></td>
        <td><input class="button" value="x" onclick= "insert('*')"></td>
      </tr>
      <tr>
        <td><input class="button" value="1" onclick= "insert(1)"></td>
        <td><input class="button" value="2" onclick= "insert(2)"></td>
        <td><input class="button" value="3" onclick= "insert(3)"></td>
        <td><input class="button" value="-" onclick= "insert('-')"></td>
      </tr>
      <tr>
        <td><input class="button" value="0" onclick= "insert(0)"></td>
        <td><input class="button" value="." onclick= "insert('.')"></td>
        <td><input class="button" value="=" onclick= "equal()"></td>
        <td><input class="button" value="+" onclick= "insert('+')"></td>
      </tr>
    </table>
    <table>
      <tr>
        <td><input class= "clear" value="Clear" onclick= "clearInput()" type="button" /></td>
      </tr>
    </table>
  </div>
</body>

</html>


问:
UITextField's numerical pad: dot instead of comma for float values
I'm using a textField which is filled from a numerical pad.

Trouble is that, with lot of local region formats (all european, for example), UITextField's numerical pad has comma instead dot, so everytime I write a decimal number, UITextField can't recognise the decimal comma and it round number; for example 23,07 become 23.

How can I solve this?
I thought to set the textField fixed on USA; is it possible? How?

I read the value using this:

```<code>var importo = (importoPrevistoTF.text as NSString).floatValue
</code>```

答:
Code working with the current version of Swift:</p>

```<code>let amount = "8,35"

var counter: Int = 0
var noCommaNumber: String!
for var carattere in (amount) {
    if carattere == "," { carattere = "." }
    if counter != 0 { noCommaNumber = "\(noCommaNumber ?? "\(carattere)")" + "\(carattere)" } else { noCommaNumber = "\(carattere)" } // otherwise first record will always be nil
    counter += 1
}

let importo = Float(noCommaNumber)
</code>```

Body:
I'm using a textField which is filled from a numerical pad.

Trouble is that, with lot of local region formats (all european, for example), UITextField's numerical pad has comma instead dot, so everytime I write a decimal number, UITextField can't recognise the decimal comma and it round number; for example 23,07 become 23.

How can I solve this?
I thought to set the textField fixed on USA; is it possible? How?

I read the value using this:

var importo = (importoPrevistoTF.text as NSString).floatValue

Body:
Code working with the current version of Swift:

let amount = "8,35"

var counter: Int = 0
var noCommaNumber: String!
for var carattere in (amount) {
    if carattere == "," { carattere = "." }
    if counter != 0 { noCommaNumber = "\(noCommaNumber ?? "\(carattere)")" + "\(carattere)" } else { noCommaNumber = "\(carattere)" } // otherwise first record will always be nil
    counter += 1
}

let importo = Float(noCommaNumber)


问:
laravel route not found on live server
My laravel  app work in localhost
but when I try to deploy on Shared hosting without ssh
my route app not work, just '/' URL is work but when I call any route it returns
'Not found'
"the request URL/myappName/Middleware/routeName was not found on this server"

and I moved public content to root folder
and changed directory for "vendor and bootstrap"

答:
Kindly read through this:

Make sure the Version of php on the shared hosting is higher or equal to the version of php your laravel is using.

After uploading the files, got to the public folder and move all the files in it to the root directory. then, go to index.php and find the following lines

```<code>require __DIR__.'/../vendor/autoload.php';
and
$app = require_once __DIR__.'/../bootstrap/app.php';
</code>```

modify the by removing /.. from each so that they look like the lines below

```<code>require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
</code>```

Then check the url again.

Title: laravel route not found on live server

Body:
Kindly read through this:

Make sure the Version of php on the shared hosting is higher or equal to the version of php your laravel is using.

After uploading the files, got to the public folder and move all the files in it to the root directory. then, go to index.php and find the following lines

require __DIR__.'/../vendor/autoload.php';
and
$app = require_once __DIR__.'/../bootstrap/app.php';

modify the by removing /.. from each so that they look like the lines below

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';

Then check the url again.


问:
Gradle IntelliJ Idea JavaFX Runtime Error
I wanted to use JavaFX to start doing an interface to my app but I get error:

```<code>java.lang.UnsupportedClassVersionError: org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
> org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
</code>```

Can someone please explain me how to fix it for IntelliJ Idea?

Thank you!

答:
It says that your current version of Java only recognises class file version up to 52.0. This means you have Java 1.8 (version 8) installed on your system.
Simply install Java version 11 to remove the error. Or if you already have Java 11 installed, then check your project's JDK path and make sure that you've configured JDK 11.
 Check this out for step by step solution on Eclipse IDE </p>

Body:
I wanted to use JavaFX to start doing an interface to my app but I get error:

java.lang.UnsupportedClassVersionError: org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
> org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

Can someone please explain me how to fix it for IntelliJ Idea?

Thank you!


问:
How to attach observers to a subject in react?
My App.js looks roughly like this:

```<code><HorizontalNavigation />
<DataPanel />
</code>```

The HorizontalNavigation component contains a Button to export the DataPanel containing charts into a PDF File. This already works fine. Now there is one tiny thing I need to do on the Chart components before I export them.

I am a react beginner, but when I understand correctly a basic solution would be to lift state up to a common ancestor of HorizontalNavigation and DataPanel. That would feel weird as I would have to reach down that state to a lot of intermediate components from DataPanel to the actual charts components. Also they would all be rerendered when this is not necessary at all.

What I had in mind is to use an observable pattern where the PDF export button notifies all charts to do their thing before exporting. How would you design such a pattern in react? The PDF Export button would be my subject to which the charts observers had to attach. But as I don't have a reference to the subject, how do observers attach?

As I'm a react beginner there might be a much more simple solution I don't see yet. So I also appreciate suggestions for other solutions.

答:
What you are looking is state transfer between component. Have a look at below link

https://reactjs.org/docs/hooks-reference.html#usecontext

Body:
My App.js looks roughly like this:

<HorizontalNavigation />
<DataPanel />

The HorizontalNavigation component contains a Button to export the DataPanel containing charts into a PDF File. This already works fine. Now there is one tiny thing I need to do on the Chart components before I export them.

I am a react beginner, but when I understand correctly a basic solution would be to lift state up to a common ancestor of HorizontalNavigation and DataPanel. That would feel weird as I would have to reach down that state to a lot of intermediate components from DataPanel to the actual charts components. Also they would all be rerendered when this is not necessary at all.

What I had in mind is to use an observable pattern where the PDF export button notifies all charts to do their thing before exporting. How would you design such a pattern in react? The PDF Export button would be my subject to which the charts observers had to attach. But as I don't have a reference to the subject, how do observers attach?

As I'm a react beginner there might be a much more simple solution I don't see yet. So I also appreciate suggestions for other solutions.


问:
How do I install expo-cli@3.11.3 on mac
ERROR: Node.js version 8.14.0 is no longer supported.

expo-cli supports following Node.js versions:

=10.13.0 <11.0.0 (Active LTS)

=12.0.0 <13.0.0 (Active LTS)

=13.0.0 <14.0.0 (Current Release)

答: If you are using older versions of node.js, Its hardly impossible to install expo-cli with < node V10. So the trick here is update your node version to a stable one and roll back to the older version that supports your application.</p>

Title: How do I install expo-cli@3.11.3 on mac


问:
Javascript current location in all browser code?
I want to create application to fetch the current location data using Java script.

I want to use this code in any of the browser Firefox,IE,Safari,Chrome,Opera mini along with any version.(1.x,2.x,3.x,.4.x)....

I have tried but it is running with some of the browser and with limited version.

can any body help me out to find out the solution for finding current location using java script for any browser which is compatible .....please share code snippet or any useful link...

thanks,
mishal shah

答: Here is the solution which abstracts from platform http://code.google.com/p/geo-location-javascript/ if you talk about geolocation.</p>


问:
Facing issue in a specfic flutter project while running over my ios device in flutter
Failed to establish a debug connection with 661e647d32d2bf1e57a60abeedda37a0af480e22 using mdns: Invalid argument(s): Cannot find executable for /Users/khattab/Desktop/flutter/bin/cache/artifacts/usbmuxd/iproxy.</p>

答: There is no artifact, so probably build failed. You should check your debug console to see what is the exact problem.</p>


问:
How to get witch values of specific enum passed to a method
I'm trying get which values of specific enum passed to a method and also what the diffrence between | and & operator when passing enums?

Enum:

```<code>enum VectorAxis
{
    X,Y,Z
}
</code>```

Method:

```<code>void SampleMethod(VectorAxis ignoredAxis)
{
// Get witch enums passed
}
</code>```

Caller:

```<code>SampleMethod(VectorAxis.X | VectorAxis.Y);
</code>```

or

```<code>SampleMethod(VectorAxis.X & VectorAxis.Y);
</code>```

答:
First of all, you should apply Flags attribute to your enum. That will indicate that enum can be treated as a set of flags:

```<code>[Flags]
enum VectorAxis
{
    // Consider also adding value None = 0 when no axis ignored
    X = 1,
    Y = 2,
    Z = 4
}
</code>```

Now you can use bitwise operators with enum values:

```<code>SampleMethod(VectorAxis.X | VectorAxis.Y); // pass both axis using bitwise OR
</code>```

How does it work? If you take a look on the binary representation of enum values

```<code>X = 001
Y = 010
Z = 100
</code>```

When you apply bitwise OR operation to X and Y (result has a bit set to 1 if any of values have a bit set to 1 on the same position) you'll get 011. And that's what will be passed to the method. In the method, you can check if the axis were passed using bitwise AND

```<code>public void SampleMethod(VectorAxis ignoredAxis)
{
     if ((ignoredAxis & VectorAxis.X) == VectorAxis.X) // check using bitwise AND
        // X is ignored
}
</code>```

The result of bitwise AND (you have 1 only when both values have a bit set to 1  on same position) of passed value 011 and value of X 001 gives you back value of X only when the corresponding bit is enabled in passed value.

```<code>011 & 001 = 001 // X is ignored
011 & 010 = 010 // Y is ignored
011 & 100 = 000 // Z is not ignored
</code>```

Also instead of checking value manually, you can use Enum.HasFlag method which does the same

```<code>if (ignoredAxis.HasFlag(VectorAxis.X))
</code>```

Body:
I'm trying get which values of specific enum passed to a method and also what the diffrence between | and & operator when passing enums?

Enum:

enum VectorAxis
{
    X,Y,Z
}

Method:

void SampleMethod(VectorAxis ignoredAxis)
{
// Get witch enums passed
}

Caller:

SampleMethod(VectorAxis.X | VectorAxis.Y);

or

SampleMethod(VectorAxis.X & VectorAxis.Y);

Body:
First of all, you should apply Flags attribute to your enum. That will indicate that enum can be treated as a set of flags:

[Flags]
enum VectorAxis
{
    // Consider also adding value None = 0 when no axis ignored
    X = 1,
    Y = 2,
    Z = 4
}

Now you can use bitwise operators with enum values:

SampleMethod(VectorAxis.X | VectorAxis.Y); // pass both axis using bitwise OR

How does it work? If you take a look on the binary representation of enum values

X = 001
Y = 010
Z = 100

When you apply bitwise OR operation to X and Y (result has a bit set to 1 if any of values have a bit set to 1 on the same position) you'll get 011. And that's what will be passed to the method. In the method, you can check if the axis were passed using bitwise AND

public void SampleMethod(VectorAxis ignoredAxis)
{
     if ((ignoredAxis & VectorAxis.X) == VectorAxis.X) // check using bitwise AND
        // X is ignored
}

The result of bitwise AND (you have 1 only when both values have a bit set to 1  on same position) of passed value 011 and value of X 001 gives you back value of X only when the corresponding bit is enabled in passed value.

011 & 001 = 001 // X is ignored
011 & 010 = 010 // Y is ignored
011 & 100 = 000 // Z is not ignored

Also instead of checking value manually, you can use Enum.HasFlag method which does the same

if (ignoredAxis.HasFlag(VectorAxis.X))


问:
Easier management of DOM creation of elements in PHP
I'm trying to find an easier way to create  elements and inserting text values into them.

There has to be an easier way than creating a new variable for each  element, right? Perhaps making a class with some abstraction? Or maybe I'm doing it the wrong way?

At this rate creating 7 s will require me to  create 7 variables, 7 different createTextNodes for each of them and 14 more lines of appendChild().

That will be 28 lines for only 7 s. This seems excessive to me. Not to mention there's more than one
in the table. Is there any way to shorten the amount of lines I can type to create something like:

```<code><table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</code>```

Short example code of what I'm doing:

```<code>$doc = new DOMDocument;

$table = $doc->createElement('table');

        $doc->appendChild($table);

        $tr1 = $doc->createElement('tr');
        $table->appendChild($tr1);

        $td1 = $doc->createElement('td');
        $tr1->appendChild($td1);

        $td1_1 = $doc->createElement('td');
        $tr1->appendChild($td1_1);

        $td1_2 = $doc->createElement('td');
        $tr1->appendChild($td1_2);

        $title1 = $doc->createTextNode('This is title #1');
        $title2 = $doc->createTextNode('This is title #2');
        $title3 = $doc->createTextNode('This is title #3');

        $td1->appendChild($title1);
        $td1_1->appendChild($title2);
        $td1_2->appendChild($title3);

        echo $doc->saveXML();

?>
</code>```

答:
You can add the text to the elements directly:

```<code>$doc->createElement('td', 'This is title #1');
</code>```

Apart from that, there isnt much to shorten in terms of method calls. DOM is a verbose API.

Body:
I'm trying to find an easier way to create  elements and inserting text values into them.

There has to be an easier way than creating a new variable for each  element, right? Perhaps making a class with some abstraction? Or maybe I'm doing it the wrong way?

At this rate creating 7 s will require me to  create 7 variables, 7 different createTextNodes for each of them and 14 more lines of appendChild().

That will be 28 lines for only 7 s. This seems excessive to me. Not to mention there's more than one
in the table. Is there any way to shorten the amount of lines I can type to create something like:

Short example code of what I'm doing:

$doc = new DOMDocument;

$table = $doc->createElement('table');

        $doc->appendChild($table);

        $tr1 = $doc->createElement('tr');
        $table->appendChild($tr1);

        $td1 = $doc->createElement('td');
        $tr1->appendChild($td1);

        $td1_1 = $doc->createElement('td');
        $tr1->appendChild($td1_1);

        $td1_2 = $doc->createElement('td');
        $tr1->appendChild($td1_2);

        $title1 = $doc->createTextNode('This is title #1');
        $title2 = $doc->createTextNode('This is title #2');
        $title3 = $doc->createTextNode('This is title #3');

        $td1->appendChild($title1);
        $td1_1->appendChild($title2);
        $td1_2->appendChild($title3);

        echo $doc->saveXML();

?>

Body:
You can add the text to the elements directly:

$doc->createElement('td', 'This is title #1');

Apart from that, there isnt much to shorten in terms of method calls. DOM is a verbose API.


答:
This is normally done to unify different conditions that are represented by enums. Then, when you use &, you expect that both are satisfied. When using |, one of them is enough.

Given these are bitwise operators, normally values set to the enums are powers of 2, and then you can combine two or more values using the sum of all of them. Check this example:

```<code>public enum Values {
    A = 1,
    B = 2,
    C = 4,
    D = 8,
    B_And_D = 10, // Both B and D applies
    A_B_C_And_D = 15, // All apply
}

public static void Main()
{
    var input = Values.B & Values.B_And_D;
    Console.WriteLine(input); // returns B

    var input2 = Values.B | Values.B_And_D;
    Console.WriteLine(input2); // returns B_And_D

    var input3 = Values.B_And_D & Values.A_B_C_And_D;
    Console.WriteLine(input3); // returns B_And_D

    var input4 = Values.B_And_D | Values.A_B_C_And_D;
    Console.WriteLine(input4); // returns A_B_C_And_D
}
</code>```

Normally you would apply this logic using the Flags attribute, which simplifies much more the logic to combine the conditions (you don't need to add them manually): https://learn.microsoft.com/en/dotnet/api/system.flagsattribute

Title: How to get witch values of specific enum passed to a method

Body:
This is normally done to unify different conditions that are represented by enums. Then, when you use &, you expect that both are satisfied. When using |, one of them is enough.

Given these are bitwise operators, normally values set to the enums are powers of 2, and then you can combine two or more values using the sum of all of them. Check this example:

public enum Values {
    A = 1,
    B = 2,
    C = 4,
    D = 8,
    B_And_D = 10, // Both B and D applies
    A_B_C_And_D = 15, // All apply
}

public static void Main()
{
    var input = Values.B & Values.B_And_D;
    Console.WriteLine(input); // returns B

    var input2 = Values.B | Values.B_And_D;
    Console.WriteLine(input2); // returns B_And_D

    var input3 = Values.B_And_D & Values.A_B_C_And_D;
    Console.WriteLine(input3); // returns B_And_D

    var input4 = Values.B_And_D | Values.A_B_C_And_D;
    Console.WriteLine(input4); // returns A_B_C_And_D
}

Normally you would apply this logic using the Flags attribute, which simplifies much more the logic to combine the conditions (you don't need to add them manually): https://learn.microsoft.com/en/dotnet/api/system.flagsattribute


问:
flutter run -bash: Desktop/flutter/bin/flutter: No such file or directory
flutter doctor

```<code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.17.1, on Mac OS X 10.14.6 18G103, locale pl-PL)
[✗] Android toolchain - develop for Android devices
    ✗ Unable to locate Android SDK.
      Install Android Studio from:
      https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK
      components.
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup
      for detailed instructions).
      If the Android SDK has been installed to a custom location, set
      ANDROID_SDK_ROOT to that location.
      You may also want to add it to your PATH environment variable.

[✓] Xcode - develop for iOS and macOS (Xcode 11.2.1)
[!] Android Studio (not installed)
[!] Connected device
    ! No devices available
</code>```

I created a my_app folder and typed:

```<code>cd my_app
flutter run
</code>```

The "flutter run" command does not work. How to fix this?

答:
I faced this problem it easy to solve

Open Android Studio

And go to preference

Plugins

Download flutter & dart

Body:
flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.17.1, on Mac OS X 10.14.6 18G103, locale pl-PL)
[✗] Android toolchain - develop for Android devices
    ✗ Unable to locate Android SDK.
      Install Android Studio from:
      https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK
      components.
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup
      for detailed instructions).
      If the Android SDK has been installed to a custom location, set
      ANDROID_SDK_ROOT to that location.
      You may also want to add it to your PATH environment variable.

[✓] Xcode - develop for iOS and macOS (Xcode 11.2.1)
[!] Android Studio (not installed)
[!] Connected device
    ! No devices available

I created a my_app folder and typed:

cd my_app
flutter run

The "flutter run" command does not work. How to fix this?


问:
Dynamically adding meta title and description to views in .net core
I am looking for a function to add meta title and description when I enter and call values in view at .net core. I have tried the following code but it did not.How do I include HtmlMeta and Page? Does this code work for me? I am waiting for your help.</p>

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = "Your Page Title";

        HtmlMeta metaDescription = new HtmlMeta();
        metaDescription.Name = "description";
        metaDescription.Content = "Your Page Description";
        Page.Header.Controls.Add(metaDescription);

        HtmlMeta metaKeywords = new HtmlMeta();
        metaKeywords.Name = "keywords";
        metaKeywords.Content = "Your Page Keywords";
        Page.Header.Controls.Add(metaKeywords);
    }
</code>```

答:
In the layout page add new section inside  tags:

...
@await RenderSectionAsync("Header", required: false)

```

<p>Then you can add meta tags to the header section from any view:</p>

<pre class="lang-html prettyprint-override"><code>@section Header {
    <meta name="description" content="@Model.Description"/>
    <meta name="keywords" content="Model.KeyWords"/>
}
</code>```

In your page model you can provide the values for Description and KeyWords then pass it to the view.

Body:
I am looking for a function to add meta title and description when I enter and call values in view at .net core. I have tried the following code but it did not.How do I include HtmlMeta and Page? Does this code work for me? I am waiting for your help.

protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = "Your Page Title";

        HtmlMeta metaDescription = new HtmlMeta();
        metaDescription.Name = "description";
        metaDescription.Content = "Your Page Description";
        Page.Header.Controls.Add(metaDescription);

        HtmlMeta metaKeywords = new HtmlMeta();
        metaKeywords.Name = "keywords";
        metaKeywords.Content = "Your Page Keywords";
        Page.Header.Controls.Add(metaKeywords);
    }

Body:
In the layout page add new section inside <head> tags:

<head>
...
@await RenderSectionAsync("Header", required: false)
</head>

Then you can add meta tags to the header section from any view:

@section Header {
    <meta name="description" content="@Model.Description"/>
    <meta name="keywords" content="Model.KeyWords"/>
}

In your page model you can provide the values for Description and KeyWords then pass it to the view.


问:
Extracting the elements from the consecutive pattern in the dataframe vector
I have a dataframe of more than 30,000 values as follows

```<code>1   qw
2   as
3   we
4   er
5   rt
6   @@@@
7   @@@@
8   @@@@
9   @@@@
10  as
11  df
12  fg
13  gh
14  hj
</code>```

I want to extract the values at location index 1,3,5,10,12,14,19,21,23 and so on. As a beginner I know extraction of value using seq(first, last, by=) but I am not able to do slicing as per the above pattern.

```<code>1   qw
3   we
5   rt
10  as
12  fg
14  hj
</code>```

答:
Having something nested like this would work for you:

```<code>> rep(seq(1, 5, 2), 3) + rep(seq(0, 18, 9), each = 3)
[1]  1  3  5 10 12 14 19 21 23
</code>```

For more values:

```<code>nMax <- 30000

seq1 <- seq(1, 5, 2)
seq2 <- rep(seq(0, nMax, 9))

rep(seq1, length(seq2)) + rep(seq2, each = 3)
</code>```

Body:
I have a dataframe of more than 30,000 values as follows

1   qw
2   as
3   we
4   er
5   rt
6   @@@@
7   @@@@
8   @@@@
9   @@@@
10  as
11  df
12  fg
13  gh
14  hj

I want to extract the values at location index 1,3,5,10,12,14,19,21,23 and so on. As a beginner I know extraction of value using seq(first, last, by=) but I am not able to do slicing as per the above pattern.

1   qw
3   we
5   rt
10  as
12  fg
14  hj

Body:
Having something nested like this would work for you:

> rep(seq(1, 5, 2), 3) + rep(seq(0, 18, 9), each = 3)
[1]  1  3  5 10 12 14 19 21 23

For more values:

nMax <- 30000

seq1 <- seq(1, 5, 2)
seq2 <- rep(seq(0, nMax, 9))

rep(seq1, length(seq2)) + rep(seq2, each = 3)


问:
How to use bcp utility with oracle dB or any other better options
I have a csv file which has to be bulk imported to oracle dB. I was working on other sybase dB engine before so I had a sample script which has the environment setup for it. Right now I have to do the process in a oracle dB so what should be the first line I know about the rest other parameters but want to know the path which has to be defined when I write
path/bcp dbtable in data.txt
If anyone could help what should be the path for oracle dB

答:
The primary tools for bulk or flat file loading are:

SQL*Loader

External Tables (and here)

GUI Tools like SQL*Developer

It is much more cumbersome, but if necessary you can roll your own solution with the UTL_FILE PL/SQL package.


问:
How do I compare elements of an array with a string powershell
I am new to Powershell and I have a question.

```<code>$status = @(qlist job -jt backup -co s)
Write-Host $status[3]
$status[3] -ceq "Suspended"
</code>```

The answer is

```<code> Suspended
False
</code>```

My question is: Why is this comparison false?

答:
Looks like you have an extra space in $status[3]

```<code>" Suspended" -eq "Suspended"
False
</code>```

you may try:

```<code>" Suspended" -like "*Suspended*"
True
</code>```

Parameter -ceq means case sensitive equal, so use only if really needed.
Equivalent for case sensitivity like is -clike

P.S. Also another option would be to use the trim method, which will remove the empty spaces: $status[3].trim() -eq "Suspended"

Body:
I am new to Powershell and I have a question.

$status = @(qlist job -jt backup -co s)
Write-Host $status[3]
$status[3] -ceq "Suspended"

The answer is

 Suspended
False

My question is: Why is this comparison false?

Body:
Looks like you have an extra space in $status[3]

" Suspended" -eq "Suspended"
False

you may try:

" Suspended" -like "*Suspended*"
True

Parameter -ceq means case sensitive equal, so use only if really needed.
Equivalent for case sensitivity like is -clike

P.S. Also another option would be to use the trim method, which will remove the empty spaces: $status[3].trim() -eq "Suspended"