问:
How do I enable slowmode via a command?
I want to enable slowmode via a command, in the form as >slowmode <seconds>, like >slowmode 10. My current code:

```<code> @has_permissions(manage_channels=True)
 async def slowmode(ctx, amount):
    await ctx.channel.edit.slowmode.delay(int(amount))
</code>```

and I get this error:

```<code>Ignoring exception in command slowmode:
Traceback (most recent call last):
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\dante\Desktop\Utilly\Utilly.py", line 116, in slowmode
    await ctx.channel.edit.slowmode.delay(int(amount))
AttributeError: 'function' object has no attribute 'slowmode'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'slowmode'
</code>```

答:
Use discord.TextChannel.edit(slowmode_delay=amount)

@has_permissions(manage_channels=True)
async def slowmode(ctx, amount):
    try:
        await ctx.channel.edit(reason='Bot Slowmode Command', slowmode_delay=int(amount))
    except discord.Errors.Forbidden:
        await ctx.send('I do not have the permission to do this, please try again')
```

Title: How do I enable slowmode via a command?

Body:
I want to enable slowmode via a command, in the form as >slowmode <seconds>, like >slowmode 10. My current code:

 @has_permissions(manage_channels=True)
 async def slowmode(ctx, amount):
    await ctx.channel.edit.slowmode.delay(int(amount))

and I get this error:

Ignoring exception in command slowmode:
Traceback (most recent call last):
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\dante\Desktop\Utilly\Utilly.py", line 116, in slowmode
    await ctx.channel.edit.slowmode.delay(int(amount))
AttributeError: 'function' object has no attribute 'slowmode'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\dante\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'slowmode'


来源: stackexchange

问:
Using ping in c#
When I Ping a remote system with windows it says there is no reply, but when I ping with c# it says success. Windows is correct, the device is not connected. Why is my code able to successfully ping when Windows is not?

Here is my code :

```<code>Ping p1 = new Ping();
PingReply PR = p1.Send("192.168.2.18");
// check when the ping is not success
while (!PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}
// check after the ping is n success
while (PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}
</code>```

答:
```<code>Imports System.Net.NetworkInformation

Public Function PingHost(ByVal nameOrAddress As String) As Boolean
    Dim pingable As Boolean = False
    Dim pinger As Ping
    Dim lPingReply As PingReply

    Try
        pinger = New Ping()
        lPingReply = pinger.Send(nameOrAddress)
        MessageBox.Show(lPingReply.Status)
        If lPingReply.Status = IPStatus.Success Then

            pingable = True
        Else
            pingable = False
        End If

    Catch PingException As Exception
        pingable = False
    End Try
    Return pingable
End Function
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using ping in c#

Body:
When I Ping a remote system with windows it says there is no reply, but when I ping with c# it says success. Windows is correct, the device is not connected. Why is my code able to successfully ping when Windows is not?

Here is my code :

Ping p1 = new Ping();
PingReply PR = p1.Send("192.168.2.18");
// check when the ping is not success
while (!PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}
// check after the ping is n success
while (PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}

ContentLicense: CC BY-SA 4.0


问:
filter object of objects dynamic key value
how can i filter object of objects with dynamic key value in javaScript or lodash.

my data is :

```<code>var names = [
  {
    name: 'c1',
    tags: {
      key1: 'value1-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c2',
    tags: {
      key1: 'value2-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c3',
    tags: {
      key3: 'value3-1',
      key4: 'value3-2',
    },
  }
]
</code>```

and filter data is:

```<code>var filterData = {
  key3: { 0: 'value3-1' },
  key4: { 0: 'value3-2' }
}
</code>```

and i expect filter and after filter show like this:

```<code>afterFilter = [
      {
        name: 'c3',
        tags: {
          key3: 'value3-1',
          key4: 'value3-2',
        }
      }
    ]
</code>```

答:
first console.log segment:

- filter contains keys/vals in tags

second console.log segment:

- exact same set of key/vals (also checks they are same length)

