问:
ListView Item Selected State not working
So I have a ListView and I want to change the color of each items background and text. This ListView is inside a ListFragment. My code inflates the layout in the onCreateView and inflates the layout of each item in the newView.

The android:state_pressed="true" is working fine, whenever I press in one item the background changes to that color. But when selecting an item neither the bg color or text color changes, even though I've defined an item with android:state_selected="true" in the selector.

Edit: I'm using SDK level 11 (Android 3.0) and a Motorola Xoom.

The list fragment layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</LinearLayout>
</code>```

The list item layout:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="25dp"
    android:background="@drawable/list_item_bg_selector">
    <TextView android:id="@+id/form_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/text_size_xlarge"
        android:textStyle="bold"
        android:textColor="@drawable/list_item_text_selector" />
    <TextView android:id="@+id/form_subtitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/text_size_medium"
        android:textStyle="normal"
        android:layout_marginTop="5dp"
        android:textColor="@drawable/list_item_text_selector" />
</LinearLayout>
</code>```

The background selector:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@color/white" />
    <item
        android:state_selected="true"
        android:drawable="@drawable/list_item_bg_selected" />
    <item
        android:drawable="@color/list_bg" />
</selector>
</code>```

The text selector:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:drawable="@color/white" />
    <item
        android:drawable="@color/list_text_blue" />
</selector>
</code>```

答: The answer is to use the android:state_activated="true" state, instead of the "selected" state. More on this here: ListFragment Item Selected Background

Body:
So I have a ListView and I want to change the color of each items background and text. This ListView is inside a ListFragment. My code inflates the layout in the onCreateView and inflates the layout of each item in the newView.

The android:state_pressed="true" is working fine, whenever I press in one item the background changes to that color. But when selecting an item neither the bg color or text color changes, even though I've defined an item with android:state_selected="true" in the selector.

Edit: I'm using SDK level 11 (Android 3.0) and a Motorola Xoom.

The list fragment layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</LinearLayout>

The list item layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="25dp"
    android:background="@drawable/list_item_bg_selector">
    <TextView android:id="@+id/form_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/text_size_xlarge"
        android:textStyle="bold"
        android:textColor="@drawable/list_item_text_selector" />
    <TextView android:id="@+id/form_subtitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/text_size_medium"
        android:textStyle="normal"
        android:layout_marginTop="5dp"
        android:textColor="@drawable/list_item_text_selector" />
</LinearLayout>

The background selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@color/white" />
    <item
        android:state_selected="true"
        android:drawable="@drawable/list_item_bg_selected" />
    <item
        android:drawable="@color/list_bg" />
</selector>

The text selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:drawable="@color/white" />
    <item
        android:drawable="@color/list_text_blue" />
</selector>


来源: stackexchange

问:
SQLite Adding a prefix to value after ordering
In SQLite, a column of numbers have been orderd in descending order by:

```<code>ORDER BY Subtotal DESC
</code>```

Is there a way to add a prefix after the numbers have been ordered in descending order? For example a '$' Prefix in front of the numbers.

答: You can just select a column that has more formatting, e.g. ('$' ||  Subtotal) AS FormattedSubtotal while continuing to sort by Subtotal.

ContentLicense: CC BY-SA 4.0

Body:
In SQLite, a column of numbers have been orderd in descending order by:

ORDER BY Subtotal DESC

Is there a way to add a prefix after the numbers have been ordered in descending order? For example a '$' Prefix in front of the numbers.


问:
Create a PDF file  from Excel: problem with images
I have an Excel template that I use to create PDF specification sheets for our vendors. I can open, manipulate and export to a PDF file fine except when I insert a picture. This is the code I am using to add one picture

```<code>workSheet.Shapes.AddPicture(imagePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 120, 700, image.Width, image.Height);
</code>```

and this is the code to save the PDF file:

```<code>private void createPDF()
{
     if (File.Exists(path + basePart.Number + ".pdf"))
         File.Delete(path + basePart.Number + ".pdf");
     workBook.Saved = true;
     workSheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, path + basePart.Number, Excel.XlFixedFormatQuality.xlQualityStandard, true,
                false, Type.Missing, Type.Missing, true, Type.Missing);
     DisposeExcelInstance();
}
</code>```

Without any images the PDF file saves fine. With images, the PDF file saves but cannot be opened. I have tried multiple PDF file readers just in case but sure enough none of them work.

EDIT:

I have tried various Excel formats and none have worked. It seems that ExportAsFixedFormat does not work with images, no matter how they get inserted into the document. Is there an alternative to this?

答:
Microsoft is to thank for this one. 6 hours of more or less banging my head against a wall testing on multiple computers with multiple file formats and PDF file tools I find out it is a compatibility issue with Excel 2010.

I finally got a spare laptop so I could stop bugging other people to test things on their PCs and the laptop had Excel 2007 on it and it worked like a charm. The actual issue, believe it or not, is that when working with Excel 2007 (the version that the template had originally been built in) someone had put it into the "Page Layout" view, which worked on Excel 2007 and older when creating a PDF file with a picture in it.

With Excel 2010 it will sometimes allow me to get away with the page layout view, but never with pictures. I wish I were making it up. I didn't think the view really had anything to do with the the functionality of the spreadsheet. This is a very specific problem, but hopefully someday it saves someone a headache.

ContentLicense: CC BY-SA 3.0

Body:
I have an Excel template that I use to create PDF specification sheets for our vendors. I can open, manipulate and export to a PDF file fine except when I insert a picture. This is the code I am using to add one picture

workSheet.Shapes.AddPicture(imagePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 120, 700, image.Width, image.Height);

and this is the code to save the PDF file:

private void createPDF()
{
     if (File.Exists(path + basePart.Number + ".pdf"))
         File.Delete(path + basePart.Number + ".pdf");
     workBook.Saved = true;
     workSheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, path + basePart.Number, Excel.XlFixedFormatQuality.xlQualityStandard, true,
                false, Type.Missing, Type.Missing, true, Type.Missing);
     DisposeExcelInstance();
}

Without any images the PDF file saves fine. With images, the PDF file saves but cannot be opened. I have tried multiple PDF file readers just in case but sure enough none of them work.

EDIT:

I have tried various Excel formats and none have worked. It seems that ExportAsFixedFormat does not work with images, no matter how they get inserted into the document. Is there an alternative to this?


问:
How to highlight word found using regex in javafx
I am trying to highlight a word in JavaFX that is found by Matcher and whenever new one is one I want to highlighted that new one.
Is this possible?
Here is my code:</p>

```<code>                String s1 = displayArea.getText();
                String s2 = textInputArea.getText();
                Pattern p = Pattern.compile("[a-zA-Z]*[^\\s]");
                Matcher m1 = p.matcher(s1);
                Matcher m2 = p.matcher(s2);
                int counter=0;

                System.out.println("Words from string \"" + s1 + "\" : ");
                while (m1.find() && m2.find() ) {

                    System.out.println("Found words: "+m1.group()+ " Typed words: "+m2.group() );
                    //m1.group() needs to be highlighted and displayed in textarea
                    if (m1.group().equals(m2.group())){
                        counter++;
                        System.out.println("counter:"+counter );

                    }else if (!(m1.group().equals(m2.group())) && typedKey==' '){
                            negativni++;
                            System.out.println("negativni:"+ negativni );

                    }

                }
</code>```

答:
I solved it using RichTextFX.

displayArea.setStyle(m1.start(),m1.end(),-fx-font-weight:bold;");

Body:
I am trying to highlight a word in JavaFX that is found by Matcher and whenever new one is one I want to highlighted that new one.
Is this possible?
Here is my code:

                String s1 = displayArea.getText();
                String s2 = textInputArea.getText();
                Pattern p = Pattern.compile("[a-zA-Z]*[^\\s]");
                Matcher m1 = p.matcher(s1);
                Matcher m2 = p.matcher(s2);
                int counter=0;

                System.out.println("Words from string \"" + s1 + "\" : ");
                while (m1.find() && m2.find() ) {

                    System.out.println("Found words: "+m1.group()+ " Typed words: "+m2.group() );
                    //m1.group() needs to be highlighted and displayed in textarea
                    if (m1.group().equals(m2.group())){
                        counter++;
                        System.out.println("counter:"+counter );

                    }else if (!(m1.group().equals(m2.group())) && typedKey==' '){
                            negativni++;
                            System.out.println("negativni:"+ negativni );

                    }

                }


问:
How pass data from Activity to Dialog in Android Studio
I need pass data from from MainActivity to Dialog in Android Studio so that when AlertDialog is launched, the value I have sent from the MainActivity can be shown in it. Until now with this code I have only managed to pass data from the Dialog to the MainActivity but not in the opposite way
The data i want to send is:

```<code>IPAdreess = "192.1681.1.4";
IPPort ="8089";
</code>```

Here is my MainActivity:

```<code>public class MainActivity extends AppCompatActivity implements ConfigWIFIDialog.ConfigWIFIDialogListener {
private String IPAdreess = "192.1681.1.4";
private String IPPort ="8089";
private TextView myIPAdreess;
private TextView myIPPort;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myIPAdreess = (TextView) findViewById(R.id.txv_ipAddress);
    myIPPort = (TextView) findViewById(R.id.txv_ipPort);
    button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDialog();
        }
    });
}

public void openDialog() {
    ConfigWIFIDialog configWIFIDialog = new ConfigWIFIDialog();
    configWIFIDialog.show(getSupportFragmentManager(), "example dialog");
}

@Override
public void applyTexts(String mIpAddreess, String mIpPort) {
    myIPAdreess.setText(mIpAddreess);
    myIPPort.setText(mIpPort);
}
}
</code>```

And here is the Dialog:

```<code>public class ConfigWIFIDialog extends AppCompatDialogFragment {
private EditText myIpAddress;
private EditText myIpPort;
private ConfigWIFIDialogListener listener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.config_wifi_dialog, null);

    myIpAddress = (EditText) view.findViewById(R.id.etx_ipAddress);
    myIpPort = view.findViewById(R.id.etx_ipPort);

    builder.setView(view)
            .setTitle("Configuracion WIFI")
           .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            })
            .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String mIpAddreess = myIpAddress.getText().toString();
                    String mIpPort = myIpPort.getText().toString();
                    listener.applyTexts(mIpAddreess, mIpPort);
                }
            });

    return builder.create();
}
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        listener = (ConfigWIFIDialogListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() +
                "must implement ConfigWIFIDialogListener");
    }
}
public interface ConfigWIFIDialogListener {
    void applyTexts(String mIpAddreess, String mIpPort);
}
}
</code>```

答:
You are implementing AppCompatDialogFragment, you can pass data to it by setting its arguments

```<code>public void openDialog() {
    ConfigWIFIDialog configWIFIDialog = new ConfigWIFIDialog();
    Bundle args = new Bundle();
    args.putString("title", title);
    configWIFIDialog.setArguments(args);
    configWIFIDialog.show(getSupportFragmentManager(), "example dialog");
}
</code>```

you can learn more from codepath

Body:
I need pass data from from MainActivity to Dialog in Android Studio so that when AlertDialog is launched, the value I have sent from the MainActivity can be shown in it. Until now with this code I have only managed to pass data from the Dialog to the MainActivity but not in the opposite way
The data i want to send is:

IPAdreess = "192.1681.1.4";
IPPort ="8089";

Here is my MainActivity:

public class MainActivity extends AppCompatActivity implements ConfigWIFIDialog.ConfigWIFIDialogListener {
private String IPAdreess = "192.1681.1.4";
private String IPPort ="8089";
private TextView myIPAdreess;
private TextView myIPPort;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myIPAdreess = (TextView) findViewById(R.id.txv_ipAddress);
    myIPPort = (TextView) findViewById(R.id.txv_ipPort);
    button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDialog();
        }
    });
}

