问:
Stop text view from going out of screen
Im trying to make an app in android studio. I have a textview with a circular background. The thing is that when i install it on ta physical device the Text view goes of the screen.
Hers the preview in android studio:

The Xml code:

```<code>             <?xml version="1.0" encoding="utf-8"?>
            <RelativeLayout

             xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
           android:layout_height="match_parent"
            android:background="#000000"
>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:orientation="horizontal"
            android:background="@drawable/top_bar">

            <TextView
                android:id="@+id/textView3"
                android:layout_width="40dp"
                android:layout_height="match_parent"
                android:layout_weight="0"

           android:drawableLeft="@drawable/ic_keyboard_arrow_left_black_24dp"

                />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:fontFamily="@font/segoeui"
                android:gravity="center_vertical|start"
                android:text="App name and image"

                android:textColor="#FFFFFF"
                android:textSize="30dp" />

        </LinearLayout>

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

            <TextView
                android:id="@+id/textView6"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fontFamily="@font/segoeui"
                android:gravity="center"
                android:text="Pakistan vs Australia T20"
                android:textColor="#ffff"
                android:textSize="24dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1.5dp"
            android:background="#ffff"
            android:orientation="vertical"
            android:layout_marginLeft="47dp"
            android:layout_marginRight="47dp"></LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            android:orientation="horizontal">

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

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="40dp"
                    android:gravity="center"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textView2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="Match Odds"
                        android:textColor="#ffff"
                        android:textSize="17dp" />

                    <TextView
                        android:id="@+id/textView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:paddingLeft="10dp"
                        android:text="Favourite"
                        android:textColor="#ffff"
                        android:textSize="17dp" />
                </LinearLayout>

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

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginTop="30dp"
                        android:orientation="horizontal">

                        <TextView
                            android:id="@+id/textView12"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView11"
                            android:layout_width="20dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="-"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView10"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />
                    </LinearLayout>

                    <TextView
                        android:id="@+id/textView13"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="40dp"
                        android:layout_marginTop="30dp"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="WestIndies"
                        android:textColor="#ffff"
                        android:textSize="16dp"

                        android:visibility="visible" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textView4"
                        android:layout_width="100dp"
                        android:layout_height="1dp"
                        android:layout_marginLeft="6dp"

                        android:background="@color/margins"
                        android:text="TextView" />

                    <TextView
                        android:id="@+id/textView7"
                        android:layout_width="100dp"
                        android:layout_height="1dp"
                        android:layout_marginLeft="30dp"
                        android:background="@color/margins"
                        android:text="TextView" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textView9"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="Session"
                        android:textColor="#ffff"
                        android:textSize="17dp" />

                    <TextView
                        android:id="@+id/textView8"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="Runs/Balls"
                        android:textColor="#ffff"
                        android:textSize="17dp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:orientation="horizontal">

                        <TextView
                            android:id="@+id/textView17"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#FF0000"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView18"
                            android:layout_width="20dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="-"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView19"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />
                    </LinearLayout>

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

                    </LinearLayout>
                </LinearLayout>

            </LinearLayout>

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

                <TextView
                    android:id="@+id/TextViewID"
                    android:layout_width="110dp"
                    android:layout_height="110dp"
                    android:layout_marginTop="80dp"
                    android:layout_marginLeft="35dp"
                    android:background="@drawable/green_circle"
                    android:gravity="center"
                    android:text="2"
                    android:textColor="#ff2800"
                    android:textSize="13sp" />
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>
</ScrollView>

  </RelativeLayout>
</code>```

What im getting on the screen:

ive tried using different devices with different screen sizes but all give the same result. How can i solve this.
TIA..!!!

答: I think it's because the LinearLayout where that round TextView is, is actually a child of another LinearLayout with horizontal orientation, and you have another empty LinearLayout of width 250dp right before it, which pushes the relevant layout out of screen. Can you try removing the empty LinearLayout and see if it helps?

Title: Stop text view from going out of screen

Body:
Im trying to make an app in android studio. I have a textview with a circular background. The thing is that when i install it on ta physical device the Text view goes of the screen.
Hers the preview in android studio:

The Xml code:

             <?xml version="1.0" encoding="utf-8"?>
            <RelativeLayout

             xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
           android:layout_height="match_parent"
            android:background="#000000"
>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:orientation="horizontal"
            android:background="@drawable/top_bar">

            <TextView
                android:id="@+id/textView3"
                android:layout_width="40dp"
                android:layout_height="match_parent"
                android:layout_weight="0"

           android:drawableLeft="@drawable/ic_keyboard_arrow_left_black_24dp"

                />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:fontFamily="@font/segoeui"
                android:gravity="center_vertical|start"
                android:text="App name and image"

                android:textColor="#FFFFFF"
                android:textSize="30dp" />

        </LinearLayout>

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

            <TextView
                android:id="@+id/textView6"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fontFamily="@font/segoeui"
                android:gravity="center"
                android:text="Pakistan vs Australia T20"
                android:textColor="#ffff"
                android:textSize="24dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1.5dp"
            android:background="#ffff"
            android:orientation="vertical"
            android:layout_marginLeft="47dp"
            android:layout_marginRight="47dp"></LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            android:orientation="horizontal">

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

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="40dp"
                    android:gravity="center"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textView2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="Match Odds"
                        android:textColor="#ffff"
                        android:textSize="17dp" />

                    <TextView
                        android:id="@+id/textView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:paddingLeft="10dp"
                        android:text="Favourite"
                        android:textColor="#ffff"
                        android:textSize="17dp" />
                </LinearLayout>

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

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginTop="30dp"
                        android:orientation="horizontal">

                        <TextView
                            android:id="@+id/textView12"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView11"
                            android:layout_width="20dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="-"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView10"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />
                    </LinearLayout>

                    <TextView
                        android:id="@+id/textView13"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="40dp"
                        android:layout_marginTop="30dp"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="WestIndies"
                        android:textColor="#ffff"
                        android:textSize="16dp"

                        android:visibility="visible" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textView4"
                        android:layout_width="100dp"
                        android:layout_height="1dp"
                        android:layout_marginLeft="6dp"

                        android:background="@color/margins"
                        android:text="TextView" />

                    <TextView
                        android:id="@+id/textView7"
                        android:layout_width="100dp"
                        android:layout_height="1dp"
                        android:layout_marginLeft="30dp"
                        android:background="@color/margins"
                        android:text="TextView" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textView9"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="Session"
                        android:textColor="#ffff"
                        android:textSize="17dp" />

                    <TextView
                        android:id="@+id/textView8"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:fontFamily="@font/segoeui"
                        android:gravity="center"
                        android:text="Runs/Balls"
                        android:textColor="#ffff"
                        android:textSize="17dp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:orientation="horizontal">

                        <TextView
                            android:id="@+id/textView17"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#FF0000"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView18"
                            android:layout_width="20dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="-"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/textView19"
                            android:layout_width="40dp"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="0"
                            android:textColor="#ffff"
                            android:textSize="20dp"
                            android:textStyle="bold" />
                    </LinearLayout>

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

                    </LinearLayout>
                </LinearLayout>

            </LinearLayout>

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

                <TextView
                    android:id="@+id/TextViewID"
                    android:layout_width="110dp"
                    android:layout_height="110dp"
                    android:layout_marginTop="80dp"
                    android:layout_marginLeft="35dp"
                    android:background="@drawable/green_circle"
                    android:gravity="center"
                    android:text="2"
                    android:textColor="#ff2800"
                    android:textSize="13sp" />
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>
</ScrollView>

  </RelativeLayout>

What im getting on the screen:

ive tried using different devices with different screen sizes but all give the same result. How can i solve this.
TIA..!!!


来源: stackexchange

问:
Can Haskell or OCAML handle sensitive data without leaking via garbage collection?
I would do something like this (pseudo code):

```<code>1. load sensitive encrypted data from file
2. decrypt the data
3. do something with the unencrypted data
4. override the data safely / securely (for example with random data)
</code>```

The time that the sensitive data lies plain (unencrypted) in memory should be as short as possible.

The plain data must not be leaked in any way.

A. Can such a program be written in Haskell or OCAML?

B. Can it be prevented that
    the data gets leaked, i.e. by being silently copied in the
    background by the garbage collector?

C. Can the plain data be properly
    overridden in memory?

As far as I know garbage collectors (GCs) can make copies of data silently in the background. I guess that is done by generational GC algorithms, but I don't know for sure.

I know that it still would be possible for an attacker to get the plain data if the attacker manages to get the memory of the program at the right time / state. I just consider to do that to raise security because I do not have the context (i.e. OS, swapping etc.) under control.

答:
I already mentioned this in a comment, but I think it is a really good question and deserves an answer.

There is already a data type ScrubbedBytes that has the following properties:

It is allocated with newAlignedPinnedByteArray#, which means while the newly allocated MutableByteArray# is referenced anywhere in your code it will not be GCed, but it will also not going to get moved or copied around.