var names = [{
    name: 'c1',
    tags: {
      key1: 'value1-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c2',
    tags: {
      key1: 'value2-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c3',
    tags: {
      key3: 'value3-1',
      key4: 'value3-2',
    },
  }
]
var filterData = {
  key3: 'value3-1',
  key4: 'value3-2'
}

names.push({
  name: 'c4',
  tags: {
    key1: 'pew',
    key2: 'pew pew',
    key4: 'value3-2',
    key3: 'value3-1'
  }
})

// filter for if _contains_ key/values of filterData
console.log(
  names.filter(({
    tags
  }) => Object.entries(filterData).every(([k, v]) => tags[k] === v))
)

// filter for only exact same key/values of filterData order-insensitive
const count = Object.keys(filterData).length
console.log(
  names.filter(
    ({
      tags
    }) =>
    (tags =>
      tags.length === count && tags.every(([k, v]) => filterData[k] === v))
    (Object.entries(tags))
  )
)```

Body:
how can i filter object of objects with dynamic key value in javaScript or lodash.

my data is :

var names = [
  {
    name: 'c1',
    tags: {
      key1: 'value1-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c2',
    tags: {
      key1: 'value2-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c3',
    tags: {
      key3: 'value3-1',
      key4: 'value3-2',
    },
  }
]

and filter data is:

var filterData = {
  key3: { 0: 'value3-1' },
  key4: { 0: 'value3-2' }
}

and i expect filter and after filter show like this:

afterFilter = [
      {
        name: 'c3',
        tags: {
          key3: 'value3-1',
          key4: 'value3-2',
        }
      }
    ]


问:
Save Unbound Values in a Form with an Append Query
I want to be able to store the values in a list of controls from a form in a table using an Append query in VBA. Here is what I have so far.</p>

```<code>Private Sub btnSave()

Dim ctl As Control
Dim str As String
Dim RecordInsertSQL As String
str = Empty

For each ctl In Me.Controls
    If TypeOf ctl Is Textbox or TypeOf ctl is Combobox or TypeOf ctl Is Listbox Then
    Debug.Print ctl.Name
    Else:
    End If
Next ctl

RecordInsertSQL = INSERT INTO tbl_Save ([ctl.Name1], [ctl.Name2]) VALUES ('" & Me.ctl.Name1.Value & "','" & Me.ctl.Name2.Value & "');"

DoCmd.RunSQL RecordInsertSQL
MsgBox("Your data has been saved")

End Sub
</code>```

答:
The normal way of using VBA to do an insert into a table from controls on a form is to actually name the control and the field that the data is going into, as:

Dates and strings require wrapping in delimiters (octothorpes and single quotes respectively);

You may need to handle null values, and convert them to either 0 or a zero-length string;

If other controls are added to the form, then your code may either stop working, or else the wrong value may get inserted into the field.

Your SQL would therefore look like (assuming both fields are text):

```<code>RecordInsertSQL="INSERT INTO [tbl_Save] (Field1, Field2) VALUES ('" & cboField1 & "','" & cboField2 & "');"
</code>```

Regards,

Body:
I want to be able to store the values in a list of controls from a form in a table using an Append query in VBA. Here is what I have so far.

Private Sub btnSave()

Dim ctl As Control
Dim str As String
Dim RecordInsertSQL As String
str = Empty

For each ctl In Me.Controls
    If TypeOf ctl Is Textbox or TypeOf ctl is Combobox or TypeOf ctl Is Listbox Then
    Debug.Print ctl.Name
    Else:
    End If
Next ctl

RecordInsertSQL = INSERT INTO tbl_Save ([ctl.Name1], [ctl.Name2]) VALUES ('" & Me.ctl.Name1.Value & "','" & Me.ctl.Name2.Value & "');"

DoCmd.RunSQL RecordInsertSQL
MsgBox("Your data has been saved")

End Sub

Body:
The normal way of using VBA to do an insert into a table from controls on a form is to actually name the control and the field that the data is going into, as:

Dates and strings require wrapping in delimiters (octothorpes and single quotes respectively);

You may need to handle null values, and convert them to either 0 or a zero-length string;

If other controls are added to the form, then your code may either stop working, or else the wrong value may get inserted into the field.

Your SQL would therefore look like (assuming both fields are text):

RecordInsertSQL="INSERT INTO [tbl_Save] (Field1, Field2) VALUES ('" & cboField1 & "','" & cboField2 & "');"

Regards,


问:
How to create Binding Adapter for material.Slider view?
My goal is to 2-way databind material.Slider view to MutableLiveData from my viewmodel:

```<code>   <com.google.android.material.slider.Slider
        ...
        android:value="@={viewmodel.fps}"
        ...
    />
</code>```

Of course, it's not working because there is no databinding adapter for Slider in androidx.databinding library

```<code>[databinding] Cannot find a getter for <com.google.android.material.slider.Slider android:value> that accepts parameter type <java.lang.Integer>. If a binding adapter provides the getter, check that the adapter is annotated correctly and that the parameter type matches.
</code>```

But, they have one for SeekBar: /androidx/databinding/adapters/SeekBarBindingAdapter.java

As I understand, 2-way databinding should work only with "progress" attribute, and 1-way databinding requires two attributes: "onChanged" and "progress"

I made a try to adapt SeekBarBindingAdapter for Slider:

```<code>    @InverseBindingMethods({
            @InverseBindingMethod(type = Slider.class, attribute = "android:value"),
    })
    public class SliderBindingAdapter {
        @BindingAdapter("android:value")
        public static void setValue(Slider view, int value) {
            if (value != view.getValue()) {
                view.setValue(value);
            }
        }

@BindingAdapter(value = {"android:valueAttrChanged", "android:onValueChange"}, requireAll = false)
    public static void setOnSliderChangeListener(Slider view, final Slider.OnChangeListener valChanged, final InverseBindingListener attrChanged) {
        if (valChanged == null)
            view.addOnChangeListener(null);
        else
            view.addOnChangeListener((slider, value, fromUser) -> {
                if (valChanged != null)
                    valChanged.onValueChange(slider, value, fromUser);
            });

        if (attrChanged != null) {
            attrChanged.onChange();
        }
    }

    @Override
    public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) {

    }
</code>```

It's not building:

```<code>Could not find event android:valueAttrChanged on View type Slider
</code>```

but why it looks for valueAttrChanged if I only use

```<code>android:value="@={viewmodel.fps}"
</code>```

?

How do I find the right attribute to add to BindingAdapter, if I don't see valueAttrChanged in Slider class?

答:
Let's look at SeekBarBindingAdapter's setOnSeekBarChangeListener() method. It adds four different attributes: {"android:onStartTrackingTouch", "android:onStopTrackingTouch", "android:onProgressChanged", "android:progressAttrChanged"} but only the last one is used by two-way databinding.

But why there are four attributes? If you look at SeekBar class, it has setOnSeekBarChangeListener() method which allows you to set and remove a listener. The problem is that SeekBar can only have one listener, and that listener provides different callbacks: onProgressChanged, onStartTrackingTouch and onStopTrackingTouch.

SeekBarBindingAdapter registers its own listener which means that no one can register another listener without removing the existing one. It's why SeekBarBindingAdapter provides onStartTrackingTouch, onStopTrackingTouch and onProgressChanged attributes, so you can listen to these events without registering your own OnSeekBarChangeListener.

Actually the Slider adapter can be much simpler than SeekBarBindingAdapter, because the Slider allows you to add and remove listeners using addOnChangeListener() and removeOnChangeListener(). So a two-way databinding adapter can register its own listener and anyone else can register other listeners without removing previous ones.

It allows us to define a pretty concise adapter. I created a kotlin example, hope you can translate it to java:

@InverseBindingAdapter(attribute = "android:value")
fun getSliderValue(slider: Slider) = slider.value

@BindingAdapter("android:valueAttrChanged")
fun setSliderListeners(slider: Slider, attrChange: InverseBindingListener) {
    slider.addOnChangeListener { _, _, _ ->
        attrChange.onChange()
    }
}
```

<p>And the layout:</p>

<pre class="lang-xml prettyprint-override"><code>...
<com.google.android.material.slider.Slider
    ...
    android:value="@={model.count}" />
...
</code>```

You can find the full sources here.

Body:
My goal is to 2-way databind material.Slider view to MutableLiveData from my viewmodel:

   <com.google.android.material.slider.Slider
        ...
        android:value="@={viewmodel.fps}"
        ...
    />

Of course, it's not working because there is no databinding adapter for Slider in androidx.databinding library

[databinding] Cannot find a getter for <com.google.android.material.slider.Slider android:value> that accepts parameter type <java.lang.Integer>. If a binding adapter provides the getter, check that the adapter is annotated correctly and that the parameter type matches.

But, they have one for SeekBar: /androidx/databinding/adapters/SeekBarBindingAdapter.java

As I understand, 2-way databinding should work only with "progress" attribute, and 1-way databinding requires two attributes: "onChanged" and "progress"

I made a try to adapt SeekBarBindingAdapter for Slider:

    @InverseBindingMethods({
            @InverseBindingMethod(type = Slider.class, attribute = "android:value"),
    })
    public class SliderBindingAdapter {
        @BindingAdapter("android:value")
        public static void setValue(Slider view, int value) {
            if (value != view.getValue()) {
                view.setValue(value);
            }
        }

@BindingAdapter(value = {"android:valueAttrChanged", "android:onValueChange"}, requireAll = false)
    public static void setOnSliderChangeListener(Slider view, final Slider.OnChangeListener valChanged, final InverseBindingListener attrChanged) {
        if (valChanged == null)
            view.addOnChangeListener(null);
        else
            view.addOnChangeListener((slider, value, fromUser) -> {
                if (valChanged != null)
                    valChanged.onValueChange(slider, value, fromUser);
            });

        if (attrChanged != null) {
            attrChanged.onChange();
        }
    }

    @Override
    public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) {

    }

It's not building:

Could not find event android:valueAttrChanged on View type Slider

but why it looks for valueAttrChanged if I only use

android:value="@={viewmodel.fps}"

?

How do I find the right attribute to add to BindingAdapter, if I don't see valueAttrChanged in Slider class?

Body:
Let's look at SeekBarBindingAdapter's setOnSeekBarChangeListener() method. It adds four different attributes: {"android:onStartTrackingTouch", "android:onStopTrackingTouch", "android:onProgressChanged", "android:progressAttrChanged"} but only the last one is used by two-way databinding.

But why there are four attributes? If you look at SeekBar class, it has setOnSeekBarChangeListener() method which allows you to set and remove a listener. The problem is that SeekBar can only have one listener, and that listener provides different callbacks: onProgressChanged, onStartTrackingTouch and onStopTrackingTouch.

SeekBarBindingAdapter registers its own listener which means that no one can register another listener without removing the existing one. It's why SeekBarBindingAdapter provides onStartTrackingTouch, onStopTrackingTouch and onProgressChanged attributes, so you can listen to these events without registering your own OnSeekBarChangeListener.

Actually the Slider adapter can be much simpler than SeekBarBindingAdapter, because the Slider allows you to add and remove listeners using addOnChangeListener() and removeOnChangeListener(). So a two-way databinding adapter can register its own listener and anyone else can register other listeners without removing previous ones.

It allows us to define a pretty concise adapter. I created a kotlin example, hope you can translate it to java:

@InverseBindingAdapter(attribute = "android:value")
fun getSliderValue(slider: Slider) = slider.value

@BindingAdapter("android:valueAttrChanged")
fun setSliderListeners(slider: Slider, attrChange: InverseBindingListener) {
    slider.addOnChangeListener { _, _, _ ->
        attrChange.onChange()
    }
}

And the layout:

...
<com.google.android.material.slider.Slider
    ...
    android:value="@={model.count}" />
...

You can find the full sources here.


问:
How to check if any application is running in docker container?
How to check if any application is running in docker container ? What is the command for it.</p>

答:
Maybe this?</p>

```<code>// Access your container
docker exec -it <name of your container> bash

// List running processes in your container
ps
</code>```

Body:
Maybe this?

// Access your container
docker exec -it <name of your container> bash

// List running processes in your container
ps


问:
how to turn text into a dictionary list
I have a text with the content shown below.
This is a string.

```<code>{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}
</code>```

If possible, I would like someone to help me build a list of dictionaries with this information.
It looks like this:

```<code>list = [{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}]
</code>```

Best wishes!

答:
Very simple with ast module, use literal_eval:

```<code>import ast

>>> astr = "{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}"
>>> list(ast.literal_eval(astr))
[{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}]
</code>```

Title: how to turn text into a dictionary list

Body:
I have a text with the content shown below.
This is a string.

{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}

If possible, I would like someone to help me build a list of dictionaries with this information.
It looks like this:

list = [{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}]

Best wishes!

Body:
Very simple with ast module, use literal_eval:

import ast

>>> astr = "{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}"
>>> list(ast.literal_eval(astr))
[{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}]


答:
This is an interesting problem. I would like to mention a couple of points here.

Here we need to get the max and second max value for price column "so    far".

"so far" mean we need to use all the data till given point and partitioning is not required.

In order to specify the unbounded window specification for start of the window we will use "Window.unboundedPreceding".

We will use rowsBetween function to specify the window from beginnning to current row.

// Lets create a sample DataFrame

```<code>// Lets create a sample DataFrame
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val df = Seq((1, 31951.509, 0.370, 1, 1),
              (2, 31951.515, 145.380, 100,100),
              (3, 31951.519, 149.370, 100, 100),
              (4, 31951.520, 144.370, 100, 100),
              (5, 31951.520, 149.370, 300, 200),
              (6, 31951.520, 119.370, 5, 5))
        .toDF("id", "tim", "price", "qty", "qtyChg")
        .orderBy("id")

// Define the window specification which starts from beginning (specified by "Window.unboundedPreceding") and and end at current row (specified by value 0).
val winSpec = Window.orderBy("tim").rowsBetween(Window.unboundedPreceding, 0)

// Collect all the values and sort them in descending order.
val df1 = df.withColumn("sort_array", sort_array(collect_list(struct("price", "qty")).over(winSpec), asc=false))

// Fectch the elements at position 1 and 2 which represent the max and second max value.

val df2 = df1//.withColumn("top1price", element_at(sort_array(array_distinct($"sort_array.price"), asc=false), 1))
             //.withColumn("top2price", element_at(sort_array(array_distinct($"sort_array.price"), asc=false), 2))
             .withColumn("top1price", element_at(array_distinct($"sort_array.price"), 1))
             .withColumn("top2price", element_at(array_distinct($"sort_array.price"), 2))
             .withColumn("top1priceQty", element_at($"sort_array.qty", 1))
             .withColumn("top2priceQty", element_at($"sort_array.qty", 2))
             .drop("sort_array")

// Display the result.
df2.show(truncate= false)
</code>```

```<code> // Output
</code>```

```<code>+---+---------+------+---+------+---------+---------+------------+------------+
|id |tim      |price |qty|qtyChg|top1price|top2price|top1priceQty|top2priceQty|
+---+---------+------+---+------+---------+---------+------------+------------+
|1  |31951.509|0.37  |1  |1     |0.37     |null     |1           |null        |
|2  |31951.515|145.38|100|100   |145.38   |0.37     |100         |1           |
|3  |31951.519|149.37|100|100   |149.37   |145.38   |100         |100         |
|4  |31951.52 |144.37|100|100   |149.37   |145.38   |100         |100         |
|5  |31951.52 |149.37|300|200   |149.37   |145.38   |300         |100         |
|6  |31951.52 |119.37|5  |5     |149.37   |145.38   |300         |100         |
+---+---------+------+---+------+---------+---------+------------+------------+
</code>```

I hope this helps.

Title: Scala Spark DataFrame Question:How to add new columns by matching the value in current row to somewhere from previous rows

Body:
I need help with Spark Dataframe.

The original dataframe df looks like this:

+---+---------+-------+---+------+
| id|      tim|  price|qty|qtyChg|
+---+---------+-------+---+------+
|  1|31951.509|  0.370|  1|     1|
|  2|31951.515|145.380|100|   100|
|  3|31951.519|149.370|100|   100|
|  4|31951.520|144.370|100|   100|
|  5|31951.520|149.370|300|   200|
|  6|31951.520|119.370|  5|     5|
|  7|31951.521|149.370|400|   100|
|  8|31951.522|109.370| 50|    50|
|  9|31951.522|149.370|410|    10|
| 10|31951.522|144.370|400|   300|
| 11|31951.522|149.870| 50|    50|
| 12|31951.524|149.370|610|   200|
| 13|31951.526|135.130| 22|    22|
| 14|31951.527|149.370|750|   140|
| 15|31951.528| 89.370|100|   100|
| 16|31951.528|145.870| 50|    50|
| 17|31951.528|139.370|100|   100|
| 18|31951.531|149.370|769|    19|
| 19|31951.531|144.370|410|    10|
| 20|31951.538|149.370|869|   100|
+---+---------+-------+---+------+

I am adding two columns top1price and top2priceby code

val ww = Window.partitionBy().orderBy($"tim")
val newdf = df.withColumn("sequence",sort_array(collect_set(col("price")).over(ww),asc=false))
                .withColumn("top1price",col("sequence").getItem(0))
                .withColumn("top2price",col("sequence").getItem(1)).drop("sequence")

newdf looks like this:

+---+---------+-------+---+------+---------+---------+
| id|      tim|  price|qty|qtyChg|top1price|top2price|
+---+---------+-------+---+------+---------+---------+
|  1|31951.509|  0.370|  1|     1|    0.370|     null|
|  2|31951.515|145.380|100|   100|  145.380|    0.370|
|  3|31951.519|149.370|100|   100|  149.370|  145.380|
|  4|31951.520|119.370|  5|     5|  149.370|  145.380|
|  5|31951.520|144.370|100|   100|  149.370|  145.380|
|  6|31951.520|149.370|300|   200|  149.370|  145.380|
|  7|31951.521|149.370|400|   100|  149.370|  145.380|
|  8|31951.522|109.370| 50|    50|  149.870|  149.370|
|  9|31951.522|144.370|400|   300|  149.870|  149.370|
| 10|31951.522|149.370|410|    10|  149.870|  149.370|
| 11|31951.522|149.870| 50|    50|  149.870|  149.370|
| 12|31951.524|149.370|610|   200|  149.870|  149.370|
| 13|31951.526|135.130| 22|    22|  149.870|  149.370|
| 14|31951.527|149.370|750|   140|  149.870|  149.370|
| 15|31951.528| 89.370|100|   100|  149.870|  149.370|
| 16|31951.528|139.370|100|   100|  149.870|  149.370|
| 17|31951.528|145.870| 50|    50|  149.870|  149.370|
| 18|31951.531|144.370|410|    10|  149.870|  149.370|
| 19|31951.531|149.370|769|    19|  149.870|  149.370|
| 20|31951.538|144.880|200|   200|  149.870|  149.370|
+---+---------+-------+---+------+---------+---------+

The logic behind top1price is what is the highest price so far at every moment. For example, at time 31951.520 (id = 6), the highest price by that time is 149.370 which comes from row id=6. The second-highest price by that time is 145.38 which comes from row2. I am interested in add two more columns top1priceQty and top2priceQty. The same example, in row 6, the highest price is 149.370 and its corresponding qty is 300 which also comes from row 6. The top2price is 145.380 and its top2priceQty would 100 which also comes from row2.

 |  8|31951.522|109.370| 50|    50|  149.870|  149.370|

For row8, top1price is 149.870 which comes from row 11 because row 8 to row 11 are the same moment. So by that time, 149.870 is the highest price and its corresponding top1priceQty would be 50. top2price is 149.370 which comes from row7, so is corresponding top2priceQty is 400 which also comes from row 7.

Thank you in advance!

Body:
This is an interesting problem. I would like to mention a couple of points here.

Here we need to get the max and second max value for price column "so    far".

"so far" mean we need to use all the data till given point and partitioning is not required.

In order to specify the unbounded window specification for start of the window we will use "Window.unboundedPreceding".

We will use rowsBetween function to specify the window from beginnning to current row.

// Lets create a sample DataFrame

// Lets create a sample DataFrame
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val df = Seq((1, 31951.509, 0.370, 1, 1),
              (2, 31951.515, 145.380, 100,100),
              (3, 31951.519, 149.370, 100, 100),
              (4, 31951.520, 144.370, 100, 100),
              (5, 31951.520, 149.370, 300, 200),
              (6, 31951.520, 119.370, 5, 5))
        .toDF("id", "tim", "price", "qty", "qtyChg")
        .orderBy("id")

// Define the window specification which starts from beginning (specified by "Window.unboundedPreceding") and and end at current row (specified by value 0).
val winSpec = Window.orderBy("tim").rowsBetween(Window.unboundedPreceding, 0)

// Collect all the values and sort them in descending order.
val df1 = df.withColumn("sort_array", sort_array(collect_list(struct("price", "qty")).over(winSpec), asc=false))

// Fectch the elements at position 1 and 2 which represent the max and second max value.

val df2 = df1//.withColumn("top1price", element_at(sort_array(array_distinct($"sort_array.price"), asc=false), 1))
             //.withColumn("top2price", element_at(sort_array(array_distinct($"sort_array.price"), asc=false), 2))
             .withColumn("top1price", element_at(array_distinct($"sort_array.price"), 1))
             .withColumn("top2price", element_at(array_distinct($"sort_array.price"), 2))
             .withColumn("top1priceQty", element_at($"sort_array.qty", 1))
             .withColumn("top2priceQty", element_at($"sort_array.qty", 2))
             .drop("sort_array")

// Display the result.
df2.show(truncate= false)

 // Output

+---+---------+------+---+------+---------+---------+------------+------------+
|id |tim      |price |qty|qtyChg|top1price|top2price|top1priceQty|top2priceQty|
+---+---------+------+---+------+---------+---------+------------+------------+
|1  |31951.509|0.37  |1  |1     |0.37     |null     |1           |null        |
|2  |31951.515|145.38|100|100   |145.38   |0.37     |100         |1           |
|3  |31951.519|149.37|100|100   |149.37   |145.38   |100         |100         |
|4  |31951.52 |144.37|100|100   |149.37   |145.38   |100         |100         |
|5  |31951.52 |149.37|300|200   |149.37   |145.38   |300         |100         |
|6  |31951.52 |119.37|5  |5     |149.37   |145.38   |300         |100         |
+---+---------+------+---+------+---------+---------+------------+------------+

I hope this helps.


问:
mock instance is null after @Mock annotation
I try to run this test:

```<code>    @Mock IRoutingObjHttpClient routingClientMock;
    @Mock IRoutingResponseRepository routingResponseRepositoryMock;

    @Test
    public void testSendRoutingRequest() throws Exception {
        CompleteRoutingResponse completeRoutingResponse = new CompleteRoutingResponse();
        completeRoutingResponse.regression_latencyMillis = 500L;

        Mockito.when(routingClientMock.sendRoutingRequest(any(RoutingRequest.class))).thenReturn(completeRoutingResponse);

        RoutingObjHttpClientWithReRun routingObjHttpClientWithReRun = new RoutingObjHttpClientWithReRun
                (routingClientMock, routingResponseRepositoryMock);

...
    }
</code>```

but I get NullPointerException for:

Mockito.when(routingClientMock.

what am i missing?

答:
For me, even after adding @RunWith(MockitoJUnitRunner.class) it was not working.

Turned out, I had made the silly mistake of importing @Test from

import org.junit.jupiter.api.Test;
```

<p>instead of </p>

```import org.junit.Test;
```

After correcting it, it worked!

Body:
I try to run this test:

    @Mock IRoutingObjHttpClient routingClientMock;
    @Mock IRoutingResponseRepository routingResponseRepositoryMock;

    @Test
    public void testSendRoutingRequest() throws Exception {
        CompleteRoutingResponse completeRoutingResponse = new CompleteRoutingResponse();
        completeRoutingResponse.regression_latencyMillis = 500L;

        Mockito.when(routingClientMock.sendRoutingRequest(any(RoutingRequest.class))).thenReturn(completeRoutingResponse);

        RoutingObjHttpClientWithReRun routingObjHttpClientWithReRun = new RoutingObjHttpClientWithReRun
                (routingClientMock, routingResponseRepositoryMock);

...
    }

but I get NullPointerException for:

Mockito.when(routingClientMock.

what am i missing?

Body:
For me, even after adding @RunWith(MockitoJUnitRunner.class) it was not working.

Turned out, I had made the silly mistake of importing @Test from

import org.junit.jupiter.api.Test;

instead of

import org.junit.Test;

After correcting it, it worked!


问:
Retrieve characters from a string
What is the best way to get a list of characters [a-z] from a string ignoring any other special character or number?</p>

答:
You could use a regular expression:

```<code>String lettersOnly = original.replaceAll("[^a-z]", "");
</code>```

or

```<code>String lettersOnly = original.replaceAll("[^a-zA-Z]", "");
</code>```

While you can use Unicode groups too, I personally find it easier to recognise and understand a simple set such as a-z or a-zA-Z - it means I don't need to look up whether it will include non-ASCII characters :)

Title: Retrieve characters from a string

Body:
You could use a regular expression:

String lettersOnly = original.replaceAll("[^a-z]", "");

or

String lettersOnly = original.replaceAll("[^a-zA-Z]", "");

While you can use Unicode groups too, I personally find it easier to recognise and understand a simple set such as a-z or a-zA-Z - it means I don't need to look up whether it will include non-ASCII characters :)


问:
Extra Plot when drawing Catplot
Using the following code:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df1 = pd.DataFrame( {'category': {0: 'Cat', 1: 'Cat', 2: 'Cat', 3: 'Cat', 4: 'Dog', 5: 'Dog', 6: 'Dog', 7: 'Dog', 8: 'Dog', 9: 'Dog', 10: 'Dog', 11: 'Dog', 12: 'Dog', 13: 'Dog', 14: 'Dog', 15: 'Dog', 16: 'Dog', 17: 'Dog', 18: 'Dog', 19: 'Dog'}, 'shape': {0: 'Small', 1: 'Small', 2: 'Small', 3: 'Small', 4: 'Small', 5: 'Small', 6: 'Small', 7: 'Medium', 8: 'Medium', 9: 'Large', 10: 'Small', 11: 'Small', 12: 'Small', 13: 'Small', 14: 'Small', 15: 'Small', 16: 'Small', 17: 'Small', 18: 'Small', 19: 'Small'}} )
plt.figure(figsize=(5,5),facecolor='#ffffff')
ax = plt.axes(facecolor='#ffffff')
plt.xticks(rotation=25)
sns.catplot(x='shape', hue='category', kind ='count', data = df1, height=5, aspect=1,ax=ax)
plt.xlabel('Diamond Shape')
plt.show()
</code>```

I got the following plot

Why there is an extra blank plot below? How to not generate that?
(I need the ax to provide extra formatting for catplot)

答:
You can use the following trick : Close the extra figure before plt.show()

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

Title: Extra Plot when drawing Catplot

Body:
Using the following code:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df1 = pd.DataFrame( {'category': {0: 'Cat', 1: 'Cat', 2: 'Cat', 3: 'Cat', 4: 'Dog', 5: 'Dog', 6: 'Dog', 7: 'Dog', 8: 'Dog', 9: 'Dog', 10: 'Dog', 11: 'Dog', 12: 'Dog', 13: 'Dog', 14: 'Dog', 15: 'Dog', 16: 'Dog', 17: 'Dog', 18: 'Dog', 19: 'Dog'}, 'shape': {0: 'Small', 1: 'Small', 2: 'Small', 3: 'Small', 4: 'Small', 5: 'Small', 6: 'Small', 7: 'Medium', 8: 'Medium', 9: 'Large', 10: 'Small', 11: 'Small', 12: 'Small', 13: 'Small', 14: 'Small', 15: 'Small', 16: 'Small', 17: 'Small', 18: 'Small', 19: 'Small'}} )
plt.figure(figsize=(5,5),facecolor='#ffffff')
ax = plt.axes(facecolor='#ffffff')
plt.xticks(rotation=25)
sns.catplot(x='shape', hue='category', kind ='count', data = df1, height=5, aspect=1,ax=ax)
plt.xlabel('Diamond Shape')
plt.show()

I got the following plot

Why there is an extra blank plot below? How to not generate that?
(I need the ax to provide extra formatting for catplot)

Body:
You can use the following trick : Close the extra figure before plt.show()

plt.close(2)
plt.show()


问:
maxjavastacktracedepth=-1 failed to create JVM
Full error:

```<code>MaxJavaStackTraceDepth=-1 is outside allowed range [0 .... 1073741823],
improperly specified vm option 'MaxJavaStackTraceDepth=-1'

failed to create JVM. JVM path: C:\Program Files\Android\Android Studio\jre\jre
</code>```

Last thing I did to break it:

Under Help → Edit Custom VM Options:

```<code>-Xms1024m
-Xmx3072m # <------ increase this to most of your RAM
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=440m
-XX:+UseCompressedOops
-XX:-HeapDumpOnOutOfMemoryError
-Dfile.encoding=UTF-8
</code>```

I have tried:

Reinstalling Android studio

Deleting vm options.

```<code>-server
-Xms750m
-Xmx750m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-Djna.nosys=true
-Djna.boot.library.path=
-da
</code>```

答:
This is the path in my case.     C:\Users\DELL\.AndroidStudio3.5\config\studio64.exe.vmoptions

It may be different according to your android studio version.

Body:
Full error:

MaxJavaStackTraceDepth=-1 is outside allowed range [0 .... 1073741823],
improperly specified vm option 'MaxJavaStackTraceDepth=-1'

failed to create JVM. JVM path: C:\Program Files\Android\Android Studio\jre\jre

Last thing I did to break it:

Under Help → Edit Custom VM Options:

-Xms1024m
-Xmx3072m # <------ increase this to most of your RAM
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=440m
-XX:+UseCompressedOops
-XX:-HeapDumpOnOutOfMemoryError
-Dfile.encoding=UTF-8

I have tried:

Reinstalling Android studio

Deleting vm options.

-server
-Xms750m
-Xmx750m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-Djna.nosys=true
-Djna.boot.library.path=
-da


问:
Call to a variable that is inside another function
```<code>def HOME():
    """ The first screen
    """

    print ('Welcome to my program!')
    input_grocery_list = input('Hello, please enter here a list of groceries: ')

    def input_to_list():
        """ This f takes the input
        and put it inside a list
        without the: ','
        and print the list
        """
        new_grocery_list = []
        separator = ", "
        while ',' in input_grocery_list:
            d = input_grocery_list.index(',')
            y = input_grocery_list[:d]
            new_grocery_list.append(y)
            input_grocery_list = input_grocery_list[(d+1):]
            if ',' not in input_grocery_list:
                new_grocery_list.append(input_grocery_list)
        print(separator.join(new_grocery_list))

    def the_groceries_list():
        """ Do somthing  to the first input
        accord to the next choice
        """

        print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
        grocery_list = input('please enter here your choice : ')
        if grocery_list == '1':
            input_to_list(input_grocery_list)

    if len(input_grocery_list) != 0:
        the_groceries_list()
HOME()
</code>```

The error

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 37, in HOME
  File "<stdin>", line 34, in the_groceries_list
TypeError: input_to_list() takes 0 positional arguments but 1 was given
</code>```

My problem is probably in the second function called "input_to_list ()"

  While I am trying to read / change the "input_grocery_list" variable that is inside the first function (HOME)
It does not recognize him.

I tried to fix it using global or self but I probably don't really know where exactly to put them because in the meantime it didn't work for me.

Anyone know how I can fix this?

答:
As I can see, you try to have a main function, but you should use a class instead of a function, so more like this.

```<code>class Home():
    def __init__(self):
        """
        define your class wide variables here as following
        """
        # example
        # self.your_name = 'hello'
        # to access it in an function IN this class, type: self.your_name
        pass

    def get_items(self):
        print('Welcome to my program!')
        input_grocery_list = input('Hello, please enter here a list of groceries (sep with comma): ')
        self.input_to_list(input_grocery_list)

    #                       you forgot this
    #                               ||
    #                               \/
    def input_to_list(self, grocery_list: str):
        """ This f takes the input
        and put it inside a list
        without the: ','
        and print the list
        """
        new_grocery_list = grocery_list.split(',')
        # to print as list
        print(new_grocery_list)
        # to print every item in list
        for item in new_grocery_list:
            print(item)
        # print('List End') # if you want to

    # I don't really know what that is supposed to do, but whatever it is it wont
    """
    def the_groceries_list(self):
        # Do somthing  to the first input
        # accord to the next choice

        print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
        grocery_list = input('please enter here your choice : ')
        if grocery_list == '1':
            input_to_list(input_grocery_list)

        if len(input_grocery_list) != 0:
            the_groceries_list()
    """

# to use this class and it's functions first create an object
home = Home()

# than call a function
home.get_items()
</code>```

I wont go into details of Classes and Object but here is a link for you.
Read this, it should explain the basics pretty good.

Body:
def HOME():
    """ The first screen
    """

    print ('Welcome to my program!')
    input_grocery_list = input('Hello, please enter here a list of groceries: ')

    def input_to_list():
        """ This f takes the input
        and put it inside a list
        without the: ','
        and print the list
        """
        new_grocery_list = []
        separator = ", "
        while ',' in input_grocery_list:
            d = input_grocery_list.index(',')
            y = input_grocery_list[:d]
            new_grocery_list.append(y)
            input_grocery_list = input_grocery_list[(d+1):]
            if ',' not in input_grocery_list:
                new_grocery_list.append(input_grocery_list)
        print(separator.join(new_grocery_list))

    def the_groceries_list():
        """ Do somthing  to the first input
        accord to the next choice
        """

        print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
        grocery_list = input('please enter here your choice : ')
        if grocery_list == '1':
            input_to_list(input_grocery_list)

    if len(input_grocery_list) != 0:
        the_groceries_list()
HOME()

The error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 37, in HOME
  File "<stdin>", line 34, in the_groceries_list
TypeError: input_to_list() takes 0 positional arguments but 1 was given

My problem is probably in the second function called "input_to_list ()"

  While I am trying to read / change the "input_grocery_list" variable that is inside the first function (HOME)
It does not recognize him.

I tried to fix it using global or self but I probably don't really know where exactly to put them because in the meantime it didn't work for me.

Anyone know how I can fix this?

Body:
As I can see, you try to have a main function, but you should use a class instead of a function, so more like this.

class Home():
    def __init__(self):
        """
        define your class wide variables here as following
        """
        # example
        # self.your_name = 'hello'
        # to access it in an function IN this class, type: self.your_name
        pass

    def get_items(self):
        print('Welcome to my program!')
        input_grocery_list = input('Hello, please enter here a list of groceries (sep with comma): ')
        self.input_to_list(input_grocery_list)

    #                       you forgot this
    #                               ||
    #                               \/
    def input_to_list(self, grocery_list: str):
        """ This f takes the input
        and put it inside a list
        without the: ','
        and print the list
        """
        new_grocery_list = grocery_list.split(',')
        # to print as list
        print(new_grocery_list)
        # to print every item in list
        for item in new_grocery_list:
            print(item)
        # print('List End') # if you want to

    # I don't really know what that is supposed to do, but whatever it is it wont
    """
    def the_groceries_list(self):
        # Do somthing  to the first input
        # accord to the next choice

        print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
        grocery_list = input('please enter here your choice : ')
        if grocery_list == '1':
            input_to_list(input_grocery_list)

        if len(input_grocery_list) != 0:
            the_groceries_list()
    """

# to use this class and it's functions first create an object
home = Home()

# than call a function
home.get_items()

I wont go into details of Classes and Object but here is a link for you.
Read this, it should explain the basics pretty good.


问:
TypeError 'builtin_function_or_method' is not iterable during heroku deployment
I'm trying to deploy my first django app to heroku. I have followed all the settings steps in the guide but I run into the following Traceback during deployment:

```<code>if 'DATABASES' not in config:
TypeError: argument of type 'builtin_function_or_method' is not iterable
</code>```

If I disable collectstatic then deployment runs without errors but as soon as I try to migrate my database it raises the same error. Can anyone help please?

答:
It turns out I was missing a () in my django settings file:

```<code>django_heroku.settings(locals())
</code>```

instead of:

```<code>django_heroku.settings(locals)
</code>```

Body:
I'm trying to deploy my first django app to heroku. I have followed all the settings steps in the guide but I run into the following Traceback during deployment:

if 'DATABASES' not in config:
TypeError: argument of type 'builtin_function_or_method' is not iterable

If I disable collectstatic then deployment runs without errors but as soon as I try to migrate my database it raises the same error. Can anyone help please?

Body:
It turns out I was missing a () in my django settings file:

django_heroku.settings(locals())

instead of:

django_heroku.settings(locals)


问:
Convert date issue in c#
I have dateformat issue where I need to convert the date from DB to different formats according to the login

Like I have 3 different format

DD/MM/YY,MM/DD/YY,DD/MMM/YY
I tried to convert using the following methods but no luck.

```<code>DateTime.TryParseExact(drtemp["StartDate"].ToString(),dateFormat,null,
   System.Globalization.DateTimeStyles.None,out startDate);
orderDate =DateTime.ParseExact(drtemp["StartDate"].ToString(), dateFormat, null);
</code>```

Any help is highly apprenticed
Thanks,
Magz

答:
You can do:

```<code>string formattedDate = ((DateTime)drtemp["StartDate"]).ToString(dateFormat);
</code>```

See MSDN DateTime.ToString reference

Title: Convert date issue in c#

Body:
I have dateformat issue where I need to convert the date from DB to different formats according to the login

Like I have 3 different format

DD/MM/YY,MM/DD/YY,DD/MMM/YY
I tried to convert using the following methods but no luck.

DateTime.TryParseExact(drtemp["StartDate"].ToString(),dateFormat,null,
   System.Globalization.DateTimeStyles.None,out startDate);
orderDate =DateTime.ParseExact(drtemp["StartDate"].ToString(), dateFormat, null);

Any help is highly apprenticed
Thanks,
Magz

Body:
You can do:

string formattedDate = ((DateTime)drtemp["StartDate"]).ToString(dateFormat);

See MSDN DateTime.ToString reference


问:
Not able to call class method using Provider.of(context)
I am learning to use State Management and Provider package using this code.

```<code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Data>(
      create: (context) => Data(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: MyText(),
          ),
          body: Level1(),
        ),
      ),
    );
  }
}

class Level1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Level2(),
    );
  }
}

class Level2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        MyTextField(),
        Level3(),
      ],
    );
  }
}

class Level3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(Provider.of<Data>(context).data);
  }
}

class MyText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(Provider.of<Data>(context).data);
  }
}

class MyTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: (newText) {
        print("onChanged Start");
        Provider.of<Data>(context).changeString(newText); //this line troubling me
        print("onChanged End");
      },
    );
  }
}

class Data extends ChangeNotifier {
  String data = "Some Data";

  void changeString(String newString) {
    print("changeString Start");
    print(newString + " changeString Text");
    data = newString;
    notifyListeners();
    print("changeString End");
  }
}
</code>```

While Running the app, The AppBar Text MyText() and Level 3 Text Text() works fine.
as if I change the value of data in the code and Hot Restart the changes updated in data and also reflected in the app.

I also created MyTextFiled() where any changes occur it should get updated in data but the changeString() method is not getting called by the Provider.of<Data>(context) at line 64.

Here is the console output when I typed "Test" in the TextField.

```<code>onChange Start
t
onChange Start
te
onChange Start
tes
onChange Start
test
</code>```

Expected was:

```<code>onChange Start
t
changeString Start
t changeString Text
changeString End
onChange End
(so on .....)
</code>```

I am using provider: ^4.1.2 and in the tutorial (which I am following), they use provider: ^3.0.0+1
So, I changed builder to create in line 10, as it was showing error.

My Flutter Version:

```<code>Flutter 1.17.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision e6b34c2b5c (4 weeks ago) • 2020-05-02 11:39:18 -0700
Engine • revision 540786dd51
Tools • Dart 2.8.1
</code>```

PS: My problem get solved when I replace Provider.of<Data>(context).changeString(newText); with context.read<Data>().changeString(newText); with the help of this example Provider Example

But I am not able to understand why Provider.of(context) didn't work but context.read() work.
Please, enlighten me with the explanation.

I apologize for asking a dumb question on this sacred community.
and Thank you for listening/reading my problem carefully.

答:
change your  TextField's onChanged function like this:

```<code>class MyTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: (newText) {
        print("onChanged Start");
        Provider.of<Data>(context,listen:false).changeString(newText); //notice , listen default value is true
        print("onChanged End");
      },
    );
  }
}

</code>```

you are right about context.read<Data>() but you should know that context.read<T>() is equivalent to Provider.of<T>(context,listen:false)

As mentioned in the documentation =>

context.watch<T>()  is the same as Provider.of<T>(context) or Provider.of<T>(context,listen:true) because listen is true by default

context.read<T>()  is the same as Provider.of<T>(context,listen:false)

Body:
I am learning to use State Management and Provider package using this code.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Data>(
      create: (context) => Data(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: MyText(),
          ),
          body: Level1(),
        ),
      ),
    );
  }
}