public void openDialog() {
    ConfigWIFIDialog configWIFIDialog = new ConfigWIFIDialog();
    configWIFIDialog.show(getSupportFragmentManager(), "example dialog");
}

@Override
public void applyTexts(String mIpAddreess, String mIpPort) {
    myIPAdreess.setText(mIpAddreess);
    myIPPort.setText(mIpPort);
}
}

And here is the Dialog:

public class ConfigWIFIDialog extends AppCompatDialogFragment {
private EditText myIpAddress;
private EditText myIpPort;
private ConfigWIFIDialogListener listener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.config_wifi_dialog, null);

    myIpAddress = (EditText) view.findViewById(R.id.etx_ipAddress);
    myIpPort = view.findViewById(R.id.etx_ipPort);

    builder.setView(view)
            .setTitle("Configuracion WIFI")
           .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            })
            .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String mIpAddreess = myIpAddress.getText().toString();
                    String mIpPort = myIpPort.getText().toString();
                    listener.applyTexts(mIpAddreess, mIpPort);
                }
            });

    return builder.create();
}
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        listener = (ConfigWIFIDialogListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() +
                "must implement ConfigWIFIDialogListener");
    }
}
public interface ConfigWIFIDialogListener {
    void applyTexts(String mIpAddreess, String mIpPort);
}
}

Body:
You are implementing AppCompatDialogFragment, you can pass data to it by setting its arguments

public void openDialog() {
    ConfigWIFIDialog configWIFIDialog = new ConfigWIFIDialog();
    Bundle args = new Bundle();
    args.putString("title", title);
    configWIFIDialog.setArguments(args);
    configWIFIDialog.show(getSupportFragmentManager(), "example dialog");
}

you can learn more from codepath


问:
Flutter logical decission between Video and Image in UI
I'm a little bit lost in an App I'm trying to write. I'd like to display either an image, or an Video - depending on an entry in a list.

So, if the entry in the list I'm currently displaying has a video I want to use the Chewie Player in the UI

```<code>child = Chewie(
       controller: _chewieController,
)
</code>```

if the entry in the list I'm currently displaying has an image I want to use CachedNetworkImage:

```<code>CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)
</code>```

as you probably noticed, I am a programming beginner. How can I solve this problem?

Right now the code I'm trying to use in the UI looks like this:

```<code>Container(
  if (_questions[widget.questionno].getVideo()=="Ja") {
    child = Chewie(
           controller: _chewieController,
    )
  } else {
    child = CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)
  }

),
</code>```

答:
Try something like this:

```<code>bool video = false

if(entryInList is Video){ //Replace Video with whatever type you would have
                          //for Videos
  video = true
}
</code>```

And in your Widget tree

```<code>child: video ? VideoWidget() : FotoWidget()
</code>```

Or all in one line:

```<code>child: entryInList is Video ? VideoWidget() : FotoWidget()
</code>```

Body:
I'm a little bit lost in an App I'm trying to write. I'd like to display either an image, or an Video - depending on an entry in a list.

So, if the entry in the list I'm currently displaying has a video I want to use the Chewie Player in the UI

child = Chewie(
       controller: _chewieController,
)

if the entry in the list I'm currently displaying has an image I want to use CachedNetworkImage:

CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)

as you probably noticed, I am a programming beginner. How can I solve this problem?

Right now the code I'm trying to use in the UI looks like this:

Container(
  if (_questions[widget.questionno].getVideo()=="Ja") {
    child = Chewie(
           controller: _chewieController,
    )
  } else {
    child = CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)
  }

),

Body:
Try something like this:

bool video = false

if(entryInList is Video){ //Replace Video with whatever type you would have
                          //for Videos
  video = true
}

And in your Widget tree

child: video ? VideoWidget() : FotoWidget()

Or all in one line:

child: entryInList is Video ? VideoWidget() : FotoWidget()


问:
Phaser stopwatch
I have started a game and I want a stopwatch (countup timer) in it I have found a code to activate it. But how to stop it?
Source: https://docs.idew.org/video-game/project-references/phaser-coding/timers#create-count-up-timer

Code related to the stopwatch:

//global vars
var timeText; var min, sec;

function create timeText = game.add.text(600, 20, "", { fontSize: '20px', fill: '#FFF' }); timeText.fixedToCamera = true;

function displayTimeElapsed(){
    if (knight.x >= 96){
        var time = Math.floor(game.time.totalElapsedSeconds() );
        min = Math.floor(time / 60);
        sec = time % 60;
        if (min < 10) {
            min = "0" + min;
        }

        if (sec < 10) {
            sec = "0" + sec;
        }
        timeText.text = "Time: " + min + ":" + sec;
   }
}
//update displayTimeElapsed();
```

答:
Lets create it from scratch,
first of all in your create() function, lets add a text to display the timer on the screen:

// CREATE()
this.timerText = this.add.text(x, y, "").setColor("#000000");
```

<p>Second lets create a function, bellow the <code>update()</code>, to count down :</p>

<pre class="lang-js prettyprint-override"><code>showTimer(){
    // Assuming you want 60 seconds, if not just chenge the 60's for whatever time you want
    let maxTime = 60;
    let time = Math.floor(this.time.totalElapsedSeconds() );

    let sec = time % 60;

    timeText.setText(sec); // Adding the timer to our text
}
</code>```

Third, create a variable in the create() to track when the timer ends:

// CREATE()
this.timerOver = false;

// And lets start the timer
this.timer = this.time.delayedCall(60000);
```

<p>Now lets modify our <code>showTimer()</code> function:</p>

<pre class="lang-js prettyprint-override"><code>showTimer(){
    let maxTime = 60;
    let time = Math.floor(this.time.totalElapsedSeconds() );
    let timeLeft = maxTime - time; // Check how much time is left

    // When the countdown is over
    if(timeLeft <= 0){
        timeLeft = 0;
        this.timerOver = true; // Setting our variable to true
    }

    let sec = time % 60;

    timeText.setText(sec);
}
</code>```

and last, in our update() function lets check if our variable this.timerOver is true

if (this.timerOver === false){
    this.showTimer(); // Calling our function every frame
}
else {
    // Whatever you want it to do when timer comes to 0
}
```

Title: Phaser stopwatch

Body:
Lets create it from scratch,
first of all in your create() function, lets add a text to display the timer on the screen:

// CREATE()
this.timerText = this.add.text(x, y, "").setColor("#000000");

Second lets create a function, bellow the update(), to count down :

showTimer(){
    // Assuming you want 60 seconds, if not just chenge the 60's for whatever time you want
    let maxTime = 60;
    let time = Math.floor(this.time.totalElapsedSeconds() );

    let sec = time % 60;

    timeText.setText(sec); // Adding the timer to our text
}

Third, create a variable in the create() to track when the timer ends:

// CREATE()
this.timerOver = false;

// And lets start the timer
this.timer = this.time.delayedCall(60000);

Now lets modify our showTimer() function:

showTimer(){
    let maxTime = 60;
    let time = Math.floor(this.time.totalElapsedSeconds() );
    let timeLeft = maxTime - time; // Check how much time is left

    // When the countdown is over
    if(timeLeft <= 0){
        timeLeft = 0;
        this.timerOver = true; // Setting our variable to true
    }

    let sec = time % 60;

    timeText.setText(sec);
}

and last, in our update() function lets check if our variable this.timerOver is true

if (this.timerOver === false){
    this.showTimer(); // Calling our function every frame
}
else {
    // Whatever you want it to do when timer comes to 0
}


问:
Is it possible to have efficient timestamp ordered queries in spanner?
I have followed this article https://cloud.google.com/blog/products/gcp/sharding-of-timestamp-ordered-data-in-cloud-spanner and created a somewhat similar schema just without companyID:

```<code>CREATE TABLE Foo (
  random_id       STRING(22) NOT NULL,
  shard_id              INT64 NOT NULL,
  timestamp_order    TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true),
) PRIMARY KEY(random_id);
CREATE INDEX OrderIndex ON Foo(shard_id, timestamp_order);
</code>```

shard_id is a random number from 0 to 49. Then I am running a bunch of selects against it:

```<code>1: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id=0 order by timestamp_order limit 1;
# this correctly scans 1 row

2: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id<1 order by timestamp_order limit 1;
# this scans 192 rows

3: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEEN 1 AND 1 order by timestamp_order limit 1;
# this scans 185 rows

4: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEN 0 AND 1 order by timestamp_order limit 1;
# this scans 377 rows
</code>```

I expected something like this:

```<code>Query #2 should scan 1 row
Query #3 should scan 1 row
Query #4 should scan 2 rows.
</code>```