Upon allocation a weak pointer is created with mkWeak# and a finalizer gets added to the newly allocated memory. This means that whenever scrubbed bytes are no longer referenced in your code and before GC deallocates the memory a scrubber will get invoked that will write zeros into the memory.

Equality will not short circuit, thus guarding against timing attacks.

There is one small gotcha to this scrubber. There is a small chance that it will not get executed, in particular if a program exits right before the GC should cleanup the memory. (See more info on weak pointers.) Therefore, I would recommend implementing it using bracket pattern. Here is how you can get it done with primitive package:

import Control.Exception
import Control.Monad.Primitive (RealWorld)
import qualified Data.Primitive.ByteArray as BA

withScrubbedMutableByteArray ::
     Int -- ^ Number of bytes
  -> (BA.MutableByteArray RealWorld -> IO a)
  -- ^ Action to execute
  -> IO a
withScrubbedMutableByteArray c f = do
  mba <- BA.newPinnedByteArray c
  f mba `finally` BA.setByteArray mba 0 c (0 :: Word8)
```

Reason why using finally is safer is because you will have stronger guarantees that the memory will be zeroed out. For example user hitting Ctrl-C in a correct setup will not prevent scrubber from running.

ContentLicense: CC BY-SA 4.0

Body:
I would do something like this (pseudo code):

1. load sensitive encrypted data from file
2. decrypt the data
3. do something with the unencrypted data
4. override the data safely / securely (for example with random data)

The time that the sensitive data lies plain (unencrypted) in memory should be as short as possible.

The plain data must not be leaked in any way.

A. Can such a program be written in Haskell or OCAML?

B. Can it be prevented that
    the data gets leaked, i.e. by being silently copied in the
    background by the garbage collector?

C. Can the plain data be properly
    overridden in memory?

As far as I know garbage collectors (GCs) can make copies of data silently in the background. I guess that is done by generational GC algorithms, but I don't know for sure.

I know that it still would be possible for an attacker to get the plain data if the attacker manages to get the memory of the program at the right time / state. I just consider to do that to raise security because I do not have the context (i.e. OS, swapping etc.) under control.

Body:
I already mentioned this in a comment, but I think it is a really good question and deserves an answer.

There is already a data type ScrubbedBytes that has the following properties:

It is allocated with newAlignedPinnedByteArray#, which means while the newly allocated MutableByteArray# is referenced anywhere in your code it will not be GCed, but it will also not going to get moved or copied around.

Upon allocation a weak pointer is created with mkWeak# and a finalizer gets added to the newly allocated memory. This means that whenever scrubbed bytes are no longer referenced in your code and before GC deallocates the memory a scrubber will get invoked that will write zeros into the memory.

Equality will not short circuit, thus guarding against timing attacks.

There is one small gotcha to this scrubber. There is a small chance that it will not get executed, in particular if a program exits right before the GC should cleanup the memory. (See more info on weak pointers.) Therefore, I would recommend implementing it using bracket pattern. Here is how you can get it done with primitive package:

import Control.Exception
import Control.Monad.Primitive (RealWorld)
import qualified Data.Primitive.ByteArray as BA

withScrubbedMutableByteArray ::
     Int -- ^ Number of bytes
  -> (BA.MutableByteArray RealWorld -> IO a)
  -- ^ Action to execute
  -> IO a
withScrubbedMutableByteArray c f = do
  mba <- BA.newPinnedByteArray c
  f mba `finally` BA.setByteArray mba 0 c (0 :: Word8)

Reason why using finally is safer is because you will have stronger guarantees that the memory will be zeroed out. For example user hitting Ctrl-C in a correct setup will not prevent scrubber from running.


问:
How to initialise type, slice of strings, from a list of strings in Go
Let's say I have the following:

a structure

```<code>type MyStructure struct {
    Field1     int
    CityNames   []string
}
</code>```

-a type, that I used as a response. I created this type just to make the response more suggestive when reading than a slice of strings

```<code>type CityNamesReponse []string
</code>```

then I have a function where I want to get from my structure just the Names and put it in the response

```<code>func GetCities() *CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return &CityNameResponse{ dbResult.CityNames}
}

</code>```

I do not want to loop over the data, just want to do it in one go. Tried also:

```<code>return &CityNameResponse{ ...dbResult.CityNames}
</code>```

Could do it like this, but I am new in Go and a bit confused and would like to do it the right way. This doesn't feel good :

```<code>    // This works
    c := dbResults.CityNames
    response := make(CityNameResponse, 0)
    response = c
    return &response
</code>```

Thanks

答:
Don't use a pointer to a slice. The pointer probably hurts performance and it complicates the code.

Do use a conversion from []string to CityNamesReponse.

```<code>func GetCities() CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return CityNameResponse(dbResult.CityNames)
}
</code>```

If you feel that you must use a pointer to a slice, then use a conversion from *[]string to *CityNameReponse.

```<code>func GetCities() *CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return (*CityNameResponse)(&dbResult.CityNames)
}
</code>```

Body:
Let's say I have the following:

a structure

type MyStructure struct {
    Field1     int
    CityNames   []string
}

-a type, that I used as a response. I created this type just to make the response more suggestive when reading than a slice of strings

type CityNamesReponse []string

then I have a function where I want to get from my structure just the Names and put it in the response

func GetCities() *CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return &CityNameResponse{ dbResult.CityNames}
}

I do not want to loop over the data, just want to do it in one go. Tried also:

return &CityNameResponse{ ...dbResult.CityNames}

Could do it like this, but I am new in Go and a bit confused and would like to do it the right way. This doesn't feel good :

    // This works
    c := dbResults.CityNames
    response := make(CityNameResponse, 0)
    response = c
    return &response

Thanks

Body:
Don't use a pointer to a slice. The pointer probably hurts performance and it complicates the code.

Do use a conversion from []string to CityNamesReponse.

func GetCities() CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return CityNameResponse(dbResult.CityNames)
}

If you feel that you must use a pointer to a slice, then use a conversion from *[]string to *CityNameReponse.

func GetCities() *CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return (*CityNameResponse)(&dbResult.CityNames)
}


问:
Symfony 5 DATABASE_URL with Docker containers
I Created a docker configuration for LEMP local server. I Tried to connect the Symfony app with MySQL database version 8 but the Connection is refused.

Error: SQLSTATE[HY000] [2002] Connection refused.

The problem is with DATABASE_URL in .env file required by Symfony 5.
What is the correct value for DATABASE_URL for a given docker-compose.yml configuration ? I run this on Docker for Windows. I was Able to connect to mysql bash with username root and root password.

docker-compose.yml:

```<code>###############################################################################
#                          Generated on phpdocker.io                          #
###############################################################################
version: "3.1"
services:

    memcached:
      image: memcached:alpine
      container_name: sampleapp-memcached

    mailhog:
      image: mailhog/mailhog:latest
      container_name: sampleapp-mailhog
      ports:
        - "8001:8025"

    redis:
      image: redis:alpine
      container_name: sampleapp-redis

    mysql:
      image: mysql:8.0
      container_name: sampleapp-mysql
      working_dir: /app
      volumes:
        - .:/app
      environment:
        - MYSQL_ROOT_PASSWORD=Ur7HJWzZ2QK9
        - MYSQL_DATABASE=maindatabase
        - MYSQL_USER=sampleuser
        - MYSQL_PASSWORD=FxGBWfJ86ykq
      ports:
        - "8002:3306"

    elasticsearch:
      image: elasticsearch:6.5.4
      container_name: sampleapp-elasticsearch

    webserver:
      image: nginx:alpine
      container_name: sampleapp-webserver
      working_dir: /app
      volumes:
          - .:/app
          - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      ports:
       - "8000:80"

    php-fpm:
      build: phpdocker/php-fpm
      container_name: sampleapp-php-fpm
      working_dir: /app
      volumes:
        - .:/app
        - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.4/fpm/conf.d/99-overrides.ini