class Level1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Level2(),
    );
  }
}

class Level2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        MyTextField(),
        Level3(),
      ],
    );
  }
}

class Level3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(Provider.of<Data>(context).data);
  }
}

class MyText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(Provider.of<Data>(context).data);
  }
}

class MyTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: (newText) {
        print("onChanged Start");
        Provider.of<Data>(context).changeString(newText); //this line troubling me
        print("onChanged End");
      },
    );
  }
}

class Data extends ChangeNotifier {
  String data = "Some Data";

  void changeString(String newString) {
    print("changeString Start");
    print(newString + " changeString Text");
    data = newString;
    notifyListeners();
    print("changeString End");
  }
}

While Running the app, The AppBar Text MyText() and Level 3 Text Text() works fine.
as if I change the value of data in the code and Hot Restart the changes updated in data and also reflected in the app.

I also created MyTextFiled() where any changes occur it should get updated in data but the changeString() method is not getting called by the Provider.of<Data>(context) at line 64.

Here is the console output when I typed "Test" in the TextField.

onChange Start
t
onChange Start
te
onChange Start
tes
onChange Start
test

Expected was:

onChange Start
t
changeString Start
t changeString Text
changeString End
onChange End
(so on .....)

I am using provider: ^4.1.2 and in the tutorial (which I am following), they use provider: ^3.0.0+1
So, I changed builder to create in line 10, as it was showing error.