Question: what am I doing wrong here? Is it possible to have efficient timestamp ordered queries in spanner?

答:
You can get efficient execution of this query using the HAVING MIN construct.

Rewritten #2:

```<code>SELECT *
FROM
    (
    SELECT shard_id, ANY_VALUE(random_id HAVING MIN timestamp_order) AS random_id, MIN(timestamp_order) AS timestamp_order
    FROM Foo@{FORCE_INDEX=OrderIndex}
    GROUP BY shard_id
    WHERE shard_id<1
    )
ORDER BY timestamp_order
LIMIT 1;
</code>```

The efficiency will come from the inner subquery.  It should only scan one row for each shard_id and then choose the minimum from among those rows.  If you find that is not the case then there is a hint that can force that behavior.

```<code>SELECT *
FROM
    (
    SELECT shard_id, ANY_VALUE(random_id HAVING MIN timestamp_order) AS random_id, MIN(timestamp_order) AS timestamp_order
    FROM Foo@{FORCE_INDEX=OrderIndex, GROUPBY_SCAN_OPTIMIZATION=true}
    GROUP BY shard_id
    WHERE shard_id<1
    )
ORDER BY timestamp_order
LIMIT 1;
</code>```

For the other queries, just replace the filter condition in the inner subquery.

Body:
I have followed this article https://cloud.google.com/blog/products/gcp/sharding-of-timestamp-ordered-data-in-cloud-spanner and created a somewhat similar schema just without companyID:

CREATE TABLE Foo (
  random_id       STRING(22) NOT NULL,
  shard_id              INT64 NOT NULL,
  timestamp_order    TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true),
) PRIMARY KEY(random_id);
CREATE INDEX OrderIndex ON Foo(shard_id, timestamp_order);

shard_id is a random number from 0 to 49. Then I am running a bunch of selects against it:

1: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id=0 order by timestamp_order limit 1;
# this correctly scans 1 row

2: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id<1 order by timestamp_order limit 1;
# this scans 192 rows

3: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEEN 1 AND 1 order by timestamp_order limit 1;
# this scans 185 rows

4: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEN 0 AND 1 order by timestamp_order limit 1;
# this scans 377 rows

I expected something like this:

Query #2 should scan 1 row
Query #3 should scan 1 row
Query #4 should scan 2 rows.

Question: what am I doing wrong here? Is it possible to have efficient timestamp ordered queries in spanner?

Body:
You can get efficient execution of this query using the HAVING MIN construct.

Rewritten #2:

SELECT *
FROM
    (
    SELECT shard_id, ANY_VALUE(random_id HAVING MIN timestamp_order) AS random_id, MIN(timestamp_order) AS timestamp_order
    FROM Foo@{FORCE_INDEX=OrderIndex}
    GROUP BY shard_id
    WHERE shard_id<1
    )
ORDER BY timestamp_order
LIMIT 1;

The efficiency will come from the inner subquery.  It should only scan one row for each shard_id and then choose the minimum from among those rows.  If you find that is not the case then there is a hint that can force that behavior.

SELECT *
FROM
    (
    SELECT shard_id, ANY_VALUE(random_id HAVING MIN timestamp_order) AS random_id, MIN(timestamp_order) AS timestamp_order
    FROM Foo@{FORCE_INDEX=OrderIndex, GROUPBY_SCAN_OPTIMIZATION=true}
    GROUP BY shard_id
    WHERE shard_id<1
    )
ORDER BY timestamp_order
LIMIT 1;

For the other queries, just replace the filter condition in the inner subquery.


问:
Tradingview Pinescript alert not working as expected
I am using below pinescript and i am not getting alerts as expected. I am aware that it is a repainting script. It is working fine with the back testing.
Long alert is set to "Once per bar close" and short alert is set to "once per bar".

The unexpected behavior is
1) Few times, i am getting short alert though there is no corresponding long alert (though i have taken care in my script, short alert will be sent only when there is a long).
2) Multiple consecutive Short alerts per bar. I am aware that in the realtime bar, the short condition may be true multiple number of times. But since i have set alert to "once per bar", the alert should come only for the first time short condition becomes true.

Please can you let me know if i am doing anything wrong ?

Thanks in advance.

```<code>//@version=4
study("My Script",overlay = true)

ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2020, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E

firstrun = true
bought = false
longcondition = false
shortcondition = false

//Just to track first run

firstrun := firstrun[1]

if (firstrun == false)
    bought := bought[1]

//once condition is met, send a buy alert and make "bought" equal to true  //to enable selling

if (close <= 8600 and bought==false and T)
    bought := true
    longcondition :=true

alertcondition(longcondition,  "Long",  "Long")

plotshape(longcondition,  title = "Buy",  text = 'Buy',  style = shape.labelup,   location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)

if (longcondition)
    longcondition :=false

//once condition is met, sent a sell alert.

if (bought and close>=9000 and T)
    shortcondition := true
    bought := false

alertcondition(shortcondition,  "short",  "short")
plotshape(shortcondition,  title = "Sell",  text = 'Sell',  style = shape.labelup,   location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)

if (shortcondition)
    shortcondition :=false

plotchar(bought, "bought", "", location = location.top)

firstrun := false

</code>```

答:
You bought variable now automatically saves its value bar to bar and I have removed the late reinitializations of vars in your script. Seems to be working fine here:

```<code>//@version=4
study("My Script",overlay = true)

ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2000, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E

var bought = false
longcondition = false
shortcondition = false

//once condition is met, send a buy alert and make "bought" equal to true  //to enable selling
if (close <= 8600 and bought==false and T)
    bought := true
    longcondition :=true

//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
    shortcondition := true
    bought := false

alertcondition(longcondition,  "Long",  "Long")
alertcondition(shortcondition,  "short",  "short")
plotshape(longcondition,  title = "Buy",  text = 'Buy',  style = shape.labelup,   location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
plotshape(shortcondition,  title = "Sell",  text = 'Sell',  style = shape.labelup,   location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
// For debugging.
plotchar(bought, "bought", "•", location = location.top)
</code>```

Body:
I am using below pinescript and i am not getting alerts as expected. I am aware that it is a repainting script. It is working fine with the back testing.
Long alert is set to "Once per bar close" and short alert is set to "once per bar".

The unexpected behavior is
1) Few times, i am getting short alert though there is no corresponding long alert (though i have taken care in my script, short alert will be sent only when there is a long).
2) Multiple consecutive Short alerts per bar. I am aware that in the realtime bar, the short condition may be true multiple number of times. But since i have set alert to "once per bar", the alert should come only for the first time short condition becomes true.

Please can you let me know if i am doing anything wrong ?

Thanks in advance.

//@version=4
study("My Script",overlay = true)

ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2020, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E

firstrun = true
bought = false
longcondition = false
shortcondition = false

//Just to track first run

firstrun := firstrun[1]

if (firstrun == false)
    bought := bought[1]

//once condition is met, send a buy alert and make "bought" equal to true  //to enable selling

if (close <= 8600 and bought==false and T)
    bought := true
    longcondition :=true

alertcondition(longcondition,  "Long",  "Long")

plotshape(longcondition,  title = "Buy",  text = 'Buy',  style = shape.labelup,   location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)

if (longcondition)
    longcondition :=false

//once condition is met, sent a sell alert.

if (bought and close>=9000 and T)
    shortcondition := true
    bought := false

alertcondition(shortcondition,  "short",  "short")
plotshape(shortcondition,  title = "Sell",  text = 'Sell',  style = shape.labelup,   location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)

if (shortcondition)
    shortcondition :=false

plotchar(bought, "bought", "", location = location.top)

firstrun := false

Body:
You bought variable now automatically saves its value bar to bar and I have removed the late reinitializations of vars in your script. Seems to be working fine here:

//@version=4
study("My Script",overlay = true)

ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2000, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E

var bought = false
longcondition = false
shortcondition = false

//once condition is met, send a buy alert and make "bought" equal to true  //to enable selling
if (close <= 8600 and bought==false and T)
    bought := true
    longcondition :=true

//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
    shortcondition := true
    bought := false