</code>```

答:
Usually the DATABASE_URL string is a standard one:

```<code>mysql://user:pwd@host:port/db
</code>```

In this case:

```<code>DATABASE_URL=mysql://sampleuser:FxGBWfJ86ykq@127.0.0.1:8002/maindatabase
</code>```

Put it in your .env.local file and it should work. Note however that I work on unix and I do not have a Windows machine nearby.

Update

Following Alexander's suggestion, if you are running your Symfony app in a container (I didn't notice your webserver container, sorry!), then you should change the string to

```<code>DATABASE_URL=mysql://sampleuser:FxGBWfJ86ykq@mysql:3306/maindatabase
</code>```

Note, however, that for container to container communications you should use the default port (or expose a new one).
As regards setting the serverVersion, you can use the query parameter or (IMHO a better approach) set it in your doctrine.yaml config file. In addition, note that your server version should match the one you've specified in your docker-compose file.

Body:
I Created a docker configuration for LEMP local server. I Tried to connect the Symfony app with MySQL database version 8 but the Connection is refused.

Error: SQLSTATE[HY000] [2002] Connection refused.

The problem is with DATABASE_URL in .env file required by Symfony 5.
What is the correct value for DATABASE_URL for a given docker-compose.yml configuration ? I run this on Docker for Windows. I was Able to connect to mysql bash with username root and root password.

docker-compose.yml:

###############################################################################
#                          Generated on phpdocker.io                          #
###############################################################################
version: "3.1"
services:

    memcached:
      image: memcached:alpine
      container_name: sampleapp-memcached

    mailhog:
      image: mailhog/mailhog:latest
      container_name: sampleapp-mailhog
      ports:
        - "8001:8025"

    redis:
      image: redis:alpine
      container_name: sampleapp-redis

    mysql:
      image: mysql:8.0
      container_name: sampleapp-mysql
      working_dir: /app
      volumes:
        - .:/app
      environment:
        - MYSQL_ROOT_PASSWORD=Ur7HJWzZ2QK9
        - MYSQL_DATABASE=maindatabase
        - MYSQL_USER=sampleuser
        - MYSQL_PASSWORD=FxGBWfJ86ykq
      ports:
        - "8002:3306"

    elasticsearch:
      image: elasticsearch:6.5.4
      container_name: sampleapp-elasticsearch

    webserver:
      image: nginx:alpine
      container_name: sampleapp-webserver
      working_dir: /app
      volumes:
          - .:/app
          - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      ports:
       - "8000:80"

    php-fpm:
      build: phpdocker/php-fpm
      container_name: sampleapp-php-fpm
      working_dir: /app
      volumes:
        - .:/app
        - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.4/fpm/conf.d/99-overrides.ini

Body:
Usually the DATABASE_URL string is a standard one:

mysql://user:pwd@host:port/db

In this case:

DATABASE_URL=mysql://sampleuser:FxGBWfJ86ykq@127.0.0.1:8002/maindatabase

Put it in your .env.local file and it should work. Note however that I work on unix and I do not have a Windows machine nearby.

Update

Following Alexander's suggestion, if you are running your Symfony app in a container (I didn't notice your webserver container, sorry!), then you should change the string to

DATABASE_URL=mysql://sampleuser:FxGBWfJ86ykq@mysql:3306/maindatabase

Note, however, that for container to container communications you should use the default port (or expose a new one).
As regards setting the serverVersion, you can use the query parameter or (IMHO a better approach) set it in your doctrine.yaml config file. In addition, note that your server version should match the one you've specified in your docker-compose file.


问:
Composer error with GitHub OAuth token on fresh laravel/homestead provision
Fresh installed a laravel/homestead vagrant box, as per docs, run the init.sh, configured Homestead.yaml and ran $ vagrant up; vagrant ssh. Afterwards cd'ed to project's folder and ran composer install.

It hangs waiting for a token with the following message

```<code>Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
- Installing sebastian/diff (1.3.0)
Downloading: Connecting...
Could not fetch https://api.github.com/repos/sebastianbergmann/diff/zipball/863df9687835c62aa423a22412d26fa2ebde3fd3, please create a GitHub OAuth token to go over the API rate limit
Head to https://github.com/settings/tokens/new?scopes=repo&description=Composer+on+homestead+2015-08-01+2140
to retrieve a token. It will be stored in "/home/vagrant/.composer/auth.json" for future use by Composer.
Token (hidden):
</code>```

I have used laravel/homestead before, and I have never had to do any of these, is this some undocumented new feature or a bug or did I do something wrong?

答: Go to settings then Developer settings from personal access token you can generate a new token

ContentLicense: CC BY-SA 3.0

Body:
Fresh installed a laravel/homestead vagrant box, as per docs, run the init.sh, configured Homestead.yaml and ran $ vagrant up; vagrant ssh. Afterwards cd'ed to project's folder and ran composer install.

It hangs waiting for a token with the following message

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
- Installing sebastian/diff (1.3.0)
Downloading: Connecting...
Could not fetch https://api.github.com/repos/sebastianbergmann/diff/zipball/863df9687835c62aa423a22412d26fa2ebde3fd3, please create a GitHub OAuth token to go over the API rate limit
Head to https://github.com/settings/tokens/new?scopes=repo&description=Composer+on+homestead+2015-08-01+2140
to retrieve a token. It will be stored in "/home/vagrant/.composer/auth.json" for future use by Composer.
Token (hidden):

I have used laravel/homestead before, and I have never had to do any of these, is this some undocumented new feature or a bug or did I do something wrong?


问:
How to remove the Square Bracket in JSON using PHP
Below code is the returned JSON

```<code>[{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}]
</code>```

Below code is the desired result of the returned JSON (without the array bracket)

```<code>{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}
</code>```

Below code is to convert the array to the JSON format

```<code>include('connect-db.php');
$result = mysql_query("SELECT * FROM patientvaccinedetail");
$specific = [];
while($row = mysql_fetch_array( $result ,MYSQL_ASSOC)) {
echo "<tr>";
echo '<td width="100px">' . $row['id'] . '</td>';
echo '<td width="200px">' . $row['patientid'] . '</td>';
echo '<td width="200px">' . $row['vaccineid'] . '</td>';
  //**********Convert the array into json*******************

  $specific[] = ["one" => $row["id"],
                 "two" => $row["patientid"],
                 "three" => $row["vaccineid"]];

$result = json_encode($specific,JSON_UNESCAPED_UNICODE);

echo $result;
echo "</tr>";
echo "</table>";
?>
</code>```

To send the request to the API, iam using Guzzle
And the format the API require is {xx:xx},{xx:xx}
without the square bracket, any idea how to remove it using PHP.
Thanks in advance

```<code>     $client = new Client([
    'headers' => ['Content-Type' => 'application/json',
                  'Token' => $token]
                           ]);

       $response = $client->post('http://localhost:91/Religious',
       ['body' => ***Where the json will be place***]
       );
</code>```

答:
This will remove the outer wrapper without disturbing any inner wrappers:
</p>

```<code>$wrapped = <<<EOD
[{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}]
EOD;

$array = json_decode($wrapped, true);
$unwrapped = json_encode($array, JSON_FORCE_OBJECT);

print_r($unwrapped);
// {"0":{"one":"id","two":"id","three":"id"},"1":{"one":"id","two":"id","three":"id"}}
</code>```

Body:
Below code is the returned JSON

[{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}]

Below code is the desired result of the returned JSON (without the array bracket)

{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}

Below code is to convert the array to the JSON format

include('connect-db.php');
$result = mysql_query("SELECT * FROM patientvaccinedetail");
$specific = [];
while($row = mysql_fetch_array( $result ,MYSQL_ASSOC)) {
echo "
";
echo '' . $row['id'] . '	';
echo '' . $row['patientid'] . '	';
echo '' . $row['vaccineid'] . '	';
  //**********Convert the array into json*******************

  $specific[] = ["one" => $row["id"],
                 "two" => $row["patientid"],
                 "three" => $row["vaccineid"]];

$result = json_encode($specific,JSON_UNESCAPED_UNICODE);

echo $result;
echo "
";
echo "
";
?>

To send the request to the API, iam using Guzzle
And the format the API require is {xx:xx},{xx:xx}
without the square bracket, any idea how to remove it using PHP.
Thanks in advance

     $client = new Client([
    'headers' => ['Content-Type' => 'application/json',
                  'Token' => $token]
                           ]);

       $response = $client->post('http://localhost:91/Religious',
       ['body' => ***Where the json will be place***]
       );

Body:
This will remove the outer wrapper without disturbing any inner wrappers:

$wrapped = <<<EOD
[{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}]
EOD;

$array = json_decode($wrapped, true);
$unwrapped = json_encode($array, JSON_FORCE_OBJECT);

print_r($unwrapped);
// {"0":{"one":"id","two":"id","three":"id"},"1":{"one":"id","two":"id","three":"id"}}


问:
How to find the first and last of one of several characters in a list of strings?
So I have a list of strings such as this:

```<code>my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
</code>```

I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last.

I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it.

The output I wanted was something like this:

```<code>first_positions=[3,2,10,1,4]
last_positions=[17,7,25,11,23]
</code>```

Thanks in advance for any answer

答:
Here is an implementation without using regex.

```<code>my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]

def find_i(word):
    first = None
    last = None
    for i, letter in enumerate(word):
        if first == None:
            if letter != '-':
                first = i
        else:
            if letter != '-':
                last = i
    return (first, last)

r = list(map(find_i, my_list))
print(r) #I like this output more, but it is up to you.

first_positions = [i[0] for i in r]
last_positions = [i[1] for i in r]