My Flutter Version:

Flutter 1.17.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision e6b34c2b5c (4 weeks ago) • 2020-05-02 11:39:18 -0700
Engine • revision 540786dd51
Tools • Dart 2.8.1

PS: My problem get solved when I replace Provider.of<Data>(context).changeString(newText); with context.read<Data>().changeString(newText); with the help of this example Provider Example

But I am not able to understand why Provider.of(context) didn't work but context.read() work.
Please, enlighten me with the explanation.

I apologize for asking a dumb question on this sacred community.
and Thank you for listening/reading my problem carefully.

Body:
change your  TextField's onChanged function like this:

class MyTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextField(
      onChanged: (newText) {
        print("onChanged Start");
        Provider.of<Data>(context,listen:false).changeString(newText); //notice , listen default value is true
        print("onChanged End");
      },
    );
  }
}

you are right about context.read<Data>() but you should know that context.read<T>() is equivalent to Provider.of<T>(context,listen:false)

As mentioned in the documentation =>

context.watch<T>()  is the same as Provider.of<T>(context) or Provider.of<T>(context,listen:true) because listen is true by default

context.read<T>()  is the same as Provider.of<T>(context,listen:false)


问:
Include DB output from a file in an class
I'm trying to edit an class with an DB driven result.
I use ColorInterpreter by Our Code World, which is a PHP port of the JavaScript library NTC JS.