alertcondition(longcondition,  "Long",  "Long")
alertcondition(shortcondition,  "short",  "short")
plotshape(longcondition,  title = "Buy",  text = 'Buy',  style = shape.labelup,   location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
plotshape(shortcondition,  title = "Sell",  text = 'Sell',  style = shape.labelup,   location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
// For debugging.
plotchar(bought, "bought", "•", location = location.top)


答:
bash:

prev_date="1970-01-01"
while IFS=, read -ra fields; do
    if [[ ${fields[0]} == "MISSINGDATE" ]]; then
        fields[0]=$(date -d "$prev_date + 1 day" "+%F")
    fi
    (IFS=,; echo "${fields[*]}")
    prev_date=${fields[0]}
done < file.csv
```

<p>Assuming GNU date.</p>

<p>I'd lean toward perl here (but I'm not really up for the explanation)</p>

```perl -MTime::Piece -MTime::Seconds -F, -sape '
    if ($F[0] eq "MISSINGDATE") {
        $prev += ONE_DAY;
        $F[0] = gmtime($prev)->ymd;
        $_ = join ",", @F;
    } else {
        $prev = Time::Piece->strptime($F[0], "%Y-%m-%d");
    }
' -- -prev=0 file.csv
```

Title: Way to replace NA string to Consecutive dates linux

Body:
This is CSV file that I got

2020-03-05,0,146541,118965,5766,88,35
2020-03-06,0,164740,136624,6284,108,42
MISSINGDATE,0,178189,151802,6767,118,44
2020-03-08,0,188518,162008,7134,130,50
2020-03-09,0,196618,171778,7382,166,51
MISSINGDATE,0,210144,184179,7513,247,54

I'm trying to change "MISSINGDATE" part in the column into an appropriate date that consequence with date in the previous line.

I was able to designate "MISSINGDATE" with sed command but didn't figure out to way to change it consequently.

when I did

sed -i "s/[MISSINGDATE]/[date that I want]//g" file

it only fixed NA date to date that I typed in...

the result that I want is

2020-03-05,0,146541,118965,5766,88,35
2020-03-06,0,164740,136624,6284,108,42
2020-03-07,0,178189,151802,6767,118,44
2020-03-08,0,188518,162008,7134,130,50
2020-03-09,0,196618,171778,7382,166,51
2020-03-10,0,210144,184179,7513,247,54

Body:
bash:

prev_date="1970-01-01"
while IFS=, read -ra fields; do
    if [[ ${fields[0]} == "MISSINGDATE" ]]; then
        fields[0]=$(date -d "$prev_date + 1 day" "+%F")
    fi
    (IFS=,; echo "${fields[*]}")
    prev_date=${fields[0]}
done < file.csv

Assuming GNU date.

I'd lean toward perl here (but I'm not really up for the explanation)

perl -MTime::Piece -MTime::Seconds -F, -sape '
    if ($F[0] eq "MISSINGDATE") {
        $prev += ONE_DAY;
        $F[0] = gmtime($prev)->ymd;
        $_ = join ",", @F;
    } else {
        $prev = Time::Piece->strptime($F[0], "%Y-%m-%d");
    }
' -- -prev=0 file.csv


问:
encryption and decryption with openssl AES on Linux
I want to use AES to communicate tcp/ip. However, difficulties arose in making the AES function.
In the process of decoding, dummy values are generated or the values are deleted.
I'd appreciate it if you could give me a little help.

```<code>int main(void)
{
unsigned char mykey[] = "01234567890123456789012345678\0";
unsigned  char iv[] = "0123456789012\0";
char buf[BUF_SIZE]="hi";
char enc[BUF_SIZE];
char dec[BUF_SIZE];
AES_encryption(buf,enc,mykey,iv);
AES_decryption(enc,dec,mykey,iv);
printf("buf : %s\n",buf);
printf("enc: %s\n",enc);
printf("dec: %s\n", dec);
return 0;
}

void AES_encryption(char plainfn[], char cipherfn[], unsigned char key[],unsigned char iv[])
   {

    EVP_CIPHER_CTX ctx;
    int in_len, out_len=0;
    in_len=strlen(plainfn);
    EVP_CIPHER_CTX_init(&ctx);
    EVP_CipherInit_ex(&ctx,EVP_aes_128_cbc(),NULL,key,iv,AES_ENCRYPT);
    EVP_CipherUpdate(&ctx,cipherfn,&out_len,plainfn,in_len);
    EVP_CipherFinal_ex(&ctx,cipherfn,&out_len);

    EVP_CIPHER_CTX_cleanup(&ctx);
    }

void AES_decryption(char cipherfn[], char plainfn[], unsigned char key[], unsigned char iv[])
    {

    EVP_CIPHER_CTX ctx;
    int in_len, out_len=0;
    in_len=strlen(cipherfn);
    EVP_CIPHER_CTX_init(&ctx);
    EVP_CipherInit_ex(&ctx,EVP_aes_128_cbc(),NULL,key,iv,AES_DECRYPT);
    EVP_CipherUpdate(&ctx,plainfn,&out_len,cipherfn,in_len);
    EVP_CipherFinal_ex(&ctx,plainfn,&out_len);
    EVP_CIPHER_CTX_cleanup(&ctx);
    }
</code>```

These results come out.
buf : hi
enc: U▒▒B▒ac▒▒]▒▒▒▒Y▒-
dec: hi▒?!▒

答:
The main problem is that AES_encryption is likely put NULL chars to the enc buffer. You then count the scrambled enc buffer "string length" via strlen() in AES_decryption. This is certainly wrong since decryption can stop too early thus not reading the entire input buffer.

You should probably pass an buffer size argument to encrypt and decrypt functions to properly encrypt/decrypt the buffer(s).
Calculate the string length before encryption and some how pass the same buffer length also to the decryption stage. You probably have to encode the string length in your buf before the actual data.

Also since enc buffer is by definition scrambled you can't just printf("%s",enc) it for the same reason strlen() doesn't work for it. You need to print the chars one by one by putchar() or some other way that is immune to null chars.

Body:
I want to use AES to communicate tcp/ip. However, difficulties arose in making the AES function.
In the process of decoding, dummy values are generated or the values are deleted.
I'd appreciate it if you could give me a little help.

int main(void)
{
unsigned char mykey[] = "01234567890123456789012345678\0";
unsigned  char iv[] = "0123456789012\0";
char buf[BUF_SIZE]="hi";
char enc[BUF_SIZE];
char dec[BUF_SIZE];
AES_encryption(buf,enc,mykey,iv);
AES_decryption(enc,dec,mykey,iv);
printf("buf : %s\n",buf);
printf("enc: %s\n",enc);
printf("dec: %s\n", dec);
return 0;
}

void AES_encryption(char plainfn[], char cipherfn[], unsigned char key[],unsigned char iv[])
   {

    EVP_CIPHER_CTX ctx;
    int in_len, out_len=0;
    in_len=strlen(plainfn);
    EVP_CIPHER_CTX_init(&ctx);
    EVP_CipherInit_ex(&ctx,EVP_aes_128_cbc(),NULL,key,iv,AES_ENCRYPT);
    EVP_CipherUpdate(&ctx,cipherfn,&out_len,plainfn,in_len);
    EVP_CipherFinal_ex(&ctx,cipherfn,&out_len);

    EVP_CIPHER_CTX_cleanup(&ctx);
    }

void AES_decryption(char cipherfn[], char plainfn[], unsigned char key[], unsigned char iv[])
    {

    EVP_CIPHER_CTX ctx;
    int in_len, out_len=0;
    in_len=strlen(cipherfn);
    EVP_CIPHER_CTX_init(&ctx);
    EVP_CipherInit_ex(&ctx,EVP_aes_128_cbc(),NULL,key,iv,AES_DECRYPT);
    EVP_CipherUpdate(&ctx,plainfn,&out_len,cipherfn,in_len);
    EVP_CipherFinal_ex(&ctx,plainfn,&out_len);
    EVP_CIPHER_CTX_cleanup(&ctx);
    }

These results come out.
buf : hi
enc: U▒▒B▒ac▒▒]▒▒▒▒Y▒-
dec: hi▒?!▒


问:
Conversion from double to string in c++
I'm currently coding a project for my Computer Science module but I'm having the problem of my string value defaulting to scientific notation if there are too many decimal places in the double value.

I've tried the obvious solution with ostringstream and .str() but it makes it into notation. I have to compile to the C++98 standard, so I cannot use modern solutions like std::to_string.

I need the value to be casted into a string but it needs to maintain its formatting. any help would be appreciated.

答:
If you use at least C++17, you could use std::to_chars() from #include <charconv>.

// `512` is here arbitrary, it is the max size of the output string.
// Smaller values should be sufficient.
char buffer[512];
// Here 'std::chars_format::fixed' tells the `std::to_chars()` to
// not use the scientific notation.
char* end = std::to_chars(std::begin(buffer), std::end(buffer), myDouble, std::chars_format::fixed).ptr;
// `end` the one-past-the-end pointer of the characters written to `buffer`.
```

This method is probably faster than the Emilien Lemaire's answer, however it's more verbose, and more error-prone. So this answer is only provided for completeness (as the performance gain may not worth it).

Moreover, unlike std::to_string(), the output string is locale-insensitive, so the double will always be formatted in the C locale (english locale).

Title: Conversion from double to string in c++

Body:
If you use at least C++17, you could use std::to_chars() from #include <charconv>.

// `512` is here arbitrary, it is the max size of the output string.
// Smaller values should be sufficient.
char buffer[512];
// Here 'std::chars_format::fixed' tells the `std::to_chars()` to
// not use the scientific notation.
char* end = std::to_chars(std::begin(buffer), std::end(buffer), myDouble, std::chars_format::fixed).ptr;
// `end` the one-past-the-end pointer of the characters written to `buffer`.

This method is probably faster than the Emilien Lemaire's answer, however it's more verbose, and more error-prone. So this answer is only provided for completeness (as the performance gain may not worth it).

Moreover, unlike std::to_string(), the output string is locale-insensitive, so the double will always be formatted in the C locale (english locale).


问:
How to avoid no Access-Control-Allow-Origin header is present on the requested resource
I have a webapp that is running on NGINX and it is secured with Keycloak. After successfully sign in through the Keycloak login, it redirects me to the webapp as expected.

However, when I look into the web browser console it shows the following error messages:

The Web Origins is configured as:

How to avoid the error message? Do I miss any configuration on NGINX?

Hint, the webapp is developed by https://quasar.dev/.

答:
You didn't configure Keycloak OIDC client correctly, so Keycloak didn't set proper CORS headers.

https://dev.oidc.databaker.io/* is not valid origin (/* at the end is a problem). https://dev.oidc.databaker.io is correct origin. But you will see that different origin was used, when you check error from the browse console. It looks like https://dev.databaker.io was used. So configure web origin of used Keycloak OIDC client properly and CORS issue should be solved.


问:
How do I solve this inheritance problem in rust?
first of all the obligatory "I am new to Rust": I am.

So I have the following problem:

I have two(or more) structs of data, that all implement some common behaviour in addition their own behaviour. I have a list of these structs (or rather: of the 'supertype'), I need to access some of their shared behaviour and some of their individual behaviour.
My Question is: how do I do that in Rust.

To further illustrate my question I have come up with a code comparision between Kotlin and Rust. Kotlin works as I want it to, Rust does not (yet).

In Kotlin the code may look like this(using the plain, old inheritance abstraction):

```<code>interface Animal {
    fun eat()
    fun sleep()
}
class Cat(val name: String) : Animal {
    fun meow()              { println("meow") }

    override fun eat()      { println("cat $name is eating fish(or lasagne)") }
    override fun sleep()    { println("cat $name sleeps inside") }
}
class Lion(val tag_id: Int) : Animal {
    fun roar()              { println("roar") }

    override fun eat()      { println("lion(tag=${tag_id} is eating gazelle") }
    override fun sleep()    { println("lion(tag=${tag_id} sleeps outside") }
}

var animals: MutableList<Animal> = ArrayList()
fun main() {
    animals.add(Cat("Garfield"))
    animals.add(Lion(12))
    //later:
    for (animal in animals) {
        animal.sleep()
        if (animal is Lion)
            animal.roar()
    }
}
</code>```

In Rust I came up with the following code (which does not allow an 'instance_of' type function):

```<code>trait Animal {
    fn eat(&self);
    fn sleep(&self);
}

struct Cat {
    name: String
}
impl Cat {
    fn meow(&self)      { println!("meow") }
}
impl Animal for Cat {
    fn eat(&self)       { println!("cat {} is eating fish(or lasagne)", self.name) }
    fn sleep(&self)     { println!("cat {} sleeps inside", self.name) }
}

struct Lion {
    tag_id: usize
}
impl Lion {
    fn roar(&self)      { println!("roar") }
}
impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![
                Box::new(Cat {name: "Garfield".to_string()}),
                Box::new(Lion {tag_id: 12})
    ];
    //later:
    for animal in animals {
        animal.sleep()
        //HOW DO I ACCESS THE CONCRETE STRUCT HERE?
    }
}
</code>```

Playground

I realize this may be a stupid question, or show how I am 'still trapped in the non-Rust thinking', but I am at kind of an Impass here and need just a little bit of assistence.

答:
Try doing it with composition instead

```<code>trait Animal {
    fn voicebox(&self) -> Voicebox;
}
enum Voicebox {
    CatVoicebox, LionVoicebox
}

impl Voicebox {
    fn make_sound(&self) {
        match *self {
            Voicebox::CatVoicebox => println!("meow"),
            Voicebox::LionVoicebox => println!("roar!")
        }
    }
}

impl Animal for Cat {
    fn voicebox(&self) -> Voicebox {
      Voicebox::CatVoicebox
    }
}

impl Animal for Lion {
    fn voicebox(&self) -> Voicebox {
        Voicebox::LionVoicebox
    }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![Box::new(Cat {name: "Garfield".to_string()}), Box::new(Lion {tag_id: 12})];
    //later:
    for animal in animals {
        animal.sleep();
        match animal.voicebox() {
            vb@Voicebox::LionVoicebox => vb.make_sound(),
            _ => ()
        }
    }
}
</code>```

Output:

```<code>cat Garfield sleeps inside
lion(tag=12) sleeps inside
roar!
</code>```

Rust playground

Body:
first of all the obligatory "I am new to Rust": I am.

So I have the following problem:

I have two(or more) structs of data, that all implement some common behaviour in addition their own behaviour. I have a list of these structs (or rather: of the 'supertype'), I need to access some of their shared behaviour and some of their individual behaviour.
My Question is: how do I do that in Rust.

To further illustrate my question I have come up with a code comparision between Kotlin and Rust. Kotlin works as I want it to, Rust does not (yet).

In Kotlin the code may look like this(using the plain, old inheritance abstraction):

interface Animal {
    fun eat()
    fun sleep()
}
class Cat(val name: String) : Animal {
    fun meow()              { println("meow") }

    override fun eat()      { println("cat $name is eating fish(or lasagne)") }
    override fun sleep()    { println("cat $name sleeps inside") }
}
class Lion(val tag_id: Int) : Animal {
    fun roar()              { println("roar") }

    override fun eat()      { println("lion(tag=${tag_id} is eating gazelle") }
    override fun sleep()    { println("lion(tag=${tag_id} sleeps outside") }
}

var animals: MutableList<Animal> = ArrayList()
fun main() {
    animals.add(Cat("Garfield"))
    animals.add(Lion(12))
    //later:
    for (animal in animals) {
        animal.sleep()
        if (animal is Lion)
            animal.roar()
    }
}

In Rust I came up with the following code (which does not allow an 'instance_of' type function):

trait Animal {
    fn eat(&self);
    fn sleep(&self);
}

struct Cat {
    name: String
}
impl Cat {
    fn meow(&self)      { println!("meow") }
}
impl Animal for Cat {
    fn eat(&self)       { println!("cat {} is eating fish(or lasagne)", self.name) }
    fn sleep(&self)     { println!("cat {} sleeps inside", self.name) }
}

struct Lion {
    tag_id: usize
}
impl Lion {
    fn roar(&self)      { println!("roar") }
}
impl Animal for Lion {
    fn eat(&self)       { println!("lion(tag={}) is eating fish(or lasagne)", self.tag_id) }
    fn sleep(&self)     { println!("lion(tag={}) sleeps inside", self.tag_id) }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![
                Box::new(Cat {name: "Garfield".to_string()}),
                Box::new(Lion {tag_id: 12})
    ];
    //later:
    for animal in animals {
        animal.sleep()
        //HOW DO I ACCESS THE CONCRETE STRUCT HERE?
    }
}

Playground

I realize this may be a stupid question, or show how I am 'still trapped in the non-Rust thinking', but I am at kind of an Impass here and need just a little bit of assistence.

Body:
Try doing it with composition instead

trait Animal {
    fn voicebox(&self) -> Voicebox;
}
enum Voicebox {
    CatVoicebox, LionVoicebox
}

impl Voicebox {
    fn make_sound(&self) {
        match *self {
            Voicebox::CatVoicebox => println!("meow"),
            Voicebox::LionVoicebox => println!("roar!")
        }
    }
}

impl Animal for Cat {
    fn voicebox(&self) -> Voicebox {
      Voicebox::CatVoicebox
    }
}

impl Animal for Lion {
    fn voicebox(&self) -> Voicebox {
        Voicebox::LionVoicebox
    }
}

fn main() {
    let animals:Vec<Box<dyn Animal>> = vec![Box::new(Cat {name: "Garfield".to_string()}), Box::new(Lion {tag_id: 12})];
    //later:
    for animal in animals {
        animal.sleep();
        match animal.voicebox() {
            vb@Voicebox::LionVoicebox => vb.make_sound(),
            _ => ()
        }
    }
}

Output:

cat Garfield sleeps inside
lion(tag=12) sleeps inside
roar!

Rust playground


问:
How to set the width of a column of a dynamic HTML table
I have code as below

```<code> <table >
    <thead >
        <th *ngFor="let col of workData.columns;trackBy: trackByColumn;
            let hindex=index;" [ngClass]="setWidth(col)" [index]="hindex">
        </th>
    </thead>
</table>

 //TS File

  setWidth(col){
   if(col.field === 'First Name') {
   col.width = '100px';
 }
}
</code>```

In the above table, I get both column names List and column Data from the Http call and render the table based on it.
How do I dynamically set width for each column based on its name.

for ex:

Column: First Name    Width:100px
 Column: Last Name     Width:90px
 Column:  Address      Width: 150px

I am using Angular 6. I tried javascript solutions and also with ngClass and ngStyle in angular. But I am not able to get a handle on how to set width to each of the columns.

答:
You can create a JSON object widht a 'style' attribute like this:

      workData = {
       columns: [
       {
        field: "First Name",
        style: {
          width: "100px",
          "background-color": "red",
          color: "white"
        }
      },
      {
        field: "Last Name",
        style: {
          width: "200px",
          "background-color": "blue",
          color: "white"
        }
      },
      {
        field: "Address",
        style: {
          width: "300px",
          "background-color": "yellow",
          color: "black"
        }
      }
    ]};

then in your file.html

```<code><table>
 <thead>
  <th [ngStyle]="col.style" *ngFor="let col of workData.columns;">{{col.field}}</th>
 </thead>
</table>
</code>```

now you can add more than one style on your table

click here to see it running

Body:
I have code as below

 //TS File

  setWidth(col){
   if(col.field === 'First Name') {
   col.width = '100px';
 }
}

In the above table, I get both column names List and column Data from the Http call and render the table based on it.
How do I dynamically set width for each column based on its name.

for ex:

Column: First Name    Width:100px
 Column: Last Name     Width:90px
 Column:  Address      Width: 150px

I am using Angular 6. I tried javascript solutions and also with ngClass and ngStyle in angular. But I am not able to get a handle on how to set width to each of the columns.

Body:
You can create a JSON object widht a 'style' attribute like this:

      workData = {
       columns: [
       {
        field: "First Name",
        style: {
          width: "100px",
          "background-color": "red",
          color: "white"
        }
      },
      {
        field: "Last Name",
        style: {
          width: "200px",
          "background-color": "blue",
          color: "white"
        }
      },
      {
        field: "Address",
        style: {
          width: "300px",
          "background-color": "yellow",
          color: "black"
        }
      }
    ]};

then in your file.html

<table>
 <thead>
  <th [ngStyle]="col.style" *ngFor="let col of workData.columns;">{{col.field}}</th>
 </thead>
</table>

now you can add more than one style on your table

click here to see it running


问:
Access clipboard in Windows batch file
Any idea how to access the Windows clipboard using a batch file?</p>

答:
Multiple lines

The problem is resolved, but disappointment remains.

I was forced to split one command into two.

First of them well understands the text and service characters, but does not understand the backspace.

The second understands backspace, but does not understand many service characters.

Can anyone unite them?

Notepad ++, in the place where it should open, is commented out because sometimes the window does not get access to enter characters and therefore you need to make sure that it is active.

Of course, it is better to enter characters using the PID of the notebook process, but ...

The request from wmic opens for a long time, so do not close the notepad window until the bat file is closed.

```<code>    @echo off
    set "like=Microsoft Visual C++"
    set "flag=0"
    start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst
    ( set LF=^
    %= NEWLINE =%
    )
    set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"
    ::------------------
    setlocal enabledelayedexpansion
    for /f "usebackq delims=" %%i in ( `wmic /node:"papa" product where "Name like '%%%like%%%'" get * ^| findstr /r /v "^$"`) do (
        for /f tokens^=1^ delims^=^" %%a in ("%%i") do set str=%%a
        if "!flag!"=="0" (
            ::start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst& set "flag=1"
            for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('{BS}{BS}{BS}{BS}');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
            set flag=1
        )
        @set /P "_=%%str%%"<NUL|clip
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
        (echo %%NL%%)|clip
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
    )
    setlocal disabledelayedexpansion
</code>```

Title: Access clipboard in Windows batch file

Body:
Multiple lines

The problem is resolved, but disappointment remains.

I was forced to split one command into two.

First of them well understands the text and service characters, but does not understand the backspace.

The second understands backspace, but does not understand many service characters.

Can anyone unite them?

Notepad ++, in the place where it should open, is commented out because sometimes the window does not get access to enter characters and therefore you need to make sure that it is active.

Of course, it is better to enter characters using the PID of the notebook process, but ...

The request from wmic opens for a long time, so do not close the notepad window until the bat file is closed.

    @echo off
    set "like=Microsoft Visual C++"
    set "flag=0"
    start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst
    ( set LF=^
    %= NEWLINE =%
    )
    set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"
    ::------------------
    setlocal enabledelayedexpansion
    for /f "usebackq delims=" %%i in ( `wmic /node:"papa" product where "Name like '%%%like%%%'" get * ^| findstr /r /v "^$"`) do (
        for /f tokens^=1^ delims^=^" %%a in ("%%i") do set str=%%a
        if "!flag!"=="0" (
            ::start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst& set "flag=1"
            for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('{BS}{BS}{BS}{BS}');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
            set flag=1
        )
        @set /P "_=%%str%%"<NUL|clip
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
        (echo %%NL%%)|clip
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
    )
    setlocal disabledelayedexpansion


问:
Cypher commands not being recognised
I'm using Neo4j for a project, when I try to run SHOW DATABASES, I get this error:

```<code>Invalid input 'H': expected 't/T', 'e/E' or 'n/N' (line 1, column 2 (offset: 1))

"SHOW DATABASES"
</code>```

I'm running Neo4j Browser version: 4.0.3.

Why is this function not recognized? It's referenced multiple times in the docs. I have no issues running other queries with different commands, but this is not recognized.

How can I solve this problem?

答:
SHOW DATABASES command is against the system database. Please see the following excerpt from https://neo4j.com/docs/operations-manual/4.0/monitoring/individual-db-states/

13.7.1. Listing Databases
First ensure that you are executing queries against the system database, either by running the command :use system (if using the Cypher shell or Neo4j Browser) or by creating a session against the system database using a Neo4j driver. Subsequently, run the SHOW DATABASES command.

Syntax:

SHOW DATABASES

Title: Cypher commands not being recognised

Body:
I'm using Neo4j for a project, when I try to run SHOW DATABASES, I get this error:

Invalid input 'H': expected 't/T', 'e/E' or 'n/N' (line 1, column 2 (offset: 1))

"SHOW DATABASES"

I'm running Neo4j Browser version: 4.0.3.

Why is this function not recognized? It's referenced multiple times in the docs. I have no issues running other queries with different commands, but this is not recognized.

How can I solve this problem?


问:
Replacing columns with different Dataframe
I have two dataframes,namely 'df' and 'df1'

```<code>df
Out[14]:
      first country  Rating
0    Robert      US     100
1     Chris     Aus      99
2  Scarlett      US     100

df1
Out[17]:
        last        Role
0     Downey     IronMan
1  Hemsworth        Thor
2  Johansson  BlackWidow
</code>```

Expected output:

```<code>      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100
</code>```

I need to drop off the 'country' column and replace with another dataframe(ie. 'df1')

I understand,I can join dataframes and drop 'country' column,but I need columns exactly in this order.

答:
IIUC:</p>

```<code>new_df = df.merge(df1, on='Role').drop('country', axis=1)
new_df = new_df[['first', 'last', 'Role', 'Rating']]
</code>```

Body:
I have two dataframes,namely 'df' and 'df1'

df
Out[14]:
      first country  Rating
0    Robert      US     100
1     Chris     Aus      99
2  Scarlett      US     100

df1
Out[17]:
        last        Role
0     Downey     IronMan
1  Hemsworth        Thor
2  Johansson  BlackWidow

Expected output:

      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100

I need to drop off the 'country' column and replace with another dataframe(ie. 'df1')

I understand,I can join dataframes and drop 'country' column,but I need columns exactly in this order.

Body:
IIUC:

new_df = df.merge(df1, on='Role').drop('country', axis=1)
new_df = new_df[['first', 'last', 'Role', 'Rating']]


问:
Particles are in front of UI elements in unity
So all i'm looking for is simple. I want the UI elements such as Buttons/Logo/..etc to be in front any particle effects in the Canvas.

In the answer Here someone suggested to add a canvas component to each and every UI element I want to show in front of the particles and that work somehow the only problem in this way the buttons won't click at all.

All elements are on the default sorting layer including the particles object and the camera.

Is that hard to do that?

Please help.

答: set "Order in layer" of Particles to 0 and UI elements to 1 or a better way of doing this is to go to add new layers, create a foreground and background layer, set foreground to 1 and background to 0 and then change from the default layer to which ever you want in front or back.</p>


问:
int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here? I know how to find the size of array
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element. </p>

```<code>
int main()
{
    int array[10] = {1, 2, 0, 3, 4};

    printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array

    int i = 0;

    while(array[i] != 0  && i < 10) {
        i++;
    };

    printf("%d\n", i);

    return 0;
}```
</code>```

答:
int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here?

How can you say there are 4 elements there as you declared that int array[10] with the size of 10 elements. This implies, you already know the no. of elements. Also, in this scenario, you can't use an if statement to determine the no. of elements as you probably know that in C, if you initialize an array of 10 elements with less than 10 values, rest of them will automatically be assigned to 0.

Body:
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element.

int main()
{
    int array[10] = {1, 2, 0, 3, 4};

    printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array

    int i = 0;

    while(array[i] != 0  && i < 10) {
        i++;
    };

    printf("%d\n", i);

    return 0;
}```


问:
Increment hex string
I'm trying to increment an hex string like this:

```
#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;
```

Here's my procedure:

```<code>var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;
</code>```

Whith this procedure, only the second byte increment.
The result is:

```
#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1
```

Thanks

答:
You could also do this by creating a "variant record" and just using Inc();

```<code>type
  testrec = record
    case Byte of
      0: (data: array[0..3] of AnsiChar);
      1: (intSequence: Integer);
  end;
var
  Sequence: testrec;
begin
  Sequence.data = #$b1#$87#$1c#$67; // reversed because of "endian-ness"
  Inc(Sequence.intSequence);
end;
</code>```

In this case, the data and intSequence fields "overlay" each other in memory, so any writes to one field will immediately reflect in the other.

ContentLicense: CC BY-SA 2.5

Title: Increment hex string

Body:
I'm trying to increment an hex string like this:

#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;

Here's my procedure:

var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;

Whith this procedure, only the second byte increment.
The result is:

#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1

Thanks

LastEditorDisplayName: Tomalak

Body:
You could also do this by creating a "variant record" and just using Inc();

type
  testrec = record
    case Byte of
      0: (data: array[0..3] of AnsiChar);
      1: (intSequence: Integer);
  end;
var
  Sequence: testrec;
begin
  Sequence.data = #$b1#$87#$1c#$67; // reversed because of "endian-ness"
  Inc(Sequence.intSequence);
end;

In this case, the data and intSequence fields "overlay" each other in memory, so any writes to one field will immediately reflect in the other.

OwnerDisplayName: Allen Bauer

LastEditorDisplayName: Allen Bauer


问:
upload image to S3 presigned url using react-native-image-picker and axios
I am trying to get an presigned url image upload working correctly. Currently the upload succeeds when selecting an image from the IOS simulator, however when I actually try to view the file it seems the file is corrupted and will not open as an image. I suspect it has something to do with my FormData but not sure.

```<code>export async function receiptUpload(file) {

  const date = new Date();
  const headers = await getAWSHeaders();

  const presignUrl = await request.post(
      urls.fileUpload.presignUpload,
      {file_name: `${date.getTime()}.jpg`},
      {headers}
    )
    .then(res => res.data);

  const formData = new FormData();
  formData.append('file', {
    name: `${date.getTime()}.jpg`,
    uri: file.uri,
    type: file.type
  });

  const fileUpload = presignUrl.presignUrl && await request.put(
      presignUrl.presignUrl,
      formData
    )
    .then(res => res.status === 200);

}
</code>```

I have tried from other fixes to change the file uri like so...

Platform.OS === 'android' ? file.uri : file.uri.replace('file://', '');

however this does not seem to work either.

答:
I did this just recently in my current project and the following code is a working example for my use case.  I didn't need to convert to a blob either though I am uploading to AWS S3 so if you are uploading elsewhere that may be the issue.

```<code>export const uploadMedia = async (fileData, s3Data, setUploadProgress = () => {}) => {
    let sendData = { ...fileData };
    sendData.data.type = sendData.type;

    let formData = new FormData();

    formData.append('key', s3Data.s3Key);
    formData.append('Content-Type', fileData.type);
    formData.append('AWSAccessKeyId', s3Data.awsAccessKey);
    formData.append('acl', 'public-read');
    formData.append('policy', s3Data.s3Policy);
    formData.append('signature', s3Data.s3Signature);

    formData.append('file', sendData.data);

    return axios({
        method: 'POST',
        url: `https://${s3Data.s3Bucket}.s3.amazonaws.com/`,
        data: formData,
        onUploadProgress: progressEvent => {
            let percentCompleted = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
            setUploadProgress(percentCompleted);
        }
    })
}
</code>```

I would first check to see where the issue is occurring.  After uploading can you view it on whatever storage service you are trying to upload it to.  If so it's something on React Native side.  If it doesn't ever get uploaded to the location you know its an error in your upload process.  Might help you track the exact location of the error.

Body:
I am trying to get an presigned url image upload working correctly. Currently the upload succeeds when selecting an image from the IOS simulator, however when I actually try to view the file it seems the file is corrupted and will not open as an image. I suspect it has something to do with my FormData but not sure.

export async function receiptUpload(file) {

  const date = new Date();
  const headers = await getAWSHeaders();

  const presignUrl = await request.post(
      urls.fileUpload.presignUpload,
      {file_name: `${date.getTime()}.jpg`},
      {headers}
    )
    .then(res => res.data);

  const formData = new FormData();
  formData.append('file', {
    name: `${date.getTime()}.jpg`,
    uri: file.uri,
    type: file.type
  });

  const fileUpload = presignUrl.presignUrl && await request.put(
      presignUrl.presignUrl,
      formData
    )
    .then(res => res.status === 200);

}

I have tried from other fixes to change the file uri like so...

Platform.OS === 'android' ? file.uri : file.uri.replace('file://', '');

however this does not seem to work either.

Body:
I did this just recently in my current project and the following code is a working example for my use case.  I didn't need to convert to a blob either though I am uploading to AWS S3 so if you are uploading elsewhere that may be the issue.

export const uploadMedia = async (fileData, s3Data, setUploadProgress = () => {}) => {
    let sendData = { ...fileData };
    sendData.data.type = sendData.type;

    let formData = new FormData();

    formData.append('key', s3Data.s3Key);
    formData.append('Content-Type', fileData.type);
    formData.append('AWSAccessKeyId', s3Data.awsAccessKey);
    formData.append('acl', 'public-read');
    formData.append('policy', s3Data.s3Policy);
    formData.append('signature', s3Data.s3Signature);

    formData.append('file', sendData.data);

    return axios({
        method: 'POST',
        url: `https://${s3Data.s3Bucket}.s3.amazonaws.com/`,
        data: formData,
        onUploadProgress: progressEvent => {
            let percentCompleted = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
            setUploadProgress(percentCompleted);
        }
    })
}