print(first_positions)
print(last_positions)
</code>```

Output:

```<code>[(3, 17), (2, 7), (10, 25), (1, 10), (4, 23)]
[3, 2, 10, 1, 4]
[17, 7, 25, 10, 23]
</code>```

Body:
So I have a list of strings such as this:

my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]

I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last.

I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it.

The output I wanted was something like this:

first_positions=[3,2,10,1,4]
last_positions=[17,7,25,11,23]

Thanks in advance for any answer

Body:
Here is an implementation without using regex.

my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]

def find_i(word):
    first = None
    last = None
    for i, letter in enumerate(word):
        if first == None:
            if letter != '-':
                first = i
        else:
            if letter != '-':
                last = i
    return (first, last)

r = list(map(find_i, my_list))
print(r) #I like this output more, but it is up to you.

first_positions = [i[0] for i in r]
last_positions = [i[1] for i in r]

print(first_positions)
print(last_positions)

Output:

[(3, 17), (2, 7), (10, 25), (1, 10), (4, 23)]
[3, 2, 10, 1, 4]
[17, 7, 25, 10, 23]


问:
Format time format in columns for Pandas pivot table
I am building a pivot table with Pandas from json data. I'd like to format the column names before sending to to_string().

```<code>import numpy as np
import pandas as pd

json_data = [
 {"year":2019,"month":"2019-11-01","sub_category":"Van fit out","category":"Vehicle","notes":"Heavy duty hooks","gross_amount":8.96},
 {"year":2019,"month":"2019-11-01","sub_category":"Fuel & oil","category":"Vehicle","notes":"Fuel","gross_amount":20.00},
# more data  [...]
 {"year":2020,"month":"2020-02-01","sub_category":"Gutter Vac","category":"WC Equipment + H&S","notes":"Tape Measure + Bungi Cord + Plastic Membrane + Extension reel + Microfibre cloths + Waterproof Jacket","gross_amount":97.94},
 {"year":2020,"month":"2020-02-01","sub_category":"Trad equipment","category":"WC Materials","notes":"Spray Bottle + Microfibres","gross_amount":4.47},
 ]

data = pd.DataFrame(json_data)

# Pivot the data:
pivot = pd.pivot_table(
            data, values=['gross_amount'], index=['category', 'sub_category'],
                    columns=['year', 'month'], aggfunc=np.sum, fill_value=0, dropna=True, margins=True)
# Add total rows for index level 0:
pivot = pd.concat([
        d.append(d.sum(skipna=True).rename((k, 'Total')))
        for k, d in pivot.groupby(level=0)
        ])

# Render to string:
string = pivot.to_string()

print(string)
</code>```

The result is

```<code>                                  gross_amount
year                                      2019       2020     All
month                               2019-11-01 2020-02-01
category           sub_category
All                                      28.96     102.41  131.37
                   Total                 28.96     102.41  131.37
Vehicle            Fuel & oil            20.00       0.00   20.00
                   Van fit out            8.96       0.00    8.96
                   Total                 28.96       0.00   28.96
WC Equipment + H&S Gutter Vac             0.00      97.94   97.94
                   Total                  0.00      97.94   97.94
WC Materials       Trad equipment         0.00       4.47    4.47
                   Total                  0.00       4.47    4.47
</code>```

How can I get the months to be formatted differently (in my case I need the month name)?
I have changed the month to a string in the dataframe before pivoting but then I lose the correct order.

Thanks

答:
that seems to work</p>

```<code># first get the column as date
data["monthdate"] = pd.to_datetime(data["month"])
# then format a column with the name
data['monthname'] = data["monthdate"].dt.strftime("%B")

# Pivot the data:
pivot = pd.pivot_table(
          data,
          values=['gross_amount'],
          index=['category', 'sub_category'],
          columns=['year', 'monthname'],
          aggfunc=np.sum,
          fill_value=0,
          dropna=True,
margins=True)

# Add total rows for index level 0:
pivot = pd.concat([
    d.append(d.sum(skipna=True).rename((k, 'Total')))
    for k, d in pivot.groupby(level=0)
    ])

# Render to string:
string = pivot.to_string()

print(string)
</code>```

Body:
I am building a pivot table with Pandas from json data. I'd like to format the column names before sending to to_string().

import numpy as np
import pandas as pd

json_data = [
 {"year":2019,"month":"2019-11-01","sub_category":"Van fit out","category":"Vehicle","notes":"Heavy duty hooks","gross_amount":8.96},
 {"year":2019,"month":"2019-11-01","sub_category":"Fuel & oil","category":"Vehicle","notes":"Fuel","gross_amount":20.00},
# more data  [...]
 {"year":2020,"month":"2020-02-01","sub_category":"Gutter Vac","category":"WC Equipment + H&S","notes":"Tape Measure + Bungi Cord + Plastic Membrane + Extension reel + Microfibre cloths + Waterproof Jacket","gross_amount":97.94},
 {"year":2020,"month":"2020-02-01","sub_category":"Trad equipment","category":"WC Materials","notes":"Spray Bottle + Microfibres","gross_amount":4.47},
 ]

data = pd.DataFrame(json_data)

# Pivot the data:
pivot = pd.pivot_table(
            data, values=['gross_amount'], index=['category', 'sub_category'],
                    columns=['year', 'month'], aggfunc=np.sum, fill_value=0, dropna=True, margins=True)
# Add total rows for index level 0:
pivot = pd.concat([
        d.append(d.sum(skipna=True).rename((k, 'Total')))
        for k, d in pivot.groupby(level=0)
        ])

# Render to string:
string = pivot.to_string()

print(string)

The result is

                                  gross_amount
year                                      2019       2020     All
month                               2019-11-01 2020-02-01
category           sub_category
All                                      28.96     102.41  131.37
                   Total                 28.96     102.41  131.37
Vehicle            Fuel & oil            20.00       0.00   20.00
                   Van fit out            8.96       0.00    8.96
                   Total                 28.96       0.00   28.96
WC Equipment + H&S Gutter Vac             0.00      97.94   97.94
                   Total                  0.00      97.94   97.94
WC Materials       Trad equipment         0.00       4.47    4.47
                   Total                  0.00       4.47    4.47

How can I get the months to be formatted differently (in my case I need the month name)?
I have changed the month to a string in the dataframe before pivoting but then I lose the correct order.

Thanks

Body:
that seems to work

# first get the column as date
data["monthdate"] = pd.to_datetime(data["month"])
# then format a column with the name
data['monthname'] = data["monthdate"].dt.strftime("%B")

# Pivot the data:
pivot = pd.pivot_table(
          data,
          values=['gross_amount'],
          index=['category', 'sub_category'],
          columns=['year', 'monthname'],
          aggfunc=np.sum,
          fill_value=0,
          dropna=True,
margins=True)

# Add total rows for index level 0:
pivot = pd.concat([
    d.append(d.sum(skipna=True).rename((k, 'Total')))
    for k, d in pivot.groupby(level=0)
    ])

# Render to string:
string = pivot.to_string()

print(string)


问:
Check for '+' at the beginning of a string using regex
I want to check for an optional + sign at the beginning of a string followed by numbers. My regex works on regex101.com, but once I put it into my code it no longer works. The numbers are included in the resulting string, but the + isn't.

My code (React Native):

```<code>const [mobileNumber, setMobileNumber] = useState('');

const onChange = (strippedValue) => {
  const formattedValue = strippedValue.match(/[+][0-9]+/g);
    if (formattedValue?.length) {
      setMobileNumber(formattedValue[0]);
    } else {
      setMobileNumber('');
    }
};
<View>
  <TextInput value={mobileNumber} onChange={onChange}/>
</View>

// Expected returns

// strippedValue = "0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "+0422119966"
console.log(formattedValue) === ["+0422119966"]

// strippedValue = "sjdb0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "sjdb+0422119966"
console.log(formattedValue) === ["+0422119966"]

// Current returns

// strippedValue = "0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "+0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "sjdb0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "sjdb+0422119966"
console.log(formattedValue) === ["0422119966"]
</code>```

答: In your current regex the + character is not optional, but mandatory. What you actually meant to write was probably something more like [+]?[0-9]+ (with a ? to indicate that it's optional). I personally would write it as /\+?\d+/

Body:
I want to check for an optional + sign at the beginning of a string followed by numbers. My regex works on regex101.com, but once I put it into my code it no longer works. The numbers are included in the resulting string, but the + isn't.

My code (React Native):

const [mobileNumber, setMobileNumber] = useState('');

const onChange = (strippedValue) => {
  const formattedValue = strippedValue.match(/[+][0-9]+/g);
    if (formattedValue?.length) {
      setMobileNumber(formattedValue[0]);
    } else {
      setMobileNumber('');
    }
};
<View>
  <TextInput value={mobileNumber} onChange={onChange}/>
</View>

// Expected returns

// strippedValue = "0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "+0422119966"
console.log(formattedValue) === ["+0422119966"]

// strippedValue = "sjdb0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "sjdb+0422119966"
console.log(formattedValue) === ["+0422119966"]

// Current returns

// strippedValue = "0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "+0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "sjdb0422119966"
console.log(formattedValue) === ["0422119966"]

// strippedValue = "sjdb+0422119966"
console.log(formattedValue) === ["0422119966"]


问:
Linq to XML, C#
I have a multilevel xml that i receive from queues. I need to break each level and put into database.
Below is the example:

```<code><?xml version="1.0" encoding="utf-16"?>
   <Request>
     <transactionID>3</transactionID>
       <units>
         <Number>001</serialNumber>
         <Id>222</instanceId>
         <fNumber>765</routeNumber>
         <status>open</status>
         <Message>Error</errorMessage>
       </units>
       <units>
         <Number>009</serialNumber>
         <Id>675</instanceId>
         <fNumber>765</routeNumber>
         <status>Close</status>
         <Message>mesage</errorMessage>
       </units>
     </Request>