In this class is a public variable which is a array of hex/colorname pairs. This is hardcoded into the class. I want to make this dynamic with the use of an DB output.

I'm still struggeling with classes so I can't get my head around this.

colornames.inc.php:
Outputs something like this:

```<code>Array
(
    [b0bf1a] => Acid Green
    [7cb9e8] => Aero
    [c9ffe5] => Aero Blue
    [b284be] => African Violet
    [00308f] => Air Force Blue (USAF)
    [72a0c1] => Air superiority Blue
    ...
}
</code>```

ColorInterpreter.php:

```<code>class ColorInterpreter
    {
        public function __construct()
            {
                $color =            null;
                $rgb =              null;
                $hsl =              null;
                $name =             null;

                for($i = 0; $i < count($this->names); $i++)
                    {
                        $color =    "#".$this->names[$i][0];
                        $rgb =      $this->rgb($color);
                        $hsl =      $this->hsl($color);

                        array_push
                            (
                                $this->names[$i],
                                $rgb[0],
                                $rgb[1],
                                $rgb[2],
                                $hsl[0],
                                $hsl[1],
                                $hsl[2]
                            );
                    }
            }

        public function name($color)
            {
                ...
            }

        // adopted from: Farbtastic 1.2
        // http://acko.net/dev/farbtastic
        public function hsl($color)
            {
                ...
            }

        // adopted from: Farbtastic 1.2
        // http://acko.net/dev/farbtastic
        public function rgb($color)
            {
                ...
            }

        public function color($name)
            {
                ...
            }

// Below is the part I need to replace with the output given from colornames.inc.php
    public $names = array(
// Pink colors
array("FFC0CB", "Pink"),
array("FFB6C1", "Light Pink"),
array("FF69B4", "Hot Pink"),
array("FF1493", "Deep Pink"),
array("DB7093", "Pale Violet Red"),
array("C71585", "Medium Violet Red"),

array("E0115F", "Ruby"),
array("FF6FFF", "Ultra"),
...
    );

    }
</code>```

I don't know how, if or where I could/should include the colornames.inc.php
And I don't know where to correctly declare the needed variables. Obviously, $this->names represent the hardcoded array, but how has this to be changed to reflect the DB output I have?
I'm completely lost here.

答:
Your best option is to create a function that returns the values, and then pass that as the constructor when you create the class. e.g.

```<code>include 'file_with_function.php';
include 'file_with_class.php';

$initialColorValues = my_get_color_values();
$newObject = new ColorObject($initialColorValues);
</code>```

Now you can process that array in the constructor, and you have an object that is seeded with the correct color values

```<code>class XYZ {
    public $names;
    public function __construct($names){
       // ... do work
       $this->names = $work;
    }

}
</code>```

Body:
I'm trying to edit an class with an DB driven result.
I use ColorInterpreter by Our Code World, which is a PHP port of the JavaScript library NTC JS.

In this class is a public variable which is a array of hex/colorname pairs. This is hardcoded into the class. I want to make this dynamic with the use of an DB output.

I'm still struggeling with classes so I can't get my head around this.

colornames.inc.php:
Outputs something like this:

Array
(
    [b0bf1a] => Acid Green
    [7cb9e8] => Aero
    [c9ffe5] => Aero Blue
    [b284be] => African Violet
    [00308f] => Air Force Blue (USAF)
    [72a0c1] => Air superiority Blue
    ...
}

ColorInterpreter.php:

class ColorInterpreter
    {
        public function __construct()
            {
                $color =            null;
                $rgb =              null;
                $hsl =              null;
                $name =             null;

                for($i = 0; $i < count($this->names); $i++)
                    {
                        $color =    "#".$this->names[$i][0];
                        $rgb =      $this->rgb($color);
                        $hsl =      $this->hsl($color);

                        array_push
                            (
                                $this->names[$i],
                                $rgb[0],
                                $rgb[1],
                                $rgb[2],
                                $hsl[0],
                                $hsl[1],
                                $hsl[2]
                            );
                    }
            }

        public function name($color)
            {
                ...
            }

        // adopted from: Farbtastic 1.2
        // http://acko.net/dev/farbtastic
        public function hsl($color)
            {
                ...
            }

        // adopted from: Farbtastic 1.2
        // http://acko.net/dev/farbtastic
        public function rgb($color)
            {
                ...
            }

        public function color($name)
            {
                ...
            }

// Below is the part I need to replace with the output given from colornames.inc.php
    public $names = array(
// Pink colors
array("FFC0CB", "Pink"),
array("FFB6C1", "Light Pink"),
array("FF69B4", "Hot Pink"),
array("FF1493", "Deep Pink"),
array("DB7093", "Pale Violet Red"),
array("C71585", "Medium Violet Red"),

array("E0115F", "Ruby"),
array("FF6FFF", "Ultra"),
...
    );

    }

I don't know how, if or where I could/should include the colornames.inc.php
And I don't know where to correctly declare the needed variables. Obviously, $this->names represent the hardcoded array, but how has this to be changed to reflect the DB output I have?
I'm completely lost here.

Body:
Your best option is to create a function that returns the values, and then pass that as the constructor when you create the class. e.g.

include 'file_with_function.php';
include 'file_with_class.php';

$initialColorValues = my_get_color_values();
$newObject = new ColorObject($initialColorValues);

Now you can process that array in the constructor, and you have an object that is seeded with the correct color values

class XYZ {
    public $names;
    public function __construct($names){
       // ... do work
       $this->names = $work;
    }

}


问:
Delete words between specific elements in a txt-file with python
I am a python beginner and have the following problem:

I have a text file ('demofile.txt') and want to cut out everything between two specific elements ({start} and {end}) multiple times.

As en example imagine the text file contains:

'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

The outcome should be:

'AAAA CCCC EEEE GGGG'

First I defined the two elements which work as the cutter

```<code>start = '{start}'
end = '{end}'
</code>```

The I tried to cut out the first part and used this code:

```<code>text_start = text.find(start)
text_new = text[0:text_start]
print(text_new)
</code>```

The outcome is : 'AAAA ', which is what I wanted

For the next part I tried this:

```<code>text_start = text.find(end)
text_end = text.find(start, text_start)
text_new = text[text_start+len(end):text_end]
print(text_new)
</code>```

The outcome is: 'CCCC ' which is again what I was looking for

Now I tried to put everything together and build a loop and failed :-)

```<code>text_start = text.find(start)
text_new = text[0:text_start]

text_end = 0

for parts in text.split("{"):
    text_start = text.find(end, text_end)
    text_end = text.find(start, text_start)
    text_new = text_new + text[text_start+len(end):text_end]
print(text_new)
</code>```

The outcome is:
'AAAA  CCCC  EEEE  GGG {start} BBBB {end} CCCC {start} DDDD {end}...'
 and lot more of that. Thus the Outcome was okay until "GGG", but one G is missing. And all the stuff afterwards should be deleted.
I guess the loop continued somehow and the start of the loop with the split statement is crap.
What is the solution here? I would like to understand what went wrong and change the code.
Of course I am also interested in a shorter and more elegant way. I am sure what I did is quite terrible ;-)
I found something with "regular expressions" but I was not able to get this going as well.
Thanks for any idea.

(PS: any idea how I could save everything I cut out in a seperate file?)

答:
You can try with re package in python, so the code will b esomething like:

```<code>import re
text = "AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG"
</code>```

you could use simply:

```<code>re.sub("{start}|{end}" , "", text)
</code>```

but you can also use list comprehension  :

```<code>words_to_save = [word for word in text.split() if word not in "{start}"]
words_to_save = [word for word in words_to_save if word not in "{end}"]

clean_text = " ".join(words_to_save)
</code>```

Body:
I am a python beginner and have the following problem:

I have a text file ('demofile.txt') and want to cut out everything between two specific elements ({start} and {end}) multiple times.

As en example imagine the text file contains:

'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

The outcome should be:

'AAAA CCCC EEEE GGGG'

First I defined the two elements which work as the cutter

start = '{start}'
end = '{end}'

The I tried to cut out the first part and used this code:

text_start = text.find(start)
text_new = text[0:text_start]
print(text_new)

The outcome is : 'AAAA ', which is what I wanted

For the next part I tried this:

text_start = text.find(end)
text_end = text.find(start, text_start)
text_new = text[text_start+len(end):text_end]
print(text_new)

The outcome is: 'CCCC ' which is again what I was looking for

Now I tried to put everything together and build a loop and failed :-)

text_start = text.find(start)
text_new = text[0:text_start]

text_end = 0

for parts in text.split("{"):
    text_start = text.find(end, text_end)
    text_end = text.find(start, text_start)
    text_new = text_new + text[text_start+len(end):text_end]
print(text_new)

The outcome is:
'AAAA  CCCC  EEEE  GGG {start} BBBB {end} CCCC {start} DDDD {end}...'
 and lot more of that. Thus the Outcome was okay until "GGG", but one G is missing. And all the stuff afterwards should be deleted.
I guess the loop continued somehow and the start of the loop with the split statement is crap.
What is the solution here? I would like to understand what went wrong and change the code.
Of course I am also interested in a shorter and more elegant way. I am sure what I did is quite terrible ;-)
I found something with "regular expressions" but I was not able to get this going as well.
Thanks for any idea.

(PS: any idea how I could save everything I cut out in a seperate file?)

Body:
You can try with re package in python, so the code will b esomething like:

import re
text = "AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG"

you could use simply:

re.sub("{start}|{end}" , "", text)

but you can also use list comprehension  :

words_to_save = [word for word in text.split() if word not in "{start}"]
words_to_save = [word for word in words_to_save if word not in "{end}"]

clean_text = " ".join(words_to_save)


问:
Handling null in ReactJS
I have table, filling from Web - Api.

When I am deleting department, linked to some user. Department object getting null. And I have crash of my react app with such error: TypeError: Cannot read property 'name' of null

I've tried ternary like that, but it didn't help

```<code>(typeof user !=='undefined' && typeof user.department.name !=='undefined') ? user.department.name : ''
</code>```

  refreshList()
    {
       fetch("https://localhost:5001/api/users")
       .then(response=> response.json())
       .then(data=> {
        this.setState({users:data});
       });
    }