I would first check to see where the issue is occurring.  After uploading can you view it on whatever storage service you are trying to upload it to.  If so it's something on React Native side.  If it doesn't ever get uploaded to the location you know its an error in your upload process.  Might help you track the exact location of the error.


问:
Loss of data while storing Spark data frame in parquet format
I have a csv data file which I can load into pyspark:

```<code>spark = SparkSession.builder.master("local").appName("MYAPP").getOrCreate()```

df = spark.read.csv( path = csvfilepath, sep="|", schema=my_schema, nullValue="NULL", mode="DROPMALFORMED")```
</code>```

Checking the number of rows of the data frame gives approximately 20 millions rows.

```<code>df.count()
</code>```

I re-store my data frame in parquet:

```<code>df.write.mode("overwrite").parquet( parquetfilepath )
</code>```

I then load the parquet data:

```<code>df = spark.read.parquet( parquetfilepath )
</code>```

Now when I count the rows (df.count()) I only get 3 million rows.

Why did I lose 85% of the rows and how can I solve this problem? I have also tried to use "repartition" and "coalesce" when creating the parquet data with the same result.

答: I am answering my own question as I have now understood what the problem is. It is actually a very simple beginner's mistake. The reason that I lose data is simply because I have asked for it when the df is read with the option mode="DROPMALFORMED". When I count the rows of the date frame I find that it is 20 millions rows, but some of them are inconsistent with the schema and are dropped when the data is actually written down to disk (i.e. the dropping of malformed rows which I requested when reading the csv has been deferred to this point). What I didn't realize was that there were errors in my data.</p>