</code>```

I tried using ds.ReadXML... it only takes units beceause i give datamember property of datagrid to units

i need to put units into different table and transaction id also..
Pls help.

If

答:
You can use Linq to XML to navigate through the XML and break it down or  you might Deserialize the XML into a C# object
Have a look at

Deserializing XML to Objects in C#

Title: Linq to XML, C#

Body:
I have a multilevel xml that i receive from queues. I need to break each level and put into database.
Below is the example:

<?xml version="1.0" encoding="utf-16"?>
   <Request>
     <transactionID>3</transactionID>
       <units>
         <Number>001</serialNumber>
         <Id>222</instanceId>
         <fNumber>765</routeNumber>
         <status>open</status>
         <Message>Error</errorMessage>
       </units>
       <units>
         <Number>009</serialNumber>
         <Id>675</instanceId>
         <fNumber>765</routeNumber>
         <status>Close</status>
         <Message>mesage</errorMessage>
       </units>
     </Request>

I tried using ds.ReadXML... it only takes units beceause i give datamember property of datagrid to units

i need to put units into different table and transaction id also..
Pls help.

If


问:
glTexImage2D - uploading a new image for the same texture id
Here is an example code:

```<code>//img1 2048x2048
//img2 1024x1024

glGenTextures(1, &texId);

glBindTexture(GL_TEXTURE_2D, texId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img1.getWidth(), img1.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img1.accessPixels());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);

//in  other function
glBindTexture(GL_TEXTURE_2D, texId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img2.getWidth(), img2.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img2.accessPixels());
glBindTexture(GL_TEXTURE_2D, 0);
</code>```

As you can see I use the same texture id for uploading two different images. I use nvidia-smi for monitoring gpu memory usage. A memory used by the texture equals 20 MiB. It doesn't matter which image is uploaded first. If I call a second glTexImage2D just after the first one without rebinding a texture then memory usage equals 4 MiB:

```<code>glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img1.getWidth(), img1.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img1.accessPixels());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img2.getWidth(), img2.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img2.accessPixels());
</code>```

Does it mean that opengl doesn't free a memory when other image is uploaded with the same texture id after rebinding a texture ?

答:
Texture names (= IDs) are just abstract handles. And between synchronization points a single texture name may in fact refer to an arbitrary number of images.

Consider this order of operations:

```<code>glBindTexture(GL_TEXTURE_2D, the_texture);

glTexImage2D(…);
glDraw…();

glTexImage2D(…);
glDraw…();

glTexImage2D(…);
glDraw…();
</code>```

Due to the as-if rule, each glDraw… operation must draw with the texture data that has been uploaded most recently. However due to the aynchronous nature of OpenGL, the actual drawing operations may be delayed until (much) later. Hence in the meantime the OpenGL implementation must hold on to the various texture images until the drawing is complete.

Body:
Here is an example code:

//img1 2048x2048
//img2 1024x1024

glGenTextures(1, &texId);

glBindTexture(GL_TEXTURE_2D, texId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img1.getWidth(), img1.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img1.accessPixels());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);

//in  other function
glBindTexture(GL_TEXTURE_2D, texId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img2.getWidth(), img2.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img2.accessPixels());
glBindTexture(GL_TEXTURE_2D, 0);

As you can see I use the same texture id for uploading two different images. I use nvidia-smi for monitoring gpu memory usage. A memory used by the texture equals 20 MiB. It doesn't matter which image is uploaded first. If I call a second glTexImage2D just after the first one without rebinding a texture then memory usage equals 4 MiB:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img1.getWidth(), img1.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img1.accessPixels());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img2.getWidth(), img2.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, img2.accessPixels());

Does it mean that opengl doesn't free a memory when other image is uploaded with the same texture id after rebinding a texture ?

Body:
Texture names (= IDs) are just abstract handles. And between synchronization points a single texture name may in fact refer to an arbitrary number of images.

Consider this order of operations:

glBindTexture(GL_TEXTURE_2D, the_texture);

glTexImage2D(…);
glDraw…();

glTexImage2D(…);
glDraw…();

glTexImage2D(…);
glDraw…();

Due to the as-if rule, each glDraw… operation must draw with the texture data that has been uploaded most recently. However due to the aynchronous nature of OpenGL, the actual drawing operations may be delayed until (much) later. Hence in the meantime the OpenGL implementation must hold on to the various texture images until the drawing is complete.


问:
Is there a way to get a buy on amazon button on my own app? (an api or so)
i am currently working on an app where i want to merge multiple E-commerce websites and be able to have certain products from them listed basically allowing to search over prices and products from multiple sites. is there any API that i could use to do so for amazons product listings?</p>

答:
Audience

This guide is intended for developers who want to build an e-commerce
storefront that sells items listed on Amazon.com, or an application
that helps others build e-commerce storefronts.

source: https://webservices.amazon.com/paapi5/documentation/


问:
Output whole row from list if duplicate has been found
I have a part of code that outputs duplicates from list. However it is giving only duplicates in particular column. How to output whole row if duplicate has been found?

Here is current code for finding duplicates:

```<code>var duplicatesPOSTADR = results.AsEnumerable()
    .Select(dr => dr.POSTADR.Trim())
    .GroupBy(x => x)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key)
    .ToList();
</code>```

Then I have another part that is sending an email message if duplicates has been found:

```<code>if (duplicatesPOSTADR?.Any() != false)
{
  string combindedString = string.Join(", ", duplicatesPOSTADR.Where(s => !string.IsNullOrEmpty(s)));
  string EmailBody = "There was an error and following duplicates has been found in POSTADR column: " + combindedString;
  CreateMailItem(EmailBody);
}
</code>```

So lets say I have data:

```<code>NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9
483   KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6
</code>```

Now as an output I get:

```<code>P4
</code>```

However I would like to get:

```<code>423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9
</code>```

Any hints how this can be achieved?

答:
After your grouping you need to select the records from the group instead of the key. You could use something like this:</p>

```<code>var duplicatesPOSTADR = results.AsEnumerable()
    .GroupBy(dr => dr.POSTADR.Trim())
    .Where(g => g.Count() > 1)
    .SelectMany(g => g)
    .ToList();