render(){
        const {users, userid, username, userfullname, department} = this.state;
        return(

           {users.map(user=>

               {user.id}
               {user.userName}
               {user.fullName}
               {user.department.name}	  <---- here i am getting crash when department is null

               ....
               )```

答:
This will handle undefined and null cases as well.</p>

```<code><td>{user.department && user.department.name || ''}</td>
</code>```

Title: Handling null in ReactJS

Body:
I have table, filling from Web - Api.

When I am deleting department, linked to some user. Department object getting null. And I have crash of my react app with such error: TypeError: Cannot read property 'name' of null

I've tried ternary like that, but it didn't help

(typeof user !=='undefined' && typeof user.department.name !=='undefined') ? user.department.name : ''

  refreshList()
    {
       fetch("https://localhost:5001/api/users")
       .then(response=> response.json())
       .then(data=> {
        this.setState({users:data});
       });
    }

render(){
        const {users, userid, username, userfullname, department} = this.state;
        return(

           {users.map(user=>

               {user.id}
               {user.userName}
               {user.fullName}
               {user.department.name}	  <---- here i am getting crash when department is null

               ....
               )

Body:
This will handle undefined and null cases as well.

<td>{user.department && user.department.name || ''}</td>


问:
Error:(2,25) Kotlin: Unresolved reference: Reference
I have created an array, however, that array is highlighted in red and it won't compile. I have attached a screenshot and if anyone can help, I would appreciate it.

Just to be a bit descriptive, I have checked other solutions here and I noticed that the problem was with a mismatch with Java bytecode and JVM target, well, these are set to Project bytecode version = 8 and JVM target = 1.8, as for the Kotlin, it is 1.3, I believe.

答:
The values you use are Identifiers, and are not expressions like String Integer.

This representation shows you how to use String Values:

```<code> fun main(){
    val brands = arrayOf("Samsung","Huawai","Nokia")
 }
</code>```

This representation shows you how to use Integer Values:

```<code>   fun main(){
       val brands=arrayOf(52,48,24")
   }
</code>```

For more info in kotlin use this link
[https://www.javatpoint.com/kotlin-data-type][1]

Body:
The values you use are Identifiers, and are not expressions like String Integer.

This representation shows you how to use String Values:

 fun main(){
    val brands = arrayOf("Samsung","Huawai","Nokia")
 }

This representation shows you how to use Integer Values:

   fun main(){
       val brands=arrayOf(52,48,24")
   }

For more info in kotlin use this link
[https://www.javatpoint.com/kotlin-data-type][1]


答:
You need to change definition of your nested function so it can take args:</p>

```<code>def input_to_list(input_grocery_list):
</code>```

Title: Call to a variable that is inside another function

Body:
You need to change definition of your nested function so it can take args:

def input_to_list(input_grocery_list):


答:
This is a JavaScript error. If you try to access a property in an object which is null or undefined, you'll get a Type Error. The solution is to validate the data before showing it like this:</p>

```<code><td>{user.department && user.department.name}</td>
</code>```

Title: Handling null in ReactJS

Body:
This is a JavaScript error. If you try to access a property in an object which is null or undefined, you'll get a Type Error. The solution is to validate the data before showing it like this:

<td>{user.department && user.department.name}</td>


问:
SQLAlchemy: filter_by with like() on foreign attribute
I have the following models:

```<code>class CRRun(Base):
    ...
    crID = Column(u'CR_ID', INTEGER(), ForeignKey(CR.id), primary_key=True,
                  nullable=False)
    cr = relationship(CR, backref=backref("CR_RUN", uselist=False))
    ...

class CR(Base):
    ...
    id = Column(u'CR_ID', INTEGER(), primary_key=True, nullable=False)
    state = Column(u'STATE', VARCHAR(20))
    ...
</code>```

I am then trying to do the following:

```<code>state = 'some value'
crsRuns = Session.query(CRRun)
crsRuns = crsRuns.options(eagerload('cr'))
                 .filter(CRRun.cr != None)
                 .filter(CRRun.cr.state.like('%' + state + '%'))
</code>```

However, this causes the following error:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'state'

How can I filter my query by the value of a column in a table that's connected to the table I'm querying via a foreign key?

答:
Try:</p>

```<code>state = 'some value'
crsRuns = Session.query(CRRun)
crsRuns = crsRuns.options(eagerload('cr')) \
    .filter(CRRun.cr.has(
        CR.state.like('%' + state + '%')
    ))
</code>```

Body:
I have the following models:

class CRRun(Base):
    ...
    crID = Column(u'CR_ID', INTEGER(), ForeignKey(CR.id), primary_key=True,
                  nullable=False)
    cr = relationship(CR, backref=backref("CR_RUN", uselist=False))
    ...

class CR(Base):
    ...
    id = Column(u'CR_ID', INTEGER(), primary_key=True, nullable=False)
    state = Column(u'STATE', VARCHAR(20))
    ...

I am then trying to do the following:

state = 'some value'
crsRuns = Session.query(CRRun)
crsRuns = crsRuns.options(eagerload('cr'))
                 .filter(CRRun.cr != None)
                 .filter(CRRun.cr.state.like('%' + state + '%'))

However, this causes the following error:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'state'

How can I filter my query by the value of a column in a table that's connected to the table I'm querying via a foreign key?

Body:
Try:

state = 'some value'
crsRuns = Session.query(CRRun)
crsRuns = crsRuns.options(eagerload('cr')) \
    .filter(CRRun.cr.has(
        CR.state.like('%' + state + '%')
    ))


问:
click function(), querySelectorAll, getElementByClassName and getElementById, try all variants
I try that the ID and the class variants work. The click and the message does not work.

html

<button type="button" class="trigger">Delete Message</button>

Message:

```

<p>js</p>

<pre class="lang-js prettyprint-override"><code>let click = document.querySelectorAll('.trigger'); // IE8

let messageAllClass = document.querySelectorAll('.messageAllClass');
let messageClass = document.getElementByClassName('messageClass');
let messeageID = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtID = "hallo from ID";

messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
messageClass.innerHTML = messClass.textContent + messageTxtClass;
messeageID.innerHTML = messID.textContent + messageTxtID;

click.onclick = function() {
  messageAllClass.innerHTML = "null";
  messageClass.innerHTML = "null";
  messeageID.innerHTML = "null";
}
</code>```

saved on jsfiddle

答:
let click = document.querySelectorAll('.trigger'); // IE8
let mess = document.querySelectorAll('.message-class');
let messID = document.getElementById('message-id');
let messTxt = "hallo from class";
let messTxtID = "hallo from id";

mess[0].innerHTML = mess[0].textContent + messTxt;
messID.innerHTML = messID.textContent + messTxtID;

click[0].onclick = function() {
  mess.innerHTML = "leer";
  messID.innerHTML = "leer";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <button type="button" class="trigger">Delete Message</button>
 <h3>Message:</h3>
<div class="message-class"></div>
<div id="message-id"></div></code>```

Body:
I try that the ID and the class variants work. The click and the message does not work.

html

<button type="button" class="trigger">Delete Message</button>

Message:

js

let click = document.querySelectorAll('.trigger'); // IE8

let messageAllClass = document.querySelectorAll('.messageAllClass');
let messageClass = document.getElementByClassName('messageClass');
let messeageID = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtID = "hallo from ID";

messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
messageClass.innerHTML = messClass.textContent + messageTxtClass;
messeageID.innerHTML = messID.textContent + messageTxtID;

click.onclick = function() {
  messageAllClass.innerHTML = "null";
  messageClass.innerHTML = "null";
  messeageID.innerHTML = "null";
}

saved on jsfiddle

Body:
let click = document.querySelectorAll('.trigger'); // IE8
let mess = document.querySelectorAll('.message-class');
let messID = document.getElementById('message-id');
let messTxt = "hallo from class";
let messTxtID = "hallo from id";

mess[0].innerHTML = mess[0].textContent + messTxt;
messID.innerHTML = messID.textContent + messTxtID;

click[0].onclick = function() {
  mess.innerHTML = "leer";
  messID.innerHTML = "leer";
}

 <button type="button" class="trigger">Delete Message</button>
 <h3>Message:</h3>
<div class="message-class"></div>
<div id="message-id"></div>


问:
React context: how to transfer function?
How can I pass the addToCard function from the ShoppingBasketProvider component via context to run it in another component? And how right is it in the component to keep the functions in the component using the context. Thank you for your help.

I have a component:

```<code>export const ShoppingBasketContext = React.createContext();

export default class ShoppingBasketProvider extends Component {

  addToCard = (event) => {
    console.log(event);
  }

  render() {
    const { shoppingBasketItems } = `this.state`;

    return (
      <ShoppingBasketContext.Provider
        value={{
          shoppingBasketItems,

        }}>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )
 }
}
</code>```

答:
Context API is a provider from which we can share data among components. And obviously, we can pass the functions in similar way:

```<code>value={{
   shoppingBasketItems,
   addToCard: this.addToCard
}}
</code>```

But I would not suggest you to go with this approach. Instead, you can have a separate file let's call it Util.js and inside that export the required functions and you can use that where ever you want:

Util.js

```<code>export const required_function = () => {
  //...
}
</code>```

Component.js

```<code>import { required_function } from 'Util'
//... required_function() ...
</code>```

Body:
How can I pass the addToCard function from the ShoppingBasketProvider component via context to run it in another component? And how right is it in the component to keep the functions in the component using the context. Thank you for your help.

I have a component:

export const ShoppingBasketContext = React.createContext();

export default class ShoppingBasketProvider extends Component {

  addToCard = (event) => {
    console.log(event);
  }

  render() {
    const { shoppingBasketItems } = `this.state`;

    return (
      <ShoppingBasketContext.Provider
        value={{
          shoppingBasketItems,

        }}>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )
 }
}

Body:
Context API is a provider from which we can share data among components. And obviously, we can pass the functions in similar way:

value={{
   shoppingBasketItems,
   addToCard: this.addToCard
}}

But I would not suggest you to go with this approach. Instead, you can have a separate file let's call it Util.js and inside that export the required functions and you can use that where ever you want:

Util.js

export const required_function = () => {
  //...
}

Component.js

import { required_function } from 'Util'
//... required_function() ...


问:
Function to wrap a value to array if it is not and output correct type in TypeScript
I am trying to create a function to wrap a value to array if it is not an array

```<code>export function asArray<T extends Array<any>>(value: T): T
export function asArray<T>(value: T): T[]
export function asArray(value: any) {
  return Array.isArray(value) ? value : [value]
}
</code>```

But it doesn't work when the type of value is union type

```<code>type A = { a: 1 } | { a: 1 }[]

const fn = (v: A) => {
  const b = asArray(v)
  return b[0].a
}
</code>```

it throws

```<code>Property 'a' does not exist on type 'A'.
  Property 'a' does not exist on type '{ a: 1; }[]'.ts(2339)
</code>```

答:
Your union type is not an array, so it is using the second declaration:

function asArray<{ a: number } | { a: number }[]>(value: T): Array<{ a: number } | { a: number }[]>
```

<p>So, for the compiler, your <code>b[0]</code> can either be a { a: number } or an array of it. It therefore cannot be sure that there is a <code>a</code> property in it.</p>

<p>You would better define your function as:</p>

<pre class="lang-js prettyprint-override"><code>export function asArray<T>(value: T | T[]): T[] {
  return ([] as T[]).concat(value)
}
</code>```

This would even not require an overload.

Body:
I am trying to create a function to wrap a value to array if it is not an array

export function asArray<T extends Array<any>>(value: T): T
export function asArray<T>(value: T): T[]
export function asArray(value: any) {
  return Array.isArray(value) ? value : [value]
}

But it doesn't work when the type of value is union type

type A = { a: 1 } | { a: 1 }[]

const fn = (v: A) => {
  const b = asArray(v)
  return b[0].a
}

it throws

Property 'a' does not exist on type 'A'.
  Property 'a' does not exist on type '{ a: 1; }[]'.ts(2339)

Body:
Your union type is not an array, so it is using the second declaration:

function asArray<{ a: number } | { a: number }[]>(value: T): Array<{ a: number } | { a: number }[]>

So, for the compiler, your b[0] can either be a { a: number } or an array of it. It therefore cannot be sure that there is a a property in it.

You would better define your function as:

export function asArray<T>(value: T | T[]): T[] {
  return ([] as T[]).concat(value)
}

This would even not require an overload.


问:
Flutter IOS FCM push notification not coming into notification bar
I am new to Flutter and IOS. I am configuring FCM push notifications for both Android and IOS.For android its working fine.I have done by referring this link https://medium.com/@jun.chenying/flutter-tutorial-part3-push-notification-with-firebase-cloud-messaging-fcm-2fbdd84d3a5e
 . For IOS, if the app is opened and if I send FCM from Firebase Console at the same time , Flutter on message is called (See the screenshot , logs are there) . But if I close the app , notification is not coming to notification bar but I am receiving in Android App,
I don't know where is the problem , Problem with Apple Profiles or Flutter .

IOS Build Settings and Signing & Capabilities

Here is my code in flutter,

```<code>    class FirebaseNotifications {
       FirebaseMessaging _firebaseMessaging;
       SharedPreferences _sharedPreferences;

       void setUpFirebase() {
         _firebaseMessaging = FirebaseMessaging();
         initializeSharedPreferences();
         firebaseCloudMessaging_Listeners();
        }

        void initializeSharedPreferences() async {
        _sharedPreferences = await SharedPreferences.getInstance();
        }

        void firebaseCloudMessaging_Listeners() {
        if (Platform.isIOS) iOS_Permission();
        _firebaseMessaging.getToken().then((token) {
        _sharedPreferences.setString(Preferences.device_token, token);
         print('Token'+token);
         });

         _firebaseMessaging.configure(
          onMessage: (Map<String, dynamic> message) async {
          print('on message $message');
         },
          onResume: (Map<String, dynamic> message) async {
          print('on resume $message');
         },
         onLaunch: (Map<String, dynamic> message) async {
         print('on launch $message');
         },
       );
     }

     void iOS_Permission() {
     _firebaseMessaging.requestNotificationPermissions(
     IosNotificationSettings(sound: true, badge: true, alert: true));
     _firebaseMessaging.onIosSettingsRegistered
     .listen((IosNotificationSettings settings) {
     print("Settings registered: $settings");
    });
   }
  }
</code>```

答:
You are not alone in this problem - try this solution.

Also, check if it not working both on debug and release builds of the application - there is a possibility of notifications not parsed by the debug variant of app.

Body:
I am new to Flutter and IOS. I am configuring FCM push notifications for both Android and IOS.For android its working fine.I have done by referring this link https://medium.com/@jun.chenying/flutter-tutorial-part3-push-notification-with-firebase-cloud-messaging-fcm-2fbdd84d3a5e
 . For IOS, if the app is opened and if I send FCM from Firebase Console at the same time , Flutter on message is called (See the screenshot , logs are there) . But if I close the app , notification is not coming to notification bar but I am receiving in Android App,
I don't know where is the problem , Problem with Apple Profiles or Flutter .

IOS Build Settings and Signing & Capabilities

Here is my code in flutter,

    class FirebaseNotifications {
       FirebaseMessaging _firebaseMessaging;
       SharedPreferences _sharedPreferences;

       void setUpFirebase() {
         _firebaseMessaging = FirebaseMessaging();
         initializeSharedPreferences();
         firebaseCloudMessaging_Listeners();
        }

        void initializeSharedPreferences() async {
        _sharedPreferences = await SharedPreferences.getInstance();
        }

        void firebaseCloudMessaging_Listeners() {
        if (Platform.isIOS) iOS_Permission();
        _firebaseMessaging.getToken().then((token) {
        _sharedPreferences.setString(Preferences.device_token, token);
         print('Token'+token);
         });

         _firebaseMessaging.configure(
          onMessage: (Map<String, dynamic> message) async {
          print('on message $message');
         },
          onResume: (Map<String, dynamic> message) async {
          print('on resume $message');
         },
         onLaunch: (Map<String, dynamic> message) async {
         print('on launch $message');
         },
       );
     }

     void iOS_Permission() {
     _firebaseMessaging.requestNotificationPermissions(
     IosNotificationSettings(sound: true, badge: true, alert: true));
     _firebaseMessaging.onIosSettingsRegistered
     .listen((IosNotificationSettings settings) {
     print("Settings registered: $settings");
    });
   }
  }


问:
Ignore duplicate key insert with Entity Framework
I'm using ASP.NET MVC4 with Entity Framework Code First. I have a table called "users", with primary key "UserId". This table may have 200,000+ entries.

I need to insert another 50 users. I might do this like

```<code>foreach(User user in NewUsers){
    context.Add(user);
}
dbcontext.SaveChanges();
</code>```

The problem is, one or more of those new users might already exist in the DB. If I add them and then try to save, it throws an error and none of the valid ones get added. I could modify the code to do this:

```<code>foreach(User user in NewUsers){
    if(dbcontext.Users.FirstOrDefault(u => u.UserId) == null)
    {
        dbcontext.Users.Add(user);
    }
}
dbcontext.SaveChanges();
</code>```

which would work. The problem is, then it has to run a query 50 times on a 200,000+ entry table. So my question is, what is the most performance efficient method of inserting these users, ignoring any duplicates?

答:
You can just filter out the failures and keep trying until it succeeds or you get another sort of Exception

```<code>public partial class YourEntities: DbContext
{
    public override int SaveChanges()
    {
        var isSaved = false;
        do
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbUpdateException ex)
            {
                var entries = ex.Entries;
                foreach (var entry in entries)
                {
                    // change state to remove it from context
                    entry.State = EntityState.Detached;
                }
            }
        }
        while (!isSaved);

        return null;    // never gets here
    }
}
</code>```

You might want to put in some extra logic to avoid an infinite loop.

Body:
I'm using ASP.NET MVC4 with Entity Framework Code First. I have a table called "users", with primary key "UserId". This table may have 200,000+ entries.

I need to insert another 50 users. I might do this like

foreach(User user in NewUsers){
    context.Add(user);
}
dbcontext.SaveChanges();

The problem is, one or more of those new users might already exist in the DB. If I add them and then try to save, it throws an error and none of the valid ones get added. I could modify the code to do this:

foreach(User user in NewUsers){
    if(dbcontext.Users.FirstOrDefault(u => u.UserId) == null)
    {
        dbcontext.Users.Add(user);
    }
}
dbcontext.SaveChanges();

which would work. The problem is, then it has to run a query 50 times on a 200,000+ entry table. So my question is, what is the most performance efficient method of inserting these users, ignoring any duplicates?

Body:
You can just filter out the failures and keep trying until it succeeds or you get another sort of Exception

public partial class YourEntities: DbContext
{
    public override int SaveChanges()
    {
        var isSaved = false;
        do
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbUpdateException ex)
            {
                var entries = ex.Entries;
                foreach (var entry in entries)
                {
                    // change state to remove it from context
                    entry.State = EntityState.Detached;
                }
            }
        }
        while (!isSaved);

        return null;    // never gets here
    }
}

You might want to put in some extra logic to avoid an infinite loop.


问:
WireMock On Spring Boot Test With External Https Host
In my application, I have external third party API requests. I want to test my application with mocking this API requests.

My Service Class:

String API_URL = "https://external.com/v1/%s";
public Result executeRequest(String apiVersion, String subUrl, HttpMethod httpMethod)
{
    try
    {
        HttpRequestBase httpRequest;
        String url = String.format(API_URL, subUrl);
        if (httpMethod.equals(HttpMethod.GET))
        {
            httpRequest = new HttpGet(url);
        }
        else if (httpMethod.equals(HttpMethod.POST))
        {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, "UTF-8"));
        }
        ...
        headers.forEach(httpRequest::setHeader);
        HttpResponse response = httpClient.execute(httpRequest);
    }
    catch (IOException e)
    {
        logger.error("IO Error: {}", e.getMessage());
        return handleExceptions(e);
    }
}
```

<p>To sum up for service class, requests can be get, post, delete, put. And this requests will be processed with headers or body parts. Then will be handled as http request.</p>

<p>My test class:</p>

<pre class="lang-java prettyprint-override"><code>@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
public class ServiceTest
{

    private static final String API_URL = "https://external.com/v1";

    @Autowired
    private Service service;

    @Autowired
    protected Gson gson;

    @Rule
    public WireMockRule wireMockRule = new WireMockRule();

    @Test
    public void getResult_successfully()
    {
        Result result = new Result();
        wireMockRule.stubFor(get(urlPathMatching("/subUrl"))
                .willReturn(aResponse()
                        .proxiedFrom(API_URL)
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody(gson.toJson(result))));

        Result returnResult = service.executeRequest("/subUrl", GET);

        assertThat(returnResult).isEqualTo(result);
    }
}
</code>```