Body:
I have a csv data file which I can load into pyspark:

spark = SparkSession.builder.master("local").appName("MYAPP").getOrCreate()```

df = spark.read.csv( path = csvfilepath, sep="|", schema=my_schema, nullValue="NULL", mode="DROPMALFORMED")```

Checking the number of rows of the data frame gives approximately 20 millions rows.

df.count()

I re-store my data frame in parquet:

df.write.mode("overwrite").parquet( parquetfilepath )

I then load the parquet data:

df = spark.read.parquet( parquetfilepath )

Now when I count the rows (df.count()) I only get 3 million rows.

Why did I lose 85% of the rows and how can I solve this problem? I have also tried to use "repartition" and "coalesce" when creating the parquet data with the same result.


问:
Bulk Insert with child entities using EF6 extensions
I'm getting an error everytime I try to bulk insert using EF6 Extensions library

When using IncludeGraph, some options must be set in the IncludeGraphBuilder (See:
    https://entityframework-extensions.net/include-graph). The following options must be specified in IncludeGraphBuilder: ColumnPrimaryKeyExpression, LambdaPrimaryKeyExpression

The schema is as follows

Customer(PK,____,AddressId)

CustomerAddress(PK,____,AddressLookupId)

CustomerPhone(PK,___,CustomerId)

AddressCities(PK,CityName)

AddressLookup(PK,Zip,CityId, StateId)

I have the following as a lookup table

AddressStates(PK,_____)

options for filling the data as follows

```<code>options.InsertIfNotExists = true;
options.IncludeGraph = true;
options.IncludeGraphOperationBuilder = operation =>
                {
                    switch (operation)
                    {
                      case BulkOperation<Customer> customer:
                            customer.InsertIfNotExists = true;
                            customer.ColumnPrimaryKeyExpression = x => new {
                            x.FirstName, x.MiddleName, x.LastName};
                            customer.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerAddress> customerAddress:
                            customerAddress.InsertIfNotExists = true;
                            customerAddress.ColumnPrimaryKeyExpression = x =>
                            new { x.Address };
                            customerAddress.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerPhone> customerPhone:
                            customerPhone.InsertIfNotExists = true;
                            customerPhone.ColumnPrimaryKeyExpression = x =>
                            x.PhoneNumber;
                            //customerPhone.LambdaPrimaryKeyExpression =
                            customerPhone.AutoMapIdentityExpression;
                            customerPhone.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressCity> addressCity:
                            addressCity.InsertIfNotExists = true;
                            addressCity.ColumnPrimaryKeyExpression = x =>
                            x.City;
                            //addressCity.LambdaPrimaryKeyExpression =
                            addressCity.AutoMapIdentityExpression;
                            addressCity.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressLookup> addressLookup:
                            addressLookup.InsertIfNotExists = true;
                            addressLookup.ColumnPrimaryKeyExpression = x =>
                          new { x.Zip, x.CityId, x.StateId };
                            //addressLookup.LambdaPrimaryKeyExpression =
                            addressLookup.AutoMapIdentityExpression;
                            addressLookup.AutoMapOutputDirection = true;
                            break;
</code>```

I also tried setting the ColumnPrimaryKeyExpression to map the columns that should stay unique and no luck.

Update 1 : Added the Customer options inside the graph builder, error has changed to violation of FK Constraint on City, even though it's set to only allow cities that doesn't exist.

答:
I was able to solve the problem by adding

     <EntityType>.AllowDuplicateKeys = false;

and I had a null key value in some records so I had to filter them out

Body:
I'm getting an error everytime I try to bulk insert using EF6 Extensions library

When using IncludeGraph, some options must be set in the IncludeGraphBuilder (See:
    https://entityframework-extensions.net/include-graph). The following options must be specified in IncludeGraphBuilder: ColumnPrimaryKeyExpression, LambdaPrimaryKeyExpression

The schema is as follows

Customer(PK,____,AddressId)

CustomerAddress(PK,____,AddressLookupId)

CustomerPhone(PK,___,CustomerId)

AddressCities(PK,CityName)

AddressLookup(PK,Zip,CityId, StateId)

I have the following as a lookup table

AddressStates(PK,_____)

options for filling the data as follows

options.InsertIfNotExists = true;
options.IncludeGraph = true;
options.IncludeGraphOperationBuilder = operation =>
                {
                    switch (operation)
                    {
                      case BulkOperation<Customer> customer:
                            customer.InsertIfNotExists = true;
                            customer.ColumnPrimaryKeyExpression = x => new {
                            x.FirstName, x.MiddleName, x.LastName};
                            customer.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerAddress> customerAddress:
                            customerAddress.InsertIfNotExists = true;
                            customerAddress.ColumnPrimaryKeyExpression = x =>
                            new { x.Address };
                            customerAddress.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerPhone> customerPhone:
                            customerPhone.InsertIfNotExists = true;
                            customerPhone.ColumnPrimaryKeyExpression = x =>
                            x.PhoneNumber;
                            //customerPhone.LambdaPrimaryKeyExpression =
                            customerPhone.AutoMapIdentityExpression;
                            customerPhone.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressCity> addressCity:
                            addressCity.InsertIfNotExists = true;
                            addressCity.ColumnPrimaryKeyExpression = x =>
                            x.City;
                            //addressCity.LambdaPrimaryKeyExpression =
                            addressCity.AutoMapIdentityExpression;
                            addressCity.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressLookup> addressLookup:
                            addressLookup.InsertIfNotExists = true;
                            addressLookup.ColumnPrimaryKeyExpression = x =>
                          new { x.Zip, x.CityId, x.StateId };
                            //addressLookup.LambdaPrimaryKeyExpression =
                            addressLookup.AutoMapIdentityExpression;
                            addressLookup.AutoMapOutputDirection = true;
                            break;

I also tried setting the ColumnPrimaryKeyExpression to map the columns that should stay unique and no luck.

Update 1 : Added the Customer options inside the graph builder, error has changed to violation of FK Constraint on City, even though it's set to only allow cities that doesn't exist.


问:
SwiftUI animation not working when embedded inside another view
I made a reusable circular progress bar. I applied repeatForever animation to keep it rotating but it only works when used directly with a @State or @Published variable and doesn't work when it is embedded in another view.

Reusable RingView. Which is a circular progress bar

```<code>struct RingView: View {
    private let percent: CGFloat = 80   // Keeping it fixed 80 for test purpose
    var color = Color.primaryLightColor // Some random color
    @Binding var show: Bool

    var body: some View {
        ZStack {
            GeometryReader { bounds in

                Circle()
                    .trim(from: self.show ? self.progress : 1, to: 1)
                    .stroke(
                        LinearGradient(gradient: Gradient(colors: [self.color]), startPoint: .topTrailing, endPoint: .bottomLeading),
                        style: StrokeStyle(lineWidth: self.lineWidth(width: bounds.size.width), lineCap: .round, lineJoin: .round, miterLimit: .infinity, dash: [20, 0], dashPhase: 0)
                )
                    .rotationEffect(Angle(degrees: 90))
                    .animation(.none)
                    .frame(width: bounds.size.width, height: bounds.size.height)
            }
        }
        .rotationEffect(.degrees(show ? 360.0 : 0.0))
        .animation(show ? Animation.linear(duration: 1.0).repeatForever(autoreverses: false) : .none)
    }

    func multiplier(width: CGFloat) -> CGFloat {
        width / 44
    }

    func lineWidth(width: CGFloat) -> CGFloat {
        5 * self.multiplier(width: width)
    }

    var progress: CGFloat {
        1 - (percent / 100)
    }
}
</code>```

Progress Button. It uses the RingView above. A general use case is to show animation when doing a long background task.

The RingView animation doesn't work in this ProgressButton

```<code>struct ProgressButton: View {
        var action: () -> Void
        var image: Image? = nil
        var text: String = ""
        var backgroundColor: Color = Color.blue
        var textColor: Color = .white
        @Binding var showProgress: Bool

        var body: some View {
            Button(action: action) {
                HStack {
                    if showProgress {
                        RingView(color: textColor, show: self.$showProgress)
                            .frame(width: 25, height: 25)
                        .transition(.scale)
                            .animation(.Spring())
                    } else {
                        image?
                            .renderingMode(.original)
                            .resizable()
                            .frame(width: 25, height: 25)
                    }
                    Text(text)
                        .font(.headline)
                        .foregroundColor(textColor)
                }
                .padding()
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 50, alignment: .center)
                .background(backgroundColor)
                .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))
            }.buttonStyle(PlainButtonStyle())
        }
    }
</code>```

When RingView animation works. When I use it directly as below.

```<code>struct LoginView: View {
    @State var showProgress = true
    var body: some View {
        VStack {

            // WORKING
            RingView(show: self.$showProgress)
                .frame(width: 25, height: 25)

            // NOT WORKING
            ProgressButton(action: {
                self.showProgress = true
            }, image: Image("password-lock"), text: "Login", backgroundColor: .blue, showProgress: self.showProgress)
        }
    }
}
</code>```

I think I'm doing some mistake understanding how @Binding and @State are working.

答:
Animation is activate on state change. In provided code there is no change so no animation at all.

Below are main changes so I made it work. Tested with Xcode 11.4 / iOS 13.4 (with some replication of absent custom dependencies)

Made initial animation off

```<code>struct LoginView: View {
    @State var showProgress = false

// ... other code

    // no model provided so used same state for progress
    ProgressButton(action: {
        self.showProgress.toggle()     // << activate change !!!
    }, image: Image("password-lock"), text: L.Login.LoginSecurely, backgroundColor: self.isLoginButtonEnabled ? Color.primaryLightColor : Color.gray, showProgress: $showProgress)

</code>```

Add internal ring activating state inside progress button; same state used for hide/unhide and activating does not work, again, because when ring appeared there is no change (it is already true) so ring is not activated

@State private var actiavteRing = false     // << here !!
var body: some View {
Button(action: action) {
HStack {

```<code>         if showProgress {
             RingView(color: textColor, show: self.$actiavteRing) // !!
                 .frame(width: 25, height: 25)
                 .transition(.opacity)
                 .animation(.spring())
                 .onAppear { self.actiavteRing = true } // <<
                 .onDisappear { self.actiavteRing = false } // <<
</code>```

in Ring fixed animation deactivation to avoid cumulative effect (.none does not work here), so

.rotationEffect(.degrees(show ? 360.0 : 0.0))
.animation(show ? Animation.linear(duration:
1.0).repeatForever(autoreverses: false) : .default)   // << here !!

Body:
I made a reusable circular progress bar. I applied repeatForever animation to keep it rotating but it only works when used directly with a @State or @Published variable and doesn't work when it is embedded in another view.

Reusable RingView. Which is a circular progress bar

struct RingView: View {
    private let percent: CGFloat = 80   // Keeping it fixed 80 for test purpose
    var color = Color.primaryLightColor // Some random color
    @Binding var show: Bool

    var body: some View {
        ZStack {
            GeometryReader { bounds in

                Circle()
                    .trim(from: self.show ? self.progress : 1, to: 1)
                    .stroke(
                        LinearGradient(gradient: Gradient(colors: [self.color]), startPoint: .topTrailing, endPoint: .bottomLeading),
                        style: StrokeStyle(lineWidth: self.lineWidth(width: bounds.size.width), lineCap: .round, lineJoin: .round, miterLimit: .infinity, dash: [20, 0], dashPhase: 0)
                )
                    .rotationEffect(Angle(degrees: 90))
                    .animation(.none)
                    .frame(width: bounds.size.width, height: bounds.size.height)
            }
        }
        .rotationEffect(.degrees(show ? 360.0 : 0.0))
        .animation(show ? Animation.linear(duration: 1.0).repeatForever(autoreverses: false) : .none)
    }

    func multiplier(width: CGFloat) -> CGFloat {
        width / 44
    }

    func lineWidth(width: CGFloat) -> CGFloat {
        5 * self.multiplier(width: width)
    }

    var progress: CGFloat {
        1 - (percent / 100)
    }
}

Progress Button. It uses the RingView above. A general use case is to show animation when doing a long background task.

The RingView animation doesn't work in this ProgressButton

struct ProgressButton: View {
        var action: () -> Void
        var image: Image? = nil
        var text: String = ""
        var backgroundColor: Color = Color.blue
        var textColor: Color = .white
        @Binding var showProgress: Bool

        var body: some View {
            Button(action: action) {
                HStack {
                    if showProgress {
                        RingView(color: textColor, show: self.$showProgress)
                            .frame(width: 25, height: 25)
                        .transition(.scale)
                            .animation(.Spring())
                    } else {
                        image?
                            .renderingMode(.original)
                            .resizable()
                            .frame(width: 25, height: 25)
                    }
                    Text(text)
                        .font(.headline)
                        .foregroundColor(textColor)
                }
                .padding()
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 50, alignment: .center)
                .background(backgroundColor)
                .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))
            }.buttonStyle(PlainButtonStyle())
        }
    }

When RingView animation works. When I use it directly as below.

struct LoginView: View {
    @State var showProgress = true
    var body: some View {
        VStack {

            // WORKING
            RingView(show: self.$showProgress)
                .frame(width: 25, height: 25)

            // NOT WORKING
            ProgressButton(action: {
                self.showProgress = true
            }, image: Image("password-lock"), text: "Login", backgroundColor: .blue, showProgress: self.showProgress)
        }
    }
}

I think I'm doing some mistake understanding how @Binding and @State are working.

Body:
Animation is activate on state change. In provided code there is no change so no animation at all.

Below are main changes so I made it work. Tested with Xcode 11.4 / iOS 13.4 (with some replication of absent custom dependencies)

Made initial animation off

struct LoginView: View {
    @State var showProgress = false

// ... other code

    // no model provided so used same state for progress
    ProgressButton(action: {
        self.showProgress.toggle()     // << activate change !!!
    }, image: Image("password-lock"), text: L.Login.LoginSecurely, backgroundColor: self.isLoginButtonEnabled ? Color.primaryLightColor : Color.gray, showProgress: $showProgress)

Add internal ring activating state inside progress button; same state used for hide/unhide and activating does not work, again, because when ring appeared there is no change (it is already true) so ring is not activated

@State private var actiavteRing = false     // << here !!
var body: some View {
Button(action: action) {
HStack {

         if showProgress {
             RingView(color: textColor, show: self.$actiavteRing) // !!
                 .frame(width: 25, height: 25)
                 .transition(.opacity)
                 .animation(.spring())
                 .onAppear { self.actiavteRing = true } // <<
                 .onDisappear { self.actiavteRing = false } // <<

in Ring fixed animation deactivation to avoid cumulative effect (.none does not work here), so

.rotationEffect(.degrees(show ? 360.0 : 0.0))
.animation(show ? Animation.linear(duration:
1.0).repeatForever(autoreverses: false) : .default)   // << here !!


问:
How do I use C++ STL list without iterator?
I need to get to the items in the STL list. I believe those items are of type list_item or ListItem. I need 'next' and 'prev' of each item. how do I do that?</p>

答:
For a std::list your choices are iteration and standard algorithms. There isn't a way to go forward/back from the item itself.

If you really want an intrusive list, boost does provide that. See http://www.boost.org/doc/libs/1_40_0/doc/html/intrusive/usage.html


问:
Triggering the 3cx call button of the 3cx-clicktotalk WordPress plugin
I am trying to find a way to remotely trigger the 3cx-clicktotalk call button remotely so I can use a custom button.

I have tried calling the button with jquery remote triggers but I am having no luck.

答:
You need to develop a Middleware Software which will trigger calls. You can initiate this via HTTP requests.
Look for 3cX Call Control APIs to get started.</p>


问:
How can I do vertical align in a cell with multiple data
I want to add to my cell two links and place them on a bottom of my cell.
I've tried "vertical-align:bottom" but it doesn't work in my case:

```<code>// Append database data here
$.ajax({
    type: "GET",
    url: "/Home/JsonWeekEvents",
    dataType: "JSON",
    success: function (result) {
        $.each(result, function (i, val) {
            var trow = $('<tr/>').data("id", val.Id);
            //trow.append('<td>' + val.Id + " " + '</td>');
            trow.append('<td style="padding:5px; width:100px; height:70px"></td>');

            trow.append('<td valign="top" style="padding:2px; width:150px; height:100px">' +
                '<div class="ui-widget">' +
                '<input  size="10" maxlength="10" id="tagsW" class="tags" />' +
                '<input type="button" id="addBtn" class="addEvent" size="5" value="+" /><br/>' +
                '<div style="text-align:center" id="wedVal" class="desc_NumW">' + val.Wednesday + '</div >' +
                '<input type="hidden" class="idEvent" />' +
                '<div style="vertical-align:bottom;">' +
                '<a  href="#" style="float:left;text-align:left;">Details<a/>' + '<a href="#" style="float:right;text-align:right;">Clear<a />' +
                '</div >' +
                '</div >' +
                '</td>');
</code>```

How can I solve it?

答: You might want to go with position:absolute; bottom:0; that would push it to the bottom.</p>

Body:
I want to add to my cell two links and place them on a bottom of my cell.
I've tried "vertical-align:bottom" but it doesn't work in my case:

// Append database data here
$.ajax({
    type: "GET",
    url: "/Home/JsonWeekEvents",
    dataType: "JSON",
    success: function (result) {
        $.each(result, function (i, val) {
            var trow = $('
').data("id", val.Id);
            //trow.append('' + val.Id + " " + '	');
            trow.append('	');

            trow.append('' +
                '
' +
                '<input  size="10" maxlength="10" id="tagsW" class="tags" />' +
                '<input type="button" id="addBtn" class="addEvent" size="5" value="+" />
' +
                '
' + val.Wednesday + '
' +
                '<input type="hidden" class="idEvent" />' +
                '
' +
                'Details' + 'Clear' +
                '
' +
                '
' +
                '	');

How can I solve it?