</code>```

Body:
I have a part of code that outputs duplicates from list. However it is giving only duplicates in particular column. How to output whole row if duplicate has been found?

Here is current code for finding duplicates:

var duplicatesPOSTADR = results.AsEnumerable()
    .Select(dr => dr.POSTADR.Trim())
    .GroupBy(x => x)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key)
    .ToList();

Then I have another part that is sending an email message if duplicates has been found:

if (duplicatesPOSTADR?.Any() != false)
{
  string combindedString = string.Join(", ", duplicatesPOSTADR.Where(s => !string.IsNullOrEmpty(s)));
  string EmailBody = "There was an error and following duplicates has been found in POSTADR column: " + combindedString;
  CreateMailItem(EmailBody);
}

So lets say I have data:

NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9
483   KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6

Now as an output I get:

P4

However I would like to get:

423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9

Any hints how this can be achieved?

Body:
After your grouping you need to select the records from the group instead of the key. You could use something like this:

var duplicatesPOSTADR = results.AsEnumerable()
    .GroupBy(dr => dr.POSTADR.Trim())
    .Where(g => g.Count() > 1)
    .SelectMany(g => g)
    .ToList();


问:
How to make an interactive checklist in Rstudio Shiny
I'm trying to build a checklist that will show me different parts of my data in Rstudio using Shiny.

For example:
If I check question A:
Row 1:2 should show in my table
If I check question B while A is still checked:
I want to see row 1:2 & 5.
If I uncheck question B but check question C while A is still checked:
I want to see row 1:2 & 3:4

I made 2 versions but I'm stuck on both

Version 1 (were I'm having trouble with the if statements in the server):

```<code>if (interactive()) {

library(shiny)
library(readxl)
Sheet2 <- read_excel("Sheet2.xlsx")
Sheet3 <- read_excel("Sheet3.xlsx")
Sheet4 <- read_excel("Sheet4.xlsx")

ui <- fluidPage(
  title = "Checklist",
  sidebarLayout(
    sidebarPanel(

      checkboxInput(inputId = "A",
                                  label = strong("A"),
                                  value = FALSE),

      conditionalPanel(condition = "input.A == true",
                       checkboxInput(inputId = "B",
                                     label = strong("B"),
                                     value = FALSE)),

      checkboxInput(inputId = "C",
                    label = strong("C"),
                    value = FALSE)

      ),
    mainPanel(
      tabsetPanel(
        id = 'dataset',
        tabPanel("Sheet2", DT::dataTableOutput("mytable1")),
        tabPanel("Sheet3", DT::dataTableOutput("mytable2")),
        tabPanel("Sheet4", DT::dataTableOutput("mytable3"))
      )
    )
  )
)

server <- function(input, output) {

  output$mytable1 <-
    DT::renderDataTable({
      if (input$A){
        DT::datatable(Sheet2[1:2,])}
      if (input$C){
        DT::datatable(Sheet2[3:4,])}
      if (input$B){
        DT::datatable(Sheet2[5,])
      }
    })

  output$mytable3 <-
    DT::renderDataTable({if ((input$A)){
      DT::datatable(Sheet3[3:4,])}
    })

}

shinyApp(ui, server)

}
</code>```

And version 2 (were i cant add multiple rows to my groupinput):

```<code>if (interactive()) {
library(shiny)
library(readxl)
Sheet2 <- read_excel("Sheet2.xlsx")
Sheet3 <- read_excel("Sheet3.xlsx")
Sheet4 <- read_excel("Sheet4.xlsx")
B3 <- 3:4

ui2 <- fluidPage(
  title = "M&A Checklist",
    mainPanel(
      tabsetPanel(
        id = 'dataset',
        tabPanel("Sheet1", checkboxGroupInput(inputId = "show_vars",
                                              label = "Questions:",
                                              choiceNames = c("AAAAAAAAAA","BBBBBBBBBB","CCCCCCCCCCC"),
                                              choiceValues = c("1","B3","5") )),
        tabPanel("Sheet2", DT::dataTableOutput("mytable1")),
        tabPanel("Sheet3", DT::dataTableOutput("mytable2")),
        tabPanel("Sheet4", DT::dataTableOutput("mytable3"))
    )
  )
)

server2 <- function(input, output) {

  # choose columns to display
  output$mytable1 <- DT::renderDataTable({
    DT::datatable(Sheet2[input$show_vars,])
  })

  # sorted columns are colored now because CSS are attached to them
  output$mytable2 <- DT::renderDataTable({
    DT::datatable(Sheet3[input$show_vars,])
  })

  # customize the length drop-down menu; display 5 rows per page by default
  output$mytable3 <- DT::renderDataTable({
    DT::datatable(Sheet4[input$show_vars,] )
  })

}

shinyApp(ui2, server2)
}
</code>```

Any suggestions, on how this can be done efficiently?

答:
One way to approach this, is to create an empty vector that will contain the rows of data to filter your data on. Then, for each if statement, you can add the additional rows to this vector.

This example is based on your first version. Let me know if this achieves what you need.

```<code>library(shiny)
library(DT)

df <- data.frame(
  a = 1:5,
  b = 6:10
)

Sheet2 <- Sheet3 <- Sheet4 <- df

ui <- fluidPage(
  title = "Checklist",
  sidebarLayout(
    sidebarPanel(
      checkboxInput(inputId = "A",
                    label = strong("A"),
                    value = FALSE),
      conditionalPanel(condition = "input.A == true",
                       checkboxInput(inputId = "B",
                                     label = strong("B"),
                                     value = FALSE)),
      checkboxInput(inputId = "C",
                    label = strong("C"),
                    value = FALSE)
    ),
    mainPanel(
      tabsetPanel(
        id = 'dataset',
        tabPanel("Sheet2", DT::dataTableOutput("mytable1")),
        tabPanel("Sheet3", DT::dataTableOutput("mytable2")),
        tabPanel("Sheet4", DT::dataTableOutput("mytable3"))
      )
    )
  )
)

server <- function(input, output) {

  selected_rows <- reactive({
    my_rows <- c()

    if (input$A) {
      my_rows <- c(my_rows, 1:2)
    }
    if (input$C) {
      my_rows <- c(my_rows, 3:4)
    }
    if (input$B) {
      my_rows <- c(my_rows, 5)
    }

    return(my_rows)
  })

  output$mytable1 <-
    DT::renderDataTable({
      DT::datatable(Sheet2[selected_rows(),])
    })

  output$mytable2 <-
    DT::renderDataTable({
      DT::datatable(Sheet3[selected_rows(),])
    })

  output$mytable3 <-
    DT::renderDataTable({
      DT::datatable(Sheet4[selected_rows(),])
    })

}

shinyApp(ui, server)
</code>```

Body:
I'm trying to build a checklist that will show me different parts of my data in Rstudio using Shiny.

For example:
If I check question A:
Row 1:2 should show in my table
If I check question B while A is still checked:
I want to see row 1:2 & 5.
If I uncheck question B but check question C while A is still checked:
I want to see row 1:2 & 3:4

I made 2 versions but I'm stuck on both

Version 1 (were I'm having trouble with the if statements in the server):

if (interactive()) {

library(shiny)
library(readxl)
Sheet2 <- read_excel("Sheet2.xlsx")
Sheet3 <- read_excel("Sheet3.xlsx")
Sheet4 <- read_excel("Sheet4.xlsx")

ui <- fluidPage(
  title = "Checklist",
  sidebarLayout(
    sidebarPanel(

      checkboxInput(inputId = "A",
                                  label = strong("A"),
                                  value = FALSE),

      conditionalPanel(condition = "input.A == true",
                       checkboxInput(inputId = "B",
                                     label = strong("B"),
                                     value = FALSE)),

      checkboxInput(inputId = "C",
                    label = strong("C"),
                    value = FALSE)

      ),
    mainPanel(
      tabsetPanel(
        id = 'dataset',
        tabPanel("Sheet2", DT::dataTableOutput("mytable1")),
        tabPanel("Sheet3", DT::dataTableOutput("mytable2")),
        tabPanel("Sheet4", DT::dataTableOutput("mytable3"))
      )
    )
  )
)

server <- function(input, output) {

  output$mytable1 <-
    DT::renderDataTable({
      if (input$A){
        DT::datatable(Sheet2[1:2,])}
      if (input$C){
        DT::datatable(Sheet2[3:4,])}
      if (input$B){
        DT::datatable(Sheet2[5,])
      }
    })

  output$mytable3 <-
    DT::renderDataTable({if ((input$A)){
      DT::datatable(Sheet3[3:4,])}
    })

}

shinyApp(ui, server)

}

And version 2 (were i cant add multiple rows to my groupinput):

if (interactive()) {
library(shiny)
library(readxl)
Sheet2 <- read_excel("Sheet2.xlsx")
Sheet3 <- read_excel("Sheet3.xlsx")
Sheet4 <- read_excel("Sheet4.xlsx")
B3 <- 3:4

ui2 <- fluidPage(
  title = "M&A Checklist",
    mainPanel(
      tabsetPanel(
        id = 'dataset',
        tabPanel("Sheet1", checkboxGroupInput(inputId = "show_vars",
                                              label = "Questions:",
                                              choiceNames = c("AAAAAAAAAA","BBBBBBBBBB","CCCCCCCCCCC"),
                                              choiceValues = c("1","B3","5") )),
        tabPanel("Sheet2", DT::dataTableOutput("mytable1")),
        tabPanel("Sheet3", DT::dataTableOutput("mytable2")),
        tabPanel("Sheet4", DT::dataTableOutput("mytable3"))
    )
  )
)

server2 <- function(input, output) {

  # choose columns to display
  output$mytable1 <- DT::renderDataTable({
    DT::datatable(Sheet2[input$show_vars,])
  })

  # sorted columns are colored now because CSS are attached to them
  output$mytable2 <- DT::renderDataTable({
    DT::datatable(Sheet3[input$show_vars,])
  })

  # customize the length drop-down menu; display 5 rows per page by default
  output$mytable3 <- DT::renderDataTable({
    DT::datatable(Sheet4[input$show_vars,] )
  })

}

shinyApp(ui2, server2)
}

Any suggestions, on how this can be done efficiently?

Body:
One way to approach this, is to create an empty vector that will contain the rows of data to filter your data on. Then, for each if statement, you can add the additional rows to this vector.

This example is based on your first version. Let me know if this achieves what you need.

library(shiny)
library(DT)

df <- data.frame(
  a = 1:5,
  b = 6:10
)

Sheet2 <- Sheet3 <- Sheet4 <- df

ui <- fluidPage(
  title = "Checklist",
  sidebarLayout(
    sidebarPanel(
      checkboxInput(inputId = "A",
                    label = strong("A"),
                    value = FALSE),
      conditionalPanel(condition = "input.A == true",
                       checkboxInput(inputId = "B",
                                     label = strong("B"),
                                     value = FALSE)),
      checkboxInput(inputId = "C",
                    label = strong("C"),
                    value = FALSE)
    ),
    mainPanel(
      tabsetPanel(
        id = 'dataset',
        tabPanel("Sheet2", DT::dataTableOutput("mytable1")),
        tabPanel("Sheet3", DT::dataTableOutput("mytable2")),
        tabPanel("Sheet4", DT::dataTableOutput("mytable3"))
      )
    )
  )
)

server <- function(input, output) {

  selected_rows <- reactive({
    my_rows <- c()

    if (input$A) {
      my_rows <- c(my_rows, 1:2)
    }
    if (input$C) {
      my_rows <- c(my_rows, 3:4)
    }
    if (input$B) {
      my_rows <- c(my_rows, 5)
    }

    return(my_rows)
  })

  output$mytable1 <-
    DT::renderDataTable({
      DT::datatable(Sheet2[selected_rows(),])
    })

  output$mytable2 <-
    DT::renderDataTable({
      DT::datatable(Sheet3[selected_rows(),])
    })

  output$mytable3 <-
    DT::renderDataTable({
      DT::datatable(Sheet4[selected_rows(),])
    })

}

shinyApp(ui, server)


问:
Simple A/B randomization script with PHP
I have two ad options in my theme, Adsense and "Custom". If the user enters code into the "Custom" field, it trumps whatever they have in the "Adsense" code field, so the theme places their custom ad atop the content area. If they have adsense enabled, and nothing in the custom ad spot, the theme places their adsense code there.

I'd like to add an option to allow the user to opt to have my theme automatically rotate ads between adsense and their custom ads. The custom ads may be Ebay, Amazon, ClickBank, etc.

How would you set up a PHP script that will randomly choose between two options?

Alternately, I'd like to be able to give the user the option to choose a percentage value so that the adsense ads are rotated based on their chosen percentage.

Just looking for some suggested approaches. Thanks in advance.

答:
1) I think mt_rand(); it's better than rand(); (source:http://php.net/manual/en/function.mt-rand.php)

2)
   $option[0] = 'html option 1';

   $option[1] = 'html option 1';

   $option[2] = 'html option 1';

   $option[3] = 'html option 2';

echo $option[rand()%count($option)];

It's not a better solution, but it works :)


问:
CocoaPods could not find compatible versions for pod "Firebase/Performance": when installed Firebase X in Ionic 5
My project in Ionic 5 and using Capacitor 2.1.2. I have installed Firebase X for capacitor using the following code.

```<code>npm install cordova-plugin-firebasex
npm install @ionic-native/firebase-x
</code>```

When I did ionic cap sync, the android installation was with no errors but I am getting the following error in IOS.

```<code>✖ Updating iOS native dependencies with "pod install" (may take several minutes):
✖ update ios:
[error] Error running update: Analyzing dependencies
[!] CocoaPods could not find compatible versions for pod "Firebase/Performance":
  In Podfile:
    CordovaPluginsStatic (from `../capacitor-cordova-ios-plugins`) was resolved to 2.1.2, which depends on
      Firebase/Performance (= 6.23.0)