When I implement it like above, mocking doesn't work. Any suggestion?

Note: I hope code snippets will be enough to understand the code in overall.

答:
I solved it like;

Describe test api-url and port. Because Wiremock creates embedded localhost server.

So in applicaition-properties:

```<code>application-test.properties:
  - service.url: http://localhost:8484
application-prod.properties:
  - service.url: https://external.com/v1
</code>```

Then my test class:

```<code>@ClassRule
public static WireMockRule wireMockRule = new WireMockRule(8484);

@Test
public void getResult_successfully()
{
    Result result = new Result();
    wireMockRule.stubFor(get(urlPathMatching("/subUrl"))
            .willReturn(aResponse()
                    .proxiedFrom(API_URL)
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(gson.toJson(result))));

    Result returnResult = service.executeRequest("/subUrl", GET);

    assertThat(returnResult).isEqualTo(result);
}
</code>```

Body:
In my application, I have external third party API requests. I want to test my application with mocking this API requests.

My Service Class:

String API_URL = "https://external.com/v1/%s";
public Result executeRequest(String apiVersion, String subUrl, HttpMethod httpMethod)
{
    try
    {
        HttpRequestBase httpRequest;
        String url = String.format(API_URL, subUrl);
        if (httpMethod.equals(HttpMethod.GET))
        {
            httpRequest = new HttpGet(url);
        }
        else if (httpMethod.equals(HttpMethod.POST))
        {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, "UTF-8"));
        }
        ...
        headers.forEach(httpRequest::setHeader);
        HttpResponse response = httpClient.execute(httpRequest);
    }
    catch (IOException e)
    {
        logger.error("IO Error: {}", e.getMessage());
        return handleExceptions(e);
    }
}

To sum up for service class, requests can be get, post, delete, put. And this requests will be processed with headers or body parts. Then will be handled as http request.

My test class:

@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
public class ServiceTest
{

    private static final String API_URL = "https://external.com/v1";

    @Autowired
    private Service service;

    @Autowired
    protected Gson gson;

    @Rule
    public WireMockRule wireMockRule = new WireMockRule();

    @Test
    public void getResult_successfully()
    {
        Result result = new Result();
        wireMockRule.stubFor(get(urlPathMatching("/subUrl"))
                .willReturn(aResponse()
                        .proxiedFrom(API_URL)
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody(gson.toJson(result))));

        Result returnResult = service.executeRequest("/subUrl", GET);

        assertThat(returnResult).isEqualTo(result);
    }
}

When I implement it like above, mocking doesn't work. Any suggestion?

Note: I hope code snippets will be enough to understand the code in overall.

Body:
I solved it like;

Describe test api-url and port. Because Wiremock creates embedded localhost server.

So in applicaition-properties:

application-test.properties:
  - service.url: http://localhost:8484
application-prod.properties:
  - service.url: https://external.com/v1

Then my test class:

@ClassRule
public static WireMockRule wireMockRule = new WireMockRule(8484);

@Test
public void getResult_successfully()
{
    Result result = new Result();
    wireMockRule.stubFor(get(urlPathMatching("/subUrl"))
            .willReturn(aResponse()
                    .proxiedFrom(API_URL)
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(gson.toJson(result))));

    Result returnResult = service.executeRequest("/subUrl", GET);

    assertThat(returnResult).isEqualTo(result);
}