None of your spec sources contain a spec satisfying the dependency: `Firebase/Performance (= 6.23.0)`.

You have either:
 * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.
</code>```

The Capacitor IOS version is "@capacitor/ios": "^2.1.2"

答:
Try running this command in the ios/App folder:</p>

```<code>pod install --repo-update
</code>```

Body:
My project in Ionic 5 and using Capacitor 2.1.2. I have installed Firebase X for capacitor using the following code.

npm install cordova-plugin-firebasex
npm install @ionic-native/firebase-x

When I did ionic cap sync, the android installation was with no errors but I am getting the following error in IOS.

✖ Updating iOS native dependencies with "pod install" (may take several minutes):
✖ update ios:
[error] Error running update: Analyzing dependencies
[!] CocoaPods could not find compatible versions for pod "Firebase/Performance":
  In Podfile:
    CordovaPluginsStatic (from `../capacitor-cordova-ios-plugins`) was resolved to 2.1.2, which depends on
      Firebase/Performance (= 6.23.0)

None of your spec sources contain a spec satisfying the dependency: `Firebase/Performance (= 6.23.0)`.

You have either:
 * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

The Capacitor IOS version is "@capacitor/ios": "^2.1.2"

Body:
Try running this command in the ios/App folder:

pod install --repo-update


问:
Invalid parameter configuration provided for $rulesApplier argument of Magento\\OfflineShipping\\Model\\SalesRule\\Calculator Magento 2
I got this error when i rewrite SalesRule module for RulesApplier Class to custom module to adding extra validation before rule apply using applyRules().

My di.xml

```<code>  <type name="Magento\SalesRule\Model\Validator">
    <arguments>
        <argument name="rulesApplier" xsi:type="array">Custom\SalesRule\Model\RulesApplier</argument>
    </arguments>
</type>
</code>```

My Class

```<code>namespace Custom\SalesRule\Model;

use Magento\SalesRule\Model\Rule\Action\Discount\CalculatorFactory;
use Magento\Framework\Event\ManagerInterface;
use Magento\SalesRule\Model\Utility;
use Magento\SalesRule\Model\Quote\ChildrenValidationLocator;
use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory;
use Magento\SalesRule\Api\Data\RuleDiscountInterfaceFactory;
use Magento\SalesRule\Api\Data\DiscountDataInterfaceFactory;

class RulesApplier extends \Magento\SalesRule\Model\RulesApplier
{

/**
 * custom validation before applying rule
 *
 * @param \Magento\SalesRule\Model\Rule\Action\Discount\CalculatorFactory\CalculatorFactory $calculatorFactory
 * @param \Magento\Framework\Event\ManagerInterface $eventManager
 * @param \Magento\SalesRule\Model\Utility $utility
 * @param \Magento\SalesRule\Model\Quote\ChildrenValidationLocator|null $childrenValidationLocator
 * @param DataFactory|null $discountDataFactory
 * @param RuleDiscountInterfaceFactory|null $discountInterfaceFactory
 * @param DiscountDataInterfaceFactory|null $discountDataInterfaceFactory
 */
public function __construct(
    CalculatorFactory $calculatorFactory,
    ManagerInterface $eventManager,
    Utility $utility,
    ChildrenValidationLocator $childrenValidationLocator = null,
    DataFactory $discountDataFactory = null,
    RuleDiscountInterfaceFactory $discountInterfaceFactory = null,
    DiscountDataInterfaceFactory $discountDataInterfaceFactory = null
) {
    parent::_construct(
        $calculatorFactory,
        $eventManager,
        $utility,
        $childrenValidationLocator,
        $discountDataFactory,
        $discountInterfaceFactory,
        $discountDataInterfaceFactory
    );
}

/**
 * Apply rules to current order item
 *
 * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item
 * @param \Magento\SalesRule\Model\ResourceModel\Rule\Collection $rules
 * @param bool $skipValidation
 * @param mixed $couponCode
 * @return array
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function applyRules($item, $rules, $skipValidation, $couponCode)
{
    $address = $item->getAddress();
    $appliedRuleIds = [];
    /* @var $rule \Magento\SalesRule\Model\Rule */
    foreach ($rules as $rule) {
        if (!$this->validatorUtility->canProcessRule($rule, $address)) {
            continue;
        }

        if (!$skipValidation && !$rule->getActions()->validate($item)) {
            if (!$this->childrenValidationLocator->isChildrenValidationRequired($item)) {
                continue;
            }
            $childItems = $item->getChildren();
            $isContinue = true;
            if (!empty($childItems)) {
                foreach ($childItems as $childItem) {
                    if ($rule->getActions()->validate($childItem)) {
                        $isContinue = false;
                    }
                }
            }
            if ($isContinue) {
                continue;
            }
        }

        $this->applyRule($item, $rule, $address, $couponCode);
        $appliedRuleIds[$rule->getRuleId()] = $rule->getRuleId();

        if ($rule->getStopRulesProcessing()) {
            break;
        }
    }

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

actually, i want to validate with my custom validation like rule applying limit qty to the cart items how many products can apply on cart,

Let suppose customer added 5 product into cart and admin allowed to discount only 3 per customer by coupon, so i need to add my custom efforts to apply coupon only 3 minimum price items.

can anyone guide me where i am wrong.

Thanks
Happy Coding!!

答:
After a deep search into arguments finaly understand the issue resolved by a small change in posted code.

Replace xsi:type="array" By xsi:type="object" because injected argument is a class object not an array.

Replace

```<code><argument name="rulesApplier" xsi:type="array">Custom\SalesRule\Model\RulesApplier</argument>
</code>```

By

```<code> <argument name="rulesApplier" xsi:type="object">Custom\SalesRule\Model\RulesApplier</argument>
</code>```

Hope this will help to you guys !!

Happy Coding

Body:
I got this error when i rewrite SalesRule module for RulesApplier Class to custom module to adding extra validation before rule apply using applyRules().

My di.xml

  <type name="Magento\SalesRule\Model\Validator">
    <arguments>
        <argument name="rulesApplier" xsi:type="array">Custom\SalesRule\Model\RulesApplier</argument>
    </arguments>
</type>

My Class

namespace Custom\SalesRule\Model;

use Magento\SalesRule\Model\Rule\Action\Discount\CalculatorFactory;
use Magento\Framework\Event\ManagerInterface;
use Magento\SalesRule\Model\Utility;
use Magento\SalesRule\Model\Quote\ChildrenValidationLocator;
use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory;
use Magento\SalesRule\Api\Data\RuleDiscountInterfaceFactory;
use Magento\SalesRule\Api\Data\DiscountDataInterfaceFactory;

class RulesApplier extends \Magento\SalesRule\Model\RulesApplier
{

/**
 * custom validation before applying rule
 *
 * @param \Magento\SalesRule\Model\Rule\Action\Discount\CalculatorFactory\CalculatorFactory $calculatorFactory
 * @param \Magento\Framework\Event\ManagerInterface $eventManager
 * @param \Magento\SalesRule\Model\Utility $utility
 * @param \Magento\SalesRule\Model\Quote\ChildrenValidationLocator|null $childrenValidationLocator
 * @param DataFactory|null $discountDataFactory
 * @param RuleDiscountInterfaceFactory|null $discountInterfaceFactory
 * @param DiscountDataInterfaceFactory|null $discountDataInterfaceFactory
 */
public function __construct(
    CalculatorFactory $calculatorFactory,
    ManagerInterface $eventManager,
    Utility $utility,
    ChildrenValidationLocator $childrenValidationLocator = null,
    DataFactory $discountDataFactory = null,
    RuleDiscountInterfaceFactory $discountInterfaceFactory = null,
    DiscountDataInterfaceFactory $discountDataInterfaceFactory = null
) {
    parent::_construct(
        $calculatorFactory,
        $eventManager,
        $utility,
        $childrenValidationLocator,
        $discountDataFactory,
        $discountInterfaceFactory,
        $discountDataInterfaceFactory
    );
}

/**
 * Apply rules to current order item
 *
 * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item
 * @param \Magento\SalesRule\Model\ResourceModel\Rule\Collection $rules
 * @param bool $skipValidation
 * @param mixed $couponCode
 * @return array
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function applyRules($item, $rules, $skipValidation, $couponCode)
{
    $address = $item->getAddress();
    $appliedRuleIds = [];
    /* @var $rule \Magento\SalesRule\Model\Rule */
    foreach ($rules as $rule) {
        if (!$this->validatorUtility->canProcessRule($rule, $address)) {
            continue;
        }

        if (!$skipValidation && !$rule->getActions()->validate($item)) {
            if (!$this->childrenValidationLocator->isChildrenValidationRequired($item)) {
                continue;
            }
            $childItems = $item->getChildren();
            $isContinue = true;
            if (!empty($childItems)) {
                foreach ($childItems as $childItem) {
                    if ($rule->getActions()->validate($childItem)) {
                        $isContinue = false;
                    }
                }
            }
            if ($isContinue) {
                continue;
            }
        }

        $this->applyRule($item, $rule, $address, $couponCode);
        $appliedRuleIds[$rule->getRuleId()] = $rule->getRuleId();

        if ($rule->getStopRulesProcessing()) {
            break;
        }
    }

    return $appliedRuleIds;
}

actually, i want to validate with my custom validation like rule applying limit qty to the cart items how many products can apply on cart,

Let suppose customer added 5 product into cart and admin allowed to discount only 3 per customer by coupon, so i need to add my custom efforts to apply coupon only 3 minimum price items.

can anyone guide me where i am wrong.

Thanks
Happy Coding!!

Body:
After a deep search into arguments finaly understand the issue resolved by a small change in posted code.

Replace xsi:type="array" By xsi:type="object" because injected argument is a class object not an array.

Replace

<argument name="rulesApplier" xsi:type="array">Custom\SalesRule\Model\RulesApplier</argument>

By

 <argument name="rulesApplier" xsi:type="object">Custom\SalesRule\Model\RulesApplier</argument>

Hope this will help to you guys !!

Happy Coding


问:
Form Based Arrays
I'm trying to access each value in a array without serializing it.
I than want this data stored into a datetime field in MySQL.
The data is received from my form [collect] => Array ( [0] => 01 [1] => 06 [2] => 2011 [3] => 17 [4] => 41 )

How can i store this array data into my database 'datetime' field column?

```<code>$dd=$_POST('$collect[0]');
$mm=$_POST('$collect[1]');
$yy=$_POST('$collect[2]');
$hh=$_POST('$collect[3]');
$ii=$_POST('$collect[4]');
$ddate = ('$yy','$mm','$dd',NULL,'$hh','$ii',NULL)
</code>```

What i'm trying to do above is take each array value and store it in variable names and than use variable $ddate to store as a datetime in my database. I'm not sure if this is even possible, but i have tried serialize, but date will not insert into database just shows format 0000/00/00 00:00 on database so i'm trying the above to see if this can work.

If there's a universal way I can use instead of the above, please can someone show me a small example which I can work from.

答:
From your example I don't really understand in what language you are coding, but in PHP it would be like this:

```<code>$time = mktime(
    $_POST['collect'][3],
    $_POST['collect'][4],
    0,
    $_POST['collect'][1],
    $_POST['collect'][0],
    $_POST['collect'][2],
);

$datetime = date('Y-m-d H:i:s', $time);
</code>```

Please refer to mktime() documentation for the order of arguments

Also, refer to date() if you need another formatting of the date.

Title: Form Based Arrays

Body:
I'm trying to access each value in a array without serializing it.
I than want this data stored into a datetime field in MySQL.
The data is received from my form [collect] => Array ( [0] => 01 [1] => 06 [2] => 2011 [3] => 17 [4] => 41 )

How can i store this array data into my database 'datetime' field column?

$dd=$_POST('$collect[0]');
$mm=$_POST('$collect[1]');
$yy=$_POST('$collect[2]');
$hh=$_POST('$collect[3]');
$ii=$_POST('$collect[4]');
$ddate = ('$yy','$mm','$dd',NULL,'$hh','$ii',NULL)

What i'm trying to do above is take each array value and store it in variable names and than use variable $ddate to store as a datetime in my database. I'm not sure if this is even possible, but i have tried serialize, but date will not insert into database just shows format 0000/00/00 00:00 on database so i'm trying the above to see if this can work.

If there's a universal way I can use instead of the above, please can someone show me a small example which I can work from.

Body:
From your example I don't really understand in what language you are coding, but in PHP it would be like this:

$time = mktime(
    $_POST['collect'][3],
    $_POST['collect'][4],
    0,
    $_POST['collect'][1],
    $_POST['collect'][0],
    $_POST['collect'][2],
);

$datetime = date('Y-m-d H:i:s', $time);

Please refer to mktime() documentation for the order of arguments

Also, refer to date() if you need another formatting of the date.


问:
Insert object to specific list index
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

```<code>list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)
</code>```

Output:

```<code>['String1', None, None, 'String2']
</code>```

答:
You can do it with something like this, if you really want:

```<code>def list_add(list_to_add, data, index):
if index < len(list_to_add):
    list_to_add[index] = data
else:
    while index > len(list_to_add):
        list_to_add.append(None)
    list_to_add.append(data)
</code>```

Actually, I don't think that this is the best way to do it, you should use a dictionary with integer indexes like this:

```<code>d = {1: 'String1'}
x = 4
d[x] = 'String2'
</code>```

It is implemented as a hash table, so it has constant lookup times.
Read this article, about python dictionaries!

Hope it helps :)

Title: Insert object to specific list index

Body:
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)

Output:

['String1', None, None, 'String2']

Body:
You can do it with something like this, if you really want:

def list_add(list_to_add, data, index):
if index < len(list_to_add):
    list_to_add[index] = data
else:
    while index > len(list_to_add):
        list_to_add.append(None)
    list_to_add.append(data)

Actually, I don't think that this is the best way to do it, you should use a dictionary with integer indexes like this:

d = {1: 'String1'}
x = 4
d[x] = 'String2'

It is implemented as a hash table, so it has constant lookup times.
Read this article, about python dictionaries!

Hope it helps :)


问:
Can we update any fhir resource on the basis of patient id?
I am trying to update Encounter resource on the basis of patient id but it is only creating one new record of Encounter rather than updating the existing one. But if i try to update Encounter on the basis of identifier i.e. unique value representing Encounter resource then it is able to update it.

Why is that? Can anyone explain?

答:
As you have discovered, some FHIR servers will allow a 'conditional update':

PUT [somebaseurl]/Encounter?search_key=search_value&...

You will need to add search parameters that filter all Encounters and result in a unique one, which will then be updated. Since, as Lloyd also indicated, a Patient can have multiple associated Encounters, the Patient id is not a suitable parameter for the conditional update. Your Encounter's identifier was unique enough, so that update succeeded.