问:
How to delay page refresh after submitting a form
I have a form that uploads the profile image to wordpress. After form submit, the page is refreshed and the old image is displayed again. I have to wait about 4 or 5 seconds for the new image to appear. So I have to refresh the page 2 times to see the new image set.

I want to delay the refresh of the page but not the submission of the form, in this way I believe that you don't have to refresh the page twice to see the changes.

I tried with a script, but it doesn't work. I apologize for all this but i am new and i don't have much knowledge about php or js, can anyone help me?

```<code><form id="wpua-edit-<?php echo esc_attr( $user->ID ); ?>" class="wpua-edit" action="" method="post" enctype="multipart/form-data">

  <input type="hidden" name="wp-user-avatar" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wp-user-avatar' : 'wp-user-avatar-existing' ) ?>" value="<?php echo esc_attr( $wpua ); ?>" />

            <div class="upload-avatar" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-upload-button' : 'wpua-upload-button-existing' ); ?>">
                <input name="wpua-file" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-file' : 'wpua-file-existing' ); ?>" type="file" class="wp-input-file"/>
                <button type="submit" class="button" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-upload' : 'wpua-upload-existing' ); ?>" name="submit" value="<?php esc_html_e( 'Aggiorna', 'one-user-avatar' ); ?>">
                    <?php esc_html_e( 'Upload', 'one-user-avatar' ); ?>
                </button>
            </div>

            <div id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-images' : 'wpua-images-existing' ); ?>" class="<?php echo esc_attr( $hide_images ); ?>">
            <p id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-remove-button' : 'wpua-remove-button-existing' ); ?>" class="<?php echo esc_attr( $hide_remove ); ?>">
               <button type="button" class="button" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-remove' : 'wpua-remove-existing' ); ?>" name="wpua-remove"><?php esc_html_e( 'Remove Image', 'one-user-avatar' ); ?></button>
            </p>
            </div>

            <input type="hidden" name="wpua_action" value="update" />
            <input type="hidden" name="user_id" id="user_id" value="<?php echo esc_attr( $user->ID ); ?>" />

            <?php wp_nonce_field( 'update-user_' . $user->ID ); ?>
            <?php submit_button( __( 'Update Profile', 'one-user-avatar' ) ); ?>

</form>

<script>
jQuery.noConflict();
jQuery(document).ready(function($) {

    $("wpua-edit-<?php echo esc_attr( $user->ID ); ?>").submit(function() {
     //your code....
     setTimeout(function() {
         window.location.reload();
      }, 5000);
   });

});
</script>
</code>```

答: If you have to upload an image and want to wait until it is uploaded before you reload the site, I would work with Ajax (XMLHttpRequest or fetch) and send the image via JavaScript to the server. Then you can wait until it is uploaded and the reload the site.</p>

Body:
I have a form that uploads the profile image to wordpress. After form submit, the page is refreshed and the old image is displayed again. I have to wait about 4 or 5 seconds for the new image to appear. So I have to refresh the page 2 times to see the new image set.

I want to delay the refresh of the page but not the submission of the form, in this way I believe that you don't have to refresh the page twice to see the changes.

I tried with a script, but it doesn't work. I apologize for all this but i am new and i don't have much knowledge about php or js, can anyone help me?

<form id="wpua-edit-<?php echo esc_attr( $user->ID ); ?>" class="wpua-edit" action="" method="post" enctype="multipart/form-data">

  <input type="hidden" name="wp-user-avatar" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wp-user-avatar' : 'wp-user-avatar-existing' ) ?>" value="<?php echo esc_attr( $wpua ); ?>" />

            <div class="upload-avatar" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-upload-button' : 'wpua-upload-button-existing' ); ?>">
                <input name="wpua-file" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-file' : 'wpua-file-existing' ); ?>" type="file" class="wp-input-file"/>
                <button type="submit" class="button" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-upload' : 'wpua-upload-existing' ); ?>" name="submit" value="<?php esc_html_e( 'Aggiorna', 'one-user-avatar' ); ?>">
                    <?php esc_html_e( 'Upload', 'one-user-avatar' ); ?>
                </button>

            <div id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-images' : 'wpua-images-existing' ); ?>" class="<?php echo esc_attr( $hide_images ); ?>">
            <p id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-remove-button' : 'wpua-remove-button-existing' ); ?>" class="<?php echo esc_attr( $hide_remove ); ?>">
               <button type="button" class="button" id="<?php echo esc_attr( ( 'add-new-user' == $user ) ? 'wpua-remove' : 'wpua-remove-existing' ); ?>" name="wpua-remove"><?php esc_html_e( 'Remove Image', 'one-user-avatar' ); ?></button>

            <input type="hidden" name="wpua_action" value="update" />
            <input type="hidden" name="user_id" id="user_id" value="<?php echo esc_attr( $user->ID ); ?>" />

            <?php wp_nonce_field( 'update-user_' . $user->ID ); ?>
            <?php submit_button( __( 'Update Profile', 'one-user-avatar' ) ); ?>

</form>


来源: stackexchange

问:
Checking for values in Vectors of strings in Rust
I'm just getting started with Rust and have hit upon an issue where I'm getting a bit lost in types, pointers, borrowing and ownership.

I have a vector of Person structs, each of which has a name property. I'd like to collect all the names into another vector, and then check if that list contains a given string.

This is my code:

struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| p.name).collect();

    let some_name = String::from("bob");
    if names.iter().any(|n| n == some_name) {
    }
}
```
<p>This fails to compile:</p>
```error[E0277]: can't compare `&String` with `String`
  --> src/main.rs:13:31
   |
13 |     if names.iter().any(|n| n == some_name) {
   |                               ^^ no implementation for `&String == String`
   |
   = help: the trait `PartialEq<String>` is not implemented for `&String`
```

I think names should have the type Vec<String>, so I'm a bit lost as to where the &String comes from. Is this a case of me holding it wrong? I'm most familiar with JavaScript so I'm trying to apply those patterns, and may be not doing it in the most "rusty" way!

答:
Because Rust does not impl PartialEq<&String> for String by default, here are impl PartialEq<&String> for &String and impl PartialEq<String> for String.

Here the type of n is &String, the type of some_name is String, so you need to balance the references on the left and right side of ==.

Both of the following fixes work. I prefer the first one, because the second one has a dereference which implies extra overhead for me. I'm not sure if Rust explicitly defines that there won't be overhead here, and even if there is, LLVM can usually optimize it.

if names.iter().any(|n| n == &some_name) // &String == &String
// or
if names.iter().any(|n| *n == some_name) // String == String
```
<p>Then you will encounter another error:</p>
```error[E0507]: cannot move out of `p.name` which is behind a shared reference
  --> src/main.rs:10:47
   |
10 |     let names: Vec<_> = people.iter().map(|p| p.name).collect();
   |                                               ^^^^^^ move occurs because `p.name` has type `String`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0507`.
```
<p><code>|p| p.name</code> tries to move the <code>name</code> out of <code>p</code>, which is not necessary for the later checks, a <code>&str</code> is enough here. Returns the <code>&str</code> of a <code>String</code> via <code>String::as_str</code>: <code>|p| p.name.as_str()</code></p>
<p>Because of this fix, the type of <code>n</code> below becomes <code>&&str</code>, you can use <code>names.into_iter()</code> to get an iterator for ownership of <code>names</code>.</p>
<p>Fixed code:</p>
<pre class="lang-rust prettyprint-override"><code>struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| p.name.as_str()).collect();

    let some_name = String::from("bob");
    if names.into_iter().any(|n| n == some_name) {
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm just getting started with Rust and have hit upon an issue where I'm getting a bit lost in types, pointers, borrowing and ownership.

I have a vector of Person structs, each of which has a name property. I'd like to collect all the names into another vector, and then check if that list contains a given string.

This is my code:

struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| p.name).collect();

    let some_name = String::from("bob");
    if names.iter().any(|n| n == some_name) {
    }
}

This fails to compile:

error[E0277]: can't compare `&String` with `String`
  --> src/main.rs:13:31
   |
13 |     if names.iter().any(|n| n == some_name) {
   |                               ^^ no implementation for `&String == String`
   |
   = help: the trait `PartialEq<String>` is not implemented for `&String`

I think names should have the type Vec<String>, so I'm a bit lost as to where the &String comes from. Is this a case of me holding it wrong? I'm most familiar with JavaScript so I'm trying to apply those patterns, and may be not doing it in the most "rusty" way!

Body:
Because Rust does not impl PartialEq<&String> for String by default, here are impl PartialEq<&String> for &String and impl PartialEq<String> for String.

Here the type of n is &String, the type of some_name is String, so you need to balance the references on the left and right side of ==.

Both of the following fixes work. I prefer the first one, because the second one has a dereference which implies extra overhead for me. I'm not sure if Rust explicitly defines that there won't be overhead here, and even if there is, LLVM can usually optimize it.

if names.iter().any(|n| n == &some_name) // &String == &String
// or
if names.iter().any(|n| *n == some_name) // String == String

Then you will encounter another error:

error[E0507]: cannot move out of `p.name` which is behind a shared reference
  --> src/main.rs:10:47
   |
10 |     let names: Vec<_> = people.iter().map(|p| p.name).collect();
   |                                               ^^^^^^ move occurs because `p.name` has type `String`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0507`.

|p| p.name tries to move the name out of p, which is not necessary for the later checks, a &str is enough here. Returns the &str of a String via String::as_str: |p| p.name.as_str()

Because of this fix, the type of n below becomes &&str, you can use names.into_iter() to get an iterator for ownership of names.

Fixed code:

struct Person {
    name: String,
}

fn main() {
    let people = vec![Person {
        name: String::from("jack"),
    }];

    let names: Vec<_> = people.iter().map(|p| p.name.as_str()).collect();

    let some_name = String::from("bob");
    if names.into_iter().any(|n| n == some_name) {
    }
}


问:
Why is my recyclerview showing a whitespace
I am practing recyclerView in a fragment in Android Studio, I made this Application;

As you can see there is a whitespace between the toolbar (appbar) and the contents (i.e the recyclerview in this case)

Please, how do I get rid of this whitespace..

Here's the .xml file of the fargment I put the recyclerview:

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ui.newscreen.NewScreenFragment">

    <!-- TODO: Update blank fragment layout -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/new_screen_recyclerview_look" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Here's the sample layout listItem;

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:cardCornerRadius="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/card_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/nav_header_image_nature"
            android:contentDescription="@string/images_for_the_stories" />
    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/card_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:text="@string/Leonardo_Del_Vecchio"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/cardView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/cardView"
        app:layout_constraintTop_toTopOf="@+id/cardView"
        app:layout_constraintVertical_bias="0.04000002" />

    <TextView
        android:id="@+id/card_tontent"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:maxLines="3"
        android:text="@string/sample_story_content"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/cardView"
        app:layout_constraintTop_toBottomOf="@+id/card_title" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Thanks in Advance for your Help!

答:
I have been able to solve the issue.

There was a attribute in the main_activity.xml that cause this.

which was android:paddingTop="?attr/actionBarSize

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">
</code>```

Body:
I am practing recyclerView in a fragment in Android Studio, I made this Application;

As you can see there is a whitespace between the toolbar (appbar) and the contents (i.e the recyclerview in this case)

Please, how do I get rid of this whitespace..

Here's the .xml file of the fargment I put the recyclerview:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ui.newscreen.NewScreenFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/new_screen_recyclerview_look" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here's the sample layout listItem;

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:cardCornerRadius="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/card_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/nav_header_image_nature"
            android:contentDescription="@string/images_for_the_stories" />
    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/card_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:text="@string/Leonardo_Del_Vecchio"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/cardView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/cardView"
        app:layout_constraintTop_toTopOf="@+id/cardView"
        app:layout_constraintVertical_bias="0.04000002" />

    <TextView
        android:id="@+id/card_tontent"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:maxLines="3"
        android:text="@string/sample_story_content"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/cardView"
        app:layout_constraintTop_toBottomOf="@+id/card_title" />

</androidx.constraintlayout.widget.ConstraintLayout>

Thanks in Advance for your Help!

Body:
I have been able to solve the issue.

There was a attribute in the main_activity.xml that cause this.

which was android:paddingTop="?attr/actionBarSize

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">


问:
get the last sunday and saturday's date in python
Looking to leverage datetime to get the date of beginning and end of the previous week, sunday to saturday.

So, if it's 8/12/13 today, I want to define a function that prints:

Last Sunday was 8/4/2013 and last Saturday was 8/10/2013

How do I go about writing this?

EDIT: okay, so there seems to be some question about edge cases. For saturdays, I want the same week, for anything else, I'd like the calendar week immediately preceding today's date.

答:
this is what i did:

```<code>import datetime

def what_date_was_last(day_of_the_week):
    today = datetime.date.today()

    last_seven_dates_from_yesterday = {}
    mod_count = -1
    for i in range(7):
        tdelta = datetime.timedelta(mod_count)
        mod_count -= 1
        date = today + tdelta
        last_seven_dates_from_yesterday[date.weekday()] = date

    days_of_the_week_dict = {
        "mon": 0,
        "tue": 1,
        "wed": 2,
        "thu": 3,
        "fri": 4,
        "sat": 5,
        "sun": 6,
    }
    answer=last_seven_dates_from_yesterday
         [days_of_the_week_dict[day_of_the_week]]
    return answer
</code>```

so now i can run..

```<code>what_date_was_last("sun")
</code>```

or any day of the week

```<code>what_date_was_last("tue")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
this is what i did:

import datetime

def what_date_was_last(day_of_the_week):
    today = datetime.date.today()

    last_seven_dates_from_yesterday = {}
    mod_count = -1
    for i in range(7):
        tdelta = datetime.timedelta(mod_count)
        mod_count -= 1
        date = today + tdelta
        last_seven_dates_from_yesterday[date.weekday()] = date

    days_of_the_week_dict = {
        "mon": 0,
        "tue": 1,
        "wed": 2,
        "thu": 3,
        "fri": 4,
        "sat": 5,
        "sun": 6,
    }
    answer=last_seven_dates_from_yesterday
         [days_of_the_week_dict[day_of_the_week]]
    return answer

so now i can run..

what_date_was_last("sun")

or any day of the week

what_date_was_last("tue")


问:
Adding a service reference to a website
I am trying to add a service reference to my website. When I add the service reference to a WPF application I get a reference.cs file that I can edit and add attributes to. When I try to do the same thing in a asp.net website there this file isn't present. I have also tried looking on the file system and the reference.cs isn't present. Can anyone provide some guidance?

EDIT:: Im using VS2010 and I need to edit the reference.cs to add [Webget] and [WebPost] attributes

答:
In Visual Studio, right-click on the reference under the "Service Reference" section of the Solution Explorer and click "View in Object Browser".  Then, in the Object Browser, under the namespace for the reference, right-click on any of the properties and select "Go to Definition".  This will load up "Reference.cs" file.

Hope this helps!

Edit:
Also worth noting is that the classes generated for you are partial classes, so it may be beneficial to consider extending them in a separate file so that you can still "Update" the reference and not have the generated code overwrite any changes you make.  This would all depend on what you're planing on modifying though.

Title: Adding a service reference to a website


问:
How to increase return values of functions without breaking legacy code?
For example, let's say you have a function:

```<code>def foo(a):
    return a
</code>```

And there are heaps of legacy code which uses this function:

```<code>amount = 4 + foo(a)
</code>```

What if I need to increase the return values of foo without breaking the existing codes?

```<code>def foo(a)
   return a, a + 5
</code>```

Now, when I do this, variable amount is not the correct answer, because a is now, in pylint's words 'a tuple' so amount will change from returning a + 4, to returning (a, a+5) + 4.

How do I add a + 5 to foo, while still allowing amount to be a single scalar value, rather than a tuple?

答:
Rename the function and add the new return value.
Then write a wrapper named like the original function, which extracts the legacy return value:

Original code:

```<code>def foo(x):
    return a
</code>```

New code:

```<code>def enhanced_foo(x):
    return a, extra_info

def foo(x):
    return enhanced_foo(x)[0]
</code>```

Legacy code still works:

```<code>a = foo(x)
</code>```

New code uses the new name:

```<code>a, extra = enhanced_foo(x)
</code>```

Body:
For example, let's say you have a function:

def foo(a):
    return a

And there are heaps of legacy code which uses this function:

amount = 4 + foo(a)

What if I need to increase the return values of foo without breaking the existing codes?

def foo(a)
   return a, a + 5

Now, when I do this, variable amount is not the correct answer, because a is now, in pylint's words 'a tuple' so amount will change from returning a + 4, to returning (a, a+5) + 4.

How do I add a + 5 to foo, while still allowing amount to be a single scalar value, rather than a tuple?

Body:
Rename the function and add the new return value.
Then write a wrapper named like the original function, which extracts the legacy return value:

Original code:

def foo(x):
    return a

New code:

def enhanced_foo(x):
    return a, extra_info

def foo(x):
    return enhanced_foo(x)[0]

Legacy code still works:

a = foo(x)

New code uses the new name:

a, extra = enhanced_foo(x)


问:
Running show() twice gives same results for rand() function for Dataframe
The below produces random numbers that differ per row as expected. So, fine. But I am apparently missing some basic aspect apparently in thinking.

```<code>from pyspark.sql import functions as F
df = spark.range(10).withColumn("randomNum",F.rand())
df.show(truncate=False)
</code>```

returning:

```<code>+---+-------------------+
|id |randomNum          |
+---+-------------------+
|0  |0.8128581612050234 |
|1  |0.40656852491856355|
|2  |0.9444869347865689 |
|3  |0.10391423680687417|
|4  |0.05285485891027453|
|5  |0.5140906081158558 |
|6  |0.900727341820192  |
|7  |0.11046600268909801|
|8  |0.6509183512961298 |
|9  |0.5060097759646045 |
+---+-------------------+
</code>```

Then invoking show() again - the special Action below, why do we get the same random number sequence again as per first time round? Is show() overriding the traditional Action approach on some aspects as it sees that it is the same DF? If so, that is not true for all methods in pyspark, etc. I am running this in 2 cells in a Databricks Notebook.

Looking at the SPARK UI, it uses the same seed twice. Why? Deterministic aspect, seems to be at odds with the concept of Action as we are taught.

```<code>df.show(truncate=False)
</code>```

答:
This is the result of random being initialized only once per partition. Source.

Hence, if partition layout is not changed, that same initial seed is being used in every consecutive execution, and thus rand generates the same sequence.

When partitions are NOT fixed, rand's behavior becomes non-deterministic, which is documented (in the source, at least) through Spark JIRA-13380.

Body:
The below produces random numbers that differ per row as expected. So, fine. But I am apparently missing some basic aspect apparently in thinking.

from pyspark.sql import functions as F
df = spark.range(10).withColumn("randomNum",F.rand())
df.show(truncate=False)

returning:

+---+-------------------+
|id |randomNum          |
+---+-------------------+
|0  |0.8128581612050234 |
|1  |0.40656852491856355|
|2  |0.9444869347865689 |
|3  |0.10391423680687417|
|4  |0.05285485891027453|
|5  |0.5140906081158558 |
|6  |0.900727341820192  |
|7  |0.11046600268909801|
|8  |0.6509183512961298 |
|9  |0.5060097759646045 |
+---+-------------------+

Then invoking show() again - the special Action below, why do we get the same random number sequence again as per first time round? Is show() overriding the traditional Action approach on some aspects as it sees that it is the same DF? If so, that is not true for all methods in pyspark, etc. I am running this in 2 cells in a Databricks Notebook.

Looking at the SPARK UI, it uses the same seed twice. Why? Deterministic aspect, seems to be at odds with the concept of Action as we are taught.

df.show(truncate=False)


问:
Get the coordinate of click inside iframe (pdf)
I display pdf documents in an iframe on my website (all documents are stored in the same domain).

I would like users to be able to click in the document to add comments at a specific location.
To do this, I am looking for a way to get the coordinate inside of an iframe (when we click).

It does not seem possible... However, there are paid solutions that offer this kind of functionality. Example : https://pdfjs.express/demo
So, what process is used?

Thanks for you help.

答:
You can get the coordinate of a click using the onmousedown event. The event gives you a MouseEvent object that contains the x and y coordinate of the click relative to the view port.

To get the coordinate relative to your iframe you have to subtract offsetLeft and offsetTop

Example

var iframe = document.getElementById("iframe")

onmousedown = function(e) {
    document.getElementById("position").textContent = "Mouse position: " + (e.clientX - iframe.offsetLeft) + " | " + (e.clientY - iframe.offsetTop)
}
```

Edit

You could use PDF.js and a canvas instead of a simple iframe to better controll the PDF-viewer.

Body:
You can get the coordinate of a click using the onmousedown event. The event gives you a MouseEvent object that contains the x and y coordinate of the click relative to the view port.

To get the coordinate relative to your iframe you have to subtract offsetLeft and offsetTop

Example

var iframe = document.getElementById("iframe")

onmousedown = function(e) {
    document.getElementById("position").textContent = "Mouse position: " + (e.clientX - iframe.offsetLeft) + " | " + (e.clientY - iframe.offsetTop)
}

Edit

You could use PDF.js and a canvas instead of a simple iframe to better controll the PDF-viewer.


问:
How can I convert SQL Server stored procedure to Python (SQLAlchemy) def
How can I convert SQL Server stored procedure to Python (SQLAlchemy) def?

My target : [MSSQL SP] to [python(SQLAlchemy) def]

答:
You are explicitly speaking of  "stored procedure" so I assume you don't have models nor ORM used in the app using this db. You have 2 options:

Use sqlalchemy to map your db models and interact with them without using your procedures.

Call your procedure through an SQL connector (that can be provided by SQLAlchemy)

You can do a mix of both solutions if you have part of your app that need to stay unmapped by an orm (for legal or certification raisons for example)

Since you did add the FastAPI tag, the first link is the official FastAPI doc on how to use SQLAlchemy with the framework.


问:
Github pages don't render images in my project built in Flutter after the last Flutter's update (2.10.1)
Github pages don't render images
Image(image:AssetImage('image.png')) in my project built in Flutter after the last Flutter's update (2.10.1)... Has anyone else had this happen?

答: Thanks to the comment of Yeasin Sheikh now works. You must add in the path: Image(image:AssetImage('assets/images/image.png'))


问:
How do I sort array by numbers and also prevent it from increasing more then 15 length and take only the biggest numbers?
here is my code for now:

```<code>router.get('/questions/best', function(req,res,next){
  Question.find({}).exec(function(err,results){
    if (err){return next(err)}
    let top15 = [];
    for(let i = 0; i< results.length; i++){
      let dislikestouse = results[i].dislikes[0]
      let ratio  = 0
      if(dislikestouse > 0){
        ratio = results[i].likes[0]/dislikestouse
      }
      else{
        ratio = results[i].likes[0]/1
      }

    }
    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  })
});
</code>```

results is every question in the database, and top15 is supposed to be only the ones displayed since they have the highest ratio and rendered into the template.
I tried using if statements to prevent it dividing by 0 since it results in an error.

how do I sort every result by finding if it is bigger then any of the items in top15 and then placing it in the right place if it is? I use pure JavaScript.
to access the numbers of a result's dislikes and likes search for the first item since it where I store the length, like a typical likes array is: [2,'username1', 'username2'].
here is the scheme for a question:

```<code>const Question = mongoose.model(
  "Question",
  new Schema({
    title: { type: String, required: true },
    text: { type: String },
    authorUsername: { type: String, required: true },
    dateCreated: {},
    answers: { type: Array, required: true },
    likes: { type: Array, required: true },
    dislikes: { type: Array, required: true },
    tag: { type: String, required: true },
    views: {type: Array, required:true},
  })
);
</code>```

here is an example of a question:

```<code>_id:620935985f6865b4e85c333d
title:"How do i make a lemon?"
text:"yeet"
authorUsername:"SweetWhite"
dateCreated:2022-02-13T16:45:12.598+00:00
answers:
Array
likes:
Array
0:1
1:"SweetWhite"
dislikes:
Array
0:0
tag:
"Social"
views:
Array
0:1
1:"SweetWhite"
__v:0
</code>```

Thanks!

答:
Before I try to help, please try to improve your code's readability. You can look up async/await and ES6 syntax to help you in this.

Also, if you're using an IDE like Visual Studio Code then you can install prettier which will autoformat your codes.

Here's a rough solution for you:

router.get('/questions/best', function(req,res,next){
  Question.find({}).exec(function(err,results){
    if (err) return next(err);

    let top15 = [];

    // note that the code is slightly more readable already
    results.forEach(result => {
      const dislikesToUse = result.dislikes[0]

      let ratio = 0;

      if(dislikesToUse > 0) {
        ratio = result.likes[0]/dislikesToUse
      } else {
        ratio = result.likes[0]/1
      }

      // push each result with ratio to top15
      top15.push({...result, ratio})
    });

    // sort top15 by ratio
    top15.sort((a,b) => b.ratio - a.ratio) // do a.ratio - b.ratio to change order

    // get only the top 15
    top15 = top15.slice(0, 15)

    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  })
});
```

NOTE

This is only one way to do it and might not be the most efficient way. You should also consider Mongo's aggregate functions.

You should also definitely reconsider your schema design.

Body:
here is my code for now:

router.get('/questions/best', function(req,res,next){
  Question.find({}).exec(function(err,results){
    if (err){return next(err)}
    let top15 = [];
    for(let i = 0; i< results.length; i++){
      let dislikestouse = results[i].dislikes[0]
      let ratio  = 0
      if(dislikestouse > 0){
        ratio = results[i].likes[0]/dislikestouse
      }
      else{
        ratio = results[i].likes[0]/1
      }

    }
    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  })
});

results is every question in the database, and top15 is supposed to be only the ones displayed since they have the highest ratio and rendered into the template.
I tried using if statements to prevent it dividing by 0 since it results in an error.

how do I sort every result by finding if it is bigger then any of the items in top15 and then placing it in the right place if it is? I use pure JavaScript.
to access the numbers of a result's dislikes and likes search for the first item since it where I store the length, like a typical likes array is: [2,'username1', 'username2'].
here is the scheme for a question:

const Question = mongoose.model(
  "Question",
  new Schema({
    title: { type: String, required: true },
    text: { type: String },
    authorUsername: { type: String, required: true },
    dateCreated: {},
    answers: { type: Array, required: true },
    likes: { type: Array, required: true },
    dislikes: { type: Array, required: true },
    tag: { type: String, required: true },
    views: {type: Array, required:true},
  })
);

here is an example of a question:

_id:620935985f6865b4e85c333d
title:"How do i make a lemon?"
text:"yeet"
authorUsername:"SweetWhite"
dateCreated:2022-02-13T16:45:12.598+00:00
answers:
Array
likes:
Array
0:1
1:"SweetWhite"
dislikes:
Array
0:0
tag:
"Social"
views:
Array
0:1
1:"SweetWhite"
__v:0

Thanks!

Body:
Before I try to help, please try to improve your code's readability. You can look up async/await and ES6 syntax to help you in this.

Also, if you're using an IDE like Visual Studio Code then you can install prettier which will autoformat your codes.

Here's a rough solution for you:

router.get('/questions/best', function(req,res,next){
  Question.find({}).exec(function(err,results){
    if (err) return next(err);

    let top15 = [];

    // note that the code is slightly more readable already
    results.forEach(result => {
      const dislikesToUse = result.dislikes[0]

      let ratio = 0;

      if(dislikesToUse > 0) {
        ratio = result.likes[0]/dislikesToUse
      } else {
        ratio = result.likes[0]/1
      }

      // push each result with ratio to top15
      top15.push({...result, ratio})
    });

    // sort top15 by ratio
    top15.sort((a,b) => b.ratio - a.ratio) // do a.ratio - b.ratio to change order

    // get only the top 15
    top15 = top15.slice(0, 15)

    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  })
});

NOTE

This is only one way to do it and might not be the most efficient way. You should also consider Mongo's aggregate functions.

You should also definitely reconsider your schema design.


问:
How to make the center of carousel slider bigger than the others?

I want to make the center Carousel Bigger than the others

```<code>      CarouselSlider(
      items: generateImageTiles(),
      options: CarouselOptions(
        enlargeCenterPage: true,
        aspectRatio: 16 / 5,
        viewportFraction: 0.4,
        reverse: false,
        initialPage: _current,
        onPageChanged: (index, other) {
          setState(() {
            _current = index;
            pizza = images[_current];
            price = prices[_current];
            name = names[_current];
          });
        },
      ),
    ),
</code>```

This is what i'm trying to achieve APP UI

答:
You need to add an attrbute in options called as

enlargeCenterPage: true,

viewportFraction: 0.8,

That will do it for you.
Also make the viewportfraction less than 1. That will make side cards visible.

Body:
I want to make the center Carousel Bigger than the others

      CarouselSlider(
      items: generateImageTiles(),
      options: CarouselOptions(
        enlargeCenterPage: true,
        aspectRatio: 16 / 5,
        viewportFraction: 0.4,
        reverse: false,
        initialPage: _current,
        onPageChanged: (index, other) {
          setState(() {
            _current = index;
            pizza = images[_current];
            price = prices[_current];
            name = names[_current];
          });
        },
      ),
    ),

This is what i'm trying to achieve APP UI


问:
How can I insert a '-' in my string?
I have a string that can look like this: 12345, this 123456 or this: 1234567.

I'd like to make each string look like this: 123-45, this: 1234-56 or this: 12345-67.

How can I do this in C#?

答:
Take a look at String.Format(), My guess is you want something like String.Format("{0:##-##}",< value >);

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Examples shown with powershell, which uses the same corelibs

```<code>PS C:\Users\Phyx> [string]::Format("{0:##-##}",1234)
12-34
PS C:\Users\Phyx> [string]::Format("{0:##-##}",123445)
1234-45
PS C:\Users\Phyx> [string]::Format("{0:##-##}",12)
-12
PS C:\Users\Phyx> [string]::Format("{0:0#-##}",12)
00-12
PS C:\Users\Phyx> [string]::Format("{0:##-##}",122)
1-22
</code>```

Title: How can I insert a '-' in my string?

Body:
Take a look at String.Format(), My guess is you want something like String.Format("{0:##-##}",< value >);

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Examples shown with powershell, which uses the same corelibs

PS C:\Users\Phyx> [string]::Format("{0:##-##}",1234)
12-34
PS C:\Users\Phyx> [string]::Format("{0:##-##}",123445)
1234-45
PS C:\Users\Phyx> [string]::Format("{0:##-##}",12)
-12
PS C:\Users\Phyx> [string]::Format("{0:0#-##}",12)
00-12
PS C:\Users\Phyx> [string]::Format("{0:##-##}",122)
1-22


问:
What is the difference between nulltypes :: and 0n in KDB?
Both of these appear to be null types, but seem to behave differently.

For example, if instantiate a dictionary with

```<code>`a`b!(0n 0n)
</code>```

I'm unable to upsert integers, where as I can if i do:

```<code>`a`b!(:: ::)
</code>```

I can. What is the difference between 0n and ::?

答:
0N actually defaults to 0Nj. Same way if you define non-float numbers they will also be long. 0N is not equivalent to :: because of this.

If you want the values of your dictionary to be integers, you would need to define it as such:  `a`b!0N 0Ni (or keep it as generic null with the identity)

Body:
Both of these appear to be null types, but seem to behave differently.

For example, if instantiate a dictionary with

`a`b!(0n 0n)

I'm unable to upsert integers, where as I can if i do:

`a`b!(:: ::)

I can. What is the difference between 0n and ::?


问:
Django How to do a correlated EXISTS or NOT EXISTS
How can I perform the following correlated EXISTS and NOT EXISTS in Django?

I do not want to use IN and NOT IN. These are not the same as EXISTS and NOT EXISTS.

Correlated EXISTS:

```<code>SELECT *
FROM foo
WHERE EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)
</code>```

Correlated NOT EXISTS:

```<code>SELECT *
FROM foo
WHERE NOT EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)
</code>```

答:
You can use method of QuerySet - exists(). Assuming that:

```<code>class Foo(models.Model):
    bar = models.ForeignKey(Bar, ..., related_name='foos')
</code>```

You can check if there is relation:

```<code>foo = Foo.objects.get(id=1)
bar = Bar.objects.get(id=1)

bar.foos.exists()   # returns True if not empty else False
foo.bar             # returns related object or None
</code>```

Body:
How can I perform the following correlated EXISTS and NOT EXISTS in Django?

I do not want to use IN and NOT IN. These are not the same as EXISTS and NOT EXISTS.

Correlated EXISTS:

SELECT *
FROM foo
WHERE EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)

Correlated NOT EXISTS:

SELECT *
FROM foo
WHERE NOT EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)

Body:
You can use method of QuerySet - exists(). Assuming that:

class Foo(models.Model):
    bar = models.ForeignKey(Bar, ..., related_name='foos')

You can check if there is relation:

foo = Foo.objects.get(id=1)
bar = Bar.objects.get(id=1)

bar.foos.exists()   # returns True if not empty else False
foo.bar             # returns related object or None


问:
Patchwork doesn't recognize plots with ggMargnial distribution elements

Trying to display 2 plots with ggMarginal but the plots are not recognized as such.

I'm pasting a simplified version of the code below where:

Before adding the ggMarginal element Patchwork displays ggplots side by side as expected

After adding marginal distributions with ggMarginal, Patchwork doesn't seem to recognize the the plot any more. The error message that I get is the following:

p1m + p2m
#> Error in p1m + p2m: non-numeric argument to binary operator
```
<p>Here's the code I'm running:</p>
<pre class="lang-r prettyprint-override"><code>library(ggplot2)
library(ggExtra)
library(patchwork)

p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp)) +
  ggtitle('Plot 1')

p1m <- ggMarginal(p1,
                 type = "density",
                 size = 3)

p2 <- ggplot(mtcars) +
  geom_point(aes(hp, wt, colour = mpg)) +
  ggtitle('Plot 3')

p2m <- ggMarginal(p2,
                 type = "density",
                 size = 3)

p1+p2

p1m + p2m
#> Error in p1m + p2m: non-numeric argument to binary operator
</code>```

Thanks a lot for your help!

Created on 2021-10-09 by the reprex package (v2.0.1)

答:
You can wrap your marginal plots in patchwork::wrap_elements()

```<code>patchwork::wrap_elements(p1m) + patchwork::wrap_elements(p2m)
</code>```

Body:
Trying to display 2 plots with ggMarginal but the plots are not recognized as such.

I'm pasting a simplified version of the code below where:

Before adding the ggMarginal element Patchwork displays ggplots side by side as expected

After adding marginal distributions with ggMarginal, Patchwork doesn't seem to recognize the the plot any more. The error message that I get is the following:

p1m + p2m
#> Error in p1m + p2m: non-numeric argument to binary operator

Here's the code I'm running:

library(ggplot2)
library(ggExtra)
library(patchwork)

p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp)) +
  ggtitle('Plot 1')

p1m <- ggMarginal(p1,
                 type = "density",
                 size = 3)

p2 <- ggplot(mtcars) +
  geom_point(aes(hp, wt, colour = mpg)) +
  ggtitle('Plot 3')

p2m <- ggMarginal(p2,
                 type = "density",
                 size = 3)

p1+p2

p1m + p2m
#> Error in p1m + p2m: non-numeric argument to binary operator

Thanks a lot for your help!

Created on 2021-10-09 by the reprex package (v2.0.1)

Body:
You can wrap your marginal plots in patchwork::wrap_elements()

patchwork::wrap_elements(p1m) + patchwork::wrap_elements(p2m)


问:
Sub-query works but would a join or other alternative be better?
I am trying to select rows from one table where the id referenced in those rows matches the unique id from another table that relates to it like so:

SELECT *
FROM booklet_tickets
WHERE bookletId = (SELECT id
                   FROM booklets
                   WHERE bookletNum = 2000
                     AND seasonId = 9
                     AND bookletTypeId = 3)
```

With the bookletNum/seasonId/bookletTypeId being filled in by a user form and inserted into the query.

This works and returns what I want but seems messy. Is a join better to use in this type of scenario?

答:
It is not possible to give a "Yes it's better" or "no it's not" answer for this type of scenario.

My personal rule of thumb if number of rows in a table is less than 1 million, I do not care optimising "SELECT WHERE IN" types of queries as SQL Server Query Optimizer is smart enough to pick an appropriate plan for the query.

In reality however you often need more values from a joined table in the final resultset so a JOIN with a filter WHERE clause might make more sense, such as:

```<code>SELECT BT.*, B.SeasonId
FROM booklet_tickes BT
INNER JOIN booklets B ON BT.bookletId = B.id
WHERE B.bookletNum = 2000
    AND B.seasonId = 9
    AND B.bookletTypeId = 3
</code>```

To me it comes down to a question of style rather than anything else, write your code so that it'll be easier for you to understand it months later. So pick a certain style and then stick to it :)

The question however is old as the time itself :)

SQL JOIN vs IN performance?

Body:
I am trying to select rows from one table where the id referenced in those rows matches the unique id from another table that relates to it like so:

SELECT *
FROM booklet_tickets
WHERE bookletId = (SELECT id
                   FROM booklets
                   WHERE bookletNum = 2000
                     AND seasonId = 9
                     AND bookletTypeId = 3)

With the bookletNum/seasonId/bookletTypeId being filled in by a user form and inserted into the query.

This works and returns what I want but seems messy. Is a join better to use in this type of scenario?

Body:
It is not possible to give a "Yes it's better" or "no it's not" answer for this type of scenario.

My personal rule of thumb if number of rows in a table is less than 1 million, I do not care optimising "SELECT WHERE IN" types of queries as SQL Server Query Optimizer is smart enough to pick an appropriate plan for the query.

In reality however you often need more values from a joined table in the final resultset so a JOIN with a filter WHERE clause might make more sense, such as:

SELECT BT.*, B.SeasonId
FROM booklet_tickes BT
INNER JOIN booklets B ON BT.bookletId = B.id
WHERE B.bookletNum = 2000
    AND B.seasonId = 9
    AND B.bookletTypeId = 3

To me it comes down to a question of style rather than anything else, write your code so that it'll be easier for you to understand it months later. So pick a certain style and then stick to it :)

The question however is old as the time itself :)

SQL JOIN vs IN performance?


问:
Big-little endian details when reading bytes (memory location)
Let's suppose to use this 32-bit number 66 DD FA EB.

Little Endian

0 x 100 ---> 66  (MSB)

0 x 99 ---> DD

0 x 98 ---> FA

0 x 97 ---> EB  (LSB)

Big Endian

0 x 100 ---> EB  (LSB)

0 x 99 ---> FA

0 x 98 ---> DD

0 x 97 ---> 66   (MSB)

I believe to have understood the correct order which bytes are stored in.

However my question is, which byte is read first when this 4-bytes word is accessed ?

is always the byte with the lowest address to be read first and then positioned so as to be the most significant or least significant depending on the endian of the computer?

I try to explain myself better.
Take the example above of LITTLE ENDIAN.

The correct order which I wanna get is 66 DD FA EB

Now to achieve this, I could read the byte with the lowest address and place it on the right of the page, then continue to the left for the following bytes.

```<code>         EB

      FA EB

   DD FA EB

66 DD FA EB
</code>```

Result is 66 DD FA EB and that's correct.

or I could read from the byte with the highest address, place it on the left of the page, and continue to the right for the following bytes

```<code>66

66 DD

66 DD FA

66 DD FA EB
</code>```

Result is Always 66 DD FA EB, and this is correct.

Since the memory address of the word is the address of the first byte(lowest address), independently of the endian, I assume that it is always the first byte(lowest address) to be read first, and then positioned in the correct order.

So my final question is,

which of the two modes I showed before is used by a computer in little endian to read the 4bytes-word in the proposed exemple ?

答:
Modern CPUs typically read all 4 bytes at once, from cache or a wide-enough external data bus.

When they read a whole cache line, there is a related concept of "critical word first", i.e. stream data from memory starting with the 8-byte chunk that includes the data you're actually waiting for (the demand load that missed in cache), so the load can complete and forward data to the next instruction waiting for it ASAP.

But this is still assuming that the bus width / transfer chunk size is at least as wide as a load, so we're not getting into details of which half of a load is loaded first if you have a narrow bus (like on a 386 SX for example).

Modern CPUs have internal busses up to 64 bytes wide (e.g. between L2 and L1d cache in Skylake, and between SIMD load/store units and L1d cache in Skylake-avx512 and later Intel CPUs).  DDR SDRAM transfers 64 bytes in 8x 8-byte transfers over the 64-bit external bus.

Fun fact, little-endian was originally invented by Intel for the 8008, which was going to be, or going to replace, a CPU with bit-serial ALU and address calculation.  Since carry propagates from low to high when doing addition / subtraction, a bit-serial machine needs to start with the low bit first.  For instructions that contain an absolute address (along with an opcode?) that meant putting the low bit in the first byte and the high bits in the next byte, so it could overlap ALU / address-calc cycles with cycles of reading one bit at a time.

8008 ended up not being a bit-serial design, but the ISA was designed to leave that option open.  See Why is x86 little endian? for some quotes.

But anyway, a bit-serial machine wants to load the low bit first.  (Over a 1-bit bus, using shift-registers for storage instead of normal RAM).

Body:
Let's suppose to use this 32-bit number 66 DD FA EB.

Little Endian

0 x 100 ---> 66  (MSB)

0 x 99 ---> DD

0 x 98 ---> FA

0 x 97 ---> EB  (LSB)

Big Endian

0 x 100 ---> EB  (LSB)

0 x 99 ---> FA

0 x 98 ---> DD

0 x 97 ---> 66   (MSB)

I believe to have understood the correct order which bytes are stored in.

However my question is, which byte is read first when this 4-bytes word is accessed ?

is always the byte with the lowest address to be read first and then positioned so as to be the most significant or least significant depending on the endian of the computer?

I try to explain myself better.
Take the example above of LITTLE ENDIAN.

The correct order which I wanna get is 66 DD FA EB

Now to achieve this, I could read the byte with the lowest address and place it on the right of the page, then continue to the left for the following bytes.

         EB

      FA EB

   DD FA EB

66 DD FA EB

Result is 66 DD FA EB and that's correct.

or I could read from the byte with the highest address, place it on the left of the page, and continue to the right for the following bytes

66

66 DD

66 DD FA

66 DD FA EB

Result is Always 66 DD FA EB, and this is correct.

Since the memory address of the word is the address of the first byte(lowest address), independently of the endian, I assume that it is always the first byte(lowest address) to be read first, and then positioned in the correct order.

So my final question is,

which of the two modes I showed before is used by a computer in little endian to read the 4bytes-word in the proposed exemple ?


答:
I'm assuming you want to add a dash two characters before the end of the string.</p>

```<code>string number = "12345";

if(number.Length > 2)
    string result = number.Insert(number.Length-2, "-");
else
    //error checking
</code>```

Title: How can I insert a '-' in my string?

Body:
I have a string that can look like this: 12345, this 123456 or this: 1234567.

I'd like to make each string look like this: 123-45, this: 1234-56 or this: 12345-67.

How can I do this in C#?

Body:
I'm assuming you want to add a dash two characters before the end of the string.

string number = "12345";

if(number.Length > 2)
    string result = number.Insert(number.Length-2, "-");
else
    //error checking


问:
Trigger onChange function even if an option is already chosen in react
I'm looking how to trigger onChange function when an option is already selected and clicked by the user to deselect it, it's like multiselect.
you can select an option and deselect it by clicking on it a second time.
this is what i've already tried.
everything is working when there is more than 1 option selected, but not when there is only one option selected.</p>
```<code>const handleChangeGroup = (selectedItems) => {
    const groups = [];
    for (let i = 0; i < selectedItems.length; i++) {
      if (groupArray.includes(selectedItems[i].value)) {
        if (groupArray.length === 0) {
          setGroupArray([]);
        } else {
          var newArray = groupArray.filter(
            (value) => value != selectedItems[i].value
          );
          setGroupArray(newArray);
        }
      } else {
        groups.push(selectedItems[i].value);
        setGroupArray(groupArray.concat(groups));
      }
    }
  };

<select
            multiple={true}
            value={groupArray}
            onChange={(event) =>
              handleChangeGroup(event.target.selectedOptions)
            }>
            {data[selectType] !== undefined
              ? Object.keys(data[selectType]).map((group, index) => (
                  <option value={group} key={group}>
                    {group}
                  </option>
                ))
              : null}
          </select>

</code>```

答:
Executable example:

const Sample = () => {
    const data = ['a', 'b', 'c'];
    const [groupArray, setGroupArray] = React.useState([]);

    const handleChangeGroup = (selectedItem) => {
        if (groupArray.includes(selectedItem)) {
            const tempArray = groupArray.filter(item => item !== selectedItem);
            setGroupArray([...tempArray]);
        } else {
            setGroupArray([...groupArray, selectedItem]);
        }
    };

    return (
        <select
            multiple
            value={groupArray}
            onClick={e => handleChangeGroup(e.target.value)}
        >
            {data.map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))}
        </select>
    );
};

ReactDOM.render(<Sample />, document.querySelector("#app"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

You might want to consider using checkboxes for a more intuitive UI and more concise code.

If you don't want to use checkboxes, you can use this code:

```<code>const handleChangeGroup = (selectedItem) => {
    if (groupArray.includes(selectedItem)) {
        const tempArray = groupArray.filter(item => item !== selectedItem);
        setGroupArray([...tempArray]);
    } else {
        setGroupArray([...groupArray, selectedItem]);
    }
};

return (
    <select
        multiple
        value={groupArray}
        onClick={e => handleChangeGroup(e.target.value)}
    >
        {data[selectType] !== undefined
            ? Object.keys(data[selectType]).map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))
            : null}
    </select>
);
</code>```

The reason onChange won't work is because the default behavior of select is to make the user choose at least one option. Clicking on the last selected option will not deselect anything. So onChange won't fire when you have only one selected item left. You can override this replacing onChange with onClick.

For a simpler example/test, you can try using select without the multiple attribute. Clicking on the currently selected option won't fire any deselect events either.

Body:
I'm looking how to trigger onChange function when an option is already selected and clicked by the user to deselect it, it's like multiselect.
you can select an option and deselect it by clicking on it a second time.
this is what i've already tried.
everything is working when there is more than 1 option selected, but not when there is only one option selected.

const handleChangeGroup = (selectedItems) => {
    const groups = [];
    for (let i = 0; i < selectedItems.length; i++) {
      if (groupArray.includes(selectedItems[i].value)) {
        if (groupArray.length === 0) {
          setGroupArray([]);
        } else {
          var newArray = groupArray.filter(
            (value) => value != selectedItems[i].value
          );
          setGroupArray(newArray);
        }
      } else {
        groups.push(selectedItems[i].value);
        setGroupArray(groupArray.concat(groups));
      }
    }
  };

<select
            multiple={true}
            value={groupArray}
            onChange={(event) =>
              handleChangeGroup(event.target.selectedOptions)
            }>
            {data[selectType] !== undefined
              ? Object.keys(data[selectType]).map((group, index) => (
                  <option value={group} key={group}>
                    {group}
                  </option>
                ))
              : null}
          </select>

Body:
Executable example:

const Sample = () => {
    const data = ['a', 'b', 'c'];
    const [groupArray, setGroupArray] = React.useState([]);

    const handleChangeGroup = (selectedItem) => {
        if (groupArray.includes(selectedItem)) {
            const tempArray = groupArray.filter(item => item !== selectedItem);
            setGroupArray([...tempArray]);
        } else {
            setGroupArray([...groupArray, selectedItem]);
        }
    };

    return (
        <select
            multiple
            value={groupArray}
            onClick={e => handleChangeGroup(e.target.value)}
        >
            {data.map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))}
        </select>
    );
};

ReactDOM.render(<Sample />, document.querySelector("#app"));

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div>

You might want to consider using checkboxes for a more intuitive UI and more concise code.

If you don't want to use checkboxes, you can use this code:

const handleChangeGroup = (selectedItem) => {
    if (groupArray.includes(selectedItem)) {
        const tempArray = groupArray.filter(item => item !== selectedItem);
        setGroupArray([...tempArray]);
    } else {
        setGroupArray([...groupArray, selectedItem]);
    }
};

return (
    <select
        multiple
        value={groupArray}
        onClick={e => handleChangeGroup(e.target.value)}
    >
        {data[selectType] !== undefined
            ? Object.keys(data[selectType]).map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))
            : null}
    </select>
);

The reason onChange won't work is because the default behavior of select is to make the user choose at least one option. Clicking on the last selected option will not deselect anything. So onChange won't fire when you have only one selected item left. You can override this replacing onChange with onClick.

For a simpler example/test, you can try using select without the multiple attribute. Clicking on the currently selected option won't fire any deselect events either.


问:
@Transactional doesn't rollback by calling an External method that throw an RuntimeException
I'm playing with Spring and the @Transactional annotation. I'm doing a simple experiment to test the behaviour of this annotation. These are my super simple java classes:

my domain:

```<code>package com.xxx.springdemo.transactionalAnnotation.domain;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;

@Data
@Entity
public class Counter {

    @Id
    int id;
    int count = 0;

}
</code>```

my service:

```<code>package com.xxx.springdemo.transactionalAnnotation.services;

import com.xxx.springdemo.transactionalAnnotation.domain.Counter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TransactionalService {

    public void throwException(Counter counter) {
        counter.setCount(1);
        throw new RuntimeException("Runtime exception");
    }

    public void dontThrowException(Counter counter) {
        counter.setCount(2);
    }
}
</code>```

and my controller:

```<code>package com.xxx.springdemo.transactionalAnnotation.controllers;

import com.xxx.springdemo.transactionalAnnotation.domain.Counter;
import com.xxx.springdemo.transactionalAnnotation.services.TransactionalService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class TransactionController {

    private final TransactionalService transactionalService;

    @GetMapping("test-transactional")
    public void testTransactional() {
        Counter counter = new Counter();
        try {
            transactionalService.throwException(counter);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
        System.out.println("Variable hasn't changed (counter = " + counter.getCount() + ")");
    }

    @GetMapping("test-transactional-2")
    public void testTransactionalWithoutException() {
        Counter counter = new Counter();
        try {
            transactionalService.dontThrowException(counter);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
        System.out.println("Variable changed (counter = " + counter.getCount() + ")");
    }
}
</code>```

The code should be self-explanatory. I expect to have printed:

Variable hasn't changed (counter = 0)

in case the test-transactional endpoint is called. What I get instead is:

Variable hasn't changed (counter = 1)

This means that in the service method throwException the count property isn't rollbacked after the exception is thrown.

P.S. this is my build.gradle file:

```<code>plugins {
    id 'org.springframework.boot' version '2.6.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'io.micrometer:micrometer-registry-prometheus'

    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}
</code>```

答:
Spring 's @Transactional is just a declarative way to manage the underlying JPA transaction. So it depends on the rollback behaviour of JPA which is defined by the spec. as follows :

For both transaction-scoped persistence contexts and for extended
persistence contexts that are joined to the current transaction,
transaction rollback causes all pre-existing managed instances and
removed instances[29] to become detached. The instances' state will be
the state of the instances at the point at which the transaction was
rolled back. Transaction rollback typically causes the persistence
context to be in an inconsistent state at the point of rollback.

Hibernate docs also mentions the same :

Rolling back the database transaction does not put your business objects back into the state they were at the start of the transaction.
This means that the database state and the business objects will be
out of sync. Usually, this is not a problem because exceptions are
not recoverable and you will have to start over after rollback anyway.

So it is the expected rollback behaviour which the Counter will still have the state just before the transaction is rollback (i.e count=1).

For the entity that is already exist in the DB , you can restore its state back to the same as DB manually by using entityManager.refresh() or simply use entityManager.get() or JPQL to retrieve it again from the DB.

For the entity that does not exist in the DB , simply re-execute the codes to create it again.

So rollback here just means nothing will be updated in DB. It does not mean that it will restore the object state to the moment just before executing a @Transactional method.

Body:
I'm playing with Spring and the @Transactional annotation. I'm doing a simple experiment to test the behaviour of this annotation. These are my super simple java classes:

my domain:

package com.xxx.springdemo.transactionalAnnotation.domain;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;

@Data
@Entity
public class Counter {

    @Id
    int id;
    int count = 0;

}

my service:

package com.xxx.springdemo.transactionalAnnotation.services;

import com.xxx.springdemo.transactionalAnnotation.domain.Counter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TransactionalService {

    public void throwException(Counter counter) {
        counter.setCount(1);
        throw new RuntimeException("Runtime exception");
    }

    public void dontThrowException(Counter counter) {
        counter.setCount(2);
    }
}

and my controller:

package com.xxx.springdemo.transactionalAnnotation.controllers;

import com.xxx.springdemo.transactionalAnnotation.domain.Counter;
import com.xxx.springdemo.transactionalAnnotation.services.TransactionalService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class TransactionController {

    private final TransactionalService transactionalService;

    @GetMapping("test-transactional")
    public void testTransactional() {
        Counter counter = new Counter();
        try {
            transactionalService.throwException(counter);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
        System.out.println("Variable hasn't changed (counter = " + counter.getCount() + ")");
    }

    @GetMapping("test-transactional-2")
    public void testTransactionalWithoutException() {
        Counter counter = new Counter();
        try {
            transactionalService.dontThrowException(counter);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
        System.out.println("Variable changed (counter = " + counter.getCount() + ")");
    }
}

The code should be self-explanatory. I expect to have printed:

Variable hasn't changed (counter = 0)

in case the test-transactional endpoint is called. What I get instead is:

Variable hasn't changed (counter = 1)

This means that in the service method throwException the count property isn't rollbacked after the exception is thrown.

P.S. this is my build.gradle file:

plugins {
    id 'org.springframework.boot' version '2.6.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'io.micrometer:micrometer-registry-prometheus'

    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}


问:
Scheduling in Linux: run a task when computer is idle (= no user input)
I'd like to run Folding@home client on my Ubuntu 8.10 box only when it's idle because of the program's heavy RAM consumption.

By "idle" I mean the state when there's no user activity (keyboard, mouse, etc). It's OK for other (probably heavy) processes to run at that time since F@H has the lowest CPU priority. The point is just to improve user experience and to do heavy work when nobody is using the machine.

How to accomplish this?

答:
I want something like xprintidle but it didn't work in my case(Ubuntu 21.10, Wayland)

I used the following solution to get idle current value(time with no mouse/keyboard input):

```<code>dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime
</code>```

It should return uint64 time in milliseconds. Example:

```<code>$ sleep 3; dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime
method return time=1644776247.028363 sender=:1.34 -> destination=:1.890 serial=9792 reply_serial=2
uint64 2942 # i.e. 2.942 seconds without input
</code>```

OwnerDisplayName: wheleph

LastEditorDisplayName: wheleph

Body:
I want something like xprintidle but it didn't work in my case(Ubuntu 21.10, Wayland)

I used the following solution to get idle current value(time with no mouse/keyboard input):

dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime

It should return uint64 time in milliseconds. Example:

$ sleep 3; dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime
method return time=1644776247.028363 sender=:1.34 -> destination=:1.890 serial=9792 reply_serial=2
uint64 2942 # i.e. 2.942 seconds without input


问:
502 Bad Gateway in elasticbeanstalk of AWS
I have deployed a spring boot application in elasticbeanstalk.
In the "application.properties" file, I have set,

server.port=5000

I have added a RDS db and set the following environment properties.

I have also added an inbound rule in the security group of the environment as shown in the image below:

I am still getting the 502 Bad Gateway error when I click on the URL.

答:
In case of Elastic Beanstalk, in your instance there is an nginx reverse proxy, which accepts HTTP connections on port 80 and proxies these connections to port 5000.

In your security group inbound rule you should accept HTTP connections on port 80 from everywhere (0.0.0.0/0).


问:
Jquery toggle with position absolute bottom
I've got an absolute positioned container, which is bottom aligned.

Now I would like to toggle (show/hide) some content without the container getting larger than its contents -  and preferably without setting the height explicitly.

html

```<code><div id="outer">
    <div class="expandableContent">
        <p class="toggler">Toggle</p>
        <div>
            <p>Some content here</p>
            <p>Some content there</p>
            <p>Some content everywhere</p>
        </div>
    </div>
</div>
</code>```

css

```<code>#outer {
     height: 300px;
     position: relative;
}

.expandableContent {
    position: absolute;
    bottom: 10px;
}

 .expandableContent > div {
     display: none;
 }
</code>```

jquery

```<code>$(document).ready(function () {
    $('.toggler').click( function() {
        $(this).next().toggle(1000);
    });
});
</code>```

Here's a link: http://jsfiddle.net/SunnyRed/A8pNv/1/

答:
```<code>width: 100%;
white-space:nowrap;
</code>```

Add the above the the div containing the text.

xGreen is correct that setting the width will work, but some browsers with also require text-wrapping to be disabled. An example would be with Chrome, just setting the width is not enough.

Body:
I've got an absolute positioned container, which is bottom aligned.

Now I would like to toggle (show/hide) some content without the container getting larger than its contents -  and preferably without setting the height explicitly.

html

Toggle

Some content here

Some content there

Some content everywhere

css

#outer {
     height: 300px;
     position: relative;
}

.expandableContent {
    position: absolute;
    bottom: 10px;
}

 .expandableContent > div {
     display: none;
 }

jquery

$(document).ready(function () {
    $('.toggler').click( function() {
        $(this).next().toggle(1000);
    });
});

Here's a link: http://jsfiddle.net/SunnyRed/A8pNv/1/

Body:
width: 100%;
white-space:nowrap;

Add the above the the div containing the text.

xGreen is correct that setting the width will work, but some browsers with also require text-wrapping to be disabled. An example would be with Chrome, just setting the width is not enough.


问:
neo4j -- Find all shortest paths between more than 2 nodes
For example,I want to query allShortestPaths between 3 nodes(A,B,C),it means i want to query:
1. the allShortestPaths between A and B
2. the allShortestPaths between C and B
3. the allShortestPaths between A and C

but I only find the allShortestPaths query to get allShortestPaths between two nodes.

As follow:

```<code>MATCH (node1:E { eid:"a9c2f114-796f-4934-a2d0-04bb3345e1d2" }),
(node2:E { eid:"01968dd2-1ed6-472d-82e9-be7701036b3b" }),
p = allShortestPaths((node1)-[*]-(node2))
RETURN p LIMIT 25
</code>```

I am wondering if there exists a allShortestPaths query supporting more than 2 nodes input?

Now,to search 3 nodes,I have to invoke the "allShortestPaths" three times,as follow:

```<code>MATCH (node1:E { eid:"b73ade90-dfa1-4b94-bd0f-c16fd93bd680" }),
(node2:E { eid:"ddb5c52d-7002-4ac7-87d5-0f727f2ab3e7" }),
(node3:E { eid:"0398b081-6676-4a91-856b-abbabaee5e70" }) ,
p = allShortestPaths((node1)-[*]-(node2)),
q = allShortestPaths((node3)-[*]-(node2)),
m = allShortestPaths((node3)-[*]-(node1))
RETURN p,q,m LIMIT 10
</code>```

What i want to do is to search allShortestPaths between arbitrary number of nodes.

So far,I intend to write user-defined procedures,but it will costs more time.I wondering who can provide better advice.

i want to search search allShortestPaths between serveral nodes.
such as: allShortestPaths((a)-[*]-(b)-[*]-(c)-[*]-(a))

I want get the all shortest path between a and b,b and c,c and a in a query

答:
here a sample cypher

```<code>MATCH (n:Entity) where n.name IN {names}
WITH collect(n) as nodes
UNWIND nodes as n
UNWIND nodes as m
WITH * WHERE id(n) < id(m)
MATCH path = allShortestPaths( (n)-[*..4]-(m) )
RETURN path
</code>```

see https://neo4j.com/developer/kb/all-shortest-paths-between-set-of-nodes/ for more

Body:
For example,I want to query allShortestPaths between 3 nodes(A,B,C),it means i want to query:
1. the allShortestPaths between A and B
2. the allShortestPaths between C and B
3. the allShortestPaths between A and C

but I only find the allShortestPaths query to get allShortestPaths between two nodes.

As follow:

MATCH (node1:E { eid:"a9c2f114-796f-4934-a2d0-04bb3345e1d2" }),
(node2:E { eid:"01968dd2-1ed6-472d-82e9-be7701036b3b" }),
p = allShortestPaths((node1)-[*]-(node2))
RETURN p LIMIT 25

I am wondering if there exists a allShortestPaths query supporting more than 2 nodes input?

Now,to search 3 nodes,I have to invoke the "allShortestPaths" three times,as follow:

MATCH (node1:E { eid:"b73ade90-dfa1-4b94-bd0f-c16fd93bd680" }),
(node2:E { eid:"ddb5c52d-7002-4ac7-87d5-0f727f2ab3e7" }),
(node3:E { eid:"0398b081-6676-4a91-856b-abbabaee5e70" }) ,
p = allShortestPaths((node1)-[*]-(node2)),
q = allShortestPaths((node3)-[*]-(node2)),
m = allShortestPaths((node3)-[*]-(node1))
RETURN p,q,m LIMIT 10

What i want to do is to search allShortestPaths between arbitrary number of nodes.

So far,I intend to write user-defined procedures,but it will costs more time.I wondering who can provide better advice.

i want to search search allShortestPaths between serveral nodes.
such as: allShortestPaths((a)-[*]-(b)-[*]-(c)-[*]-(a))

I want get the all shortest path between a and b,b and c,c and a in a query

Body:
here a sample cypher

MATCH (n:Entity) where n.name IN {names}
WITH collect(n) as nodes
UNWIND nodes as n
UNWIND nodes as m
WITH * WHERE id(n) < id(m)
MATCH path = allShortestPaths( (n)-[*..4]-(m) )
RETURN path

see https://neo4j.com/developer/kb/all-shortest-paths-between-set-of-nodes/ for more


问:
How can I check if a solution of an LP is unique?
I want to check if my linear program has just one solution or infinite ones. How can I do that using PuLP?</p>

答:
In practice, there are virtually always multiple solutions because of numerical tolerances, that is, allowing small violations of primal and dual feasibility in the solutions.

I suppose you are rather referring to multiple different optimal bases for your LP. This can be checked by testing for degeneracy: Check whether there are basic variables that are on one of their bounds (or tight basic constraints) and check whether there are non-basic variables with 0 reduced costs or dual multipliers.

These checks can only be done if your LP solution is a basic solution in the first place, coming from a simplex-type optimization.


问:
How can the terminal on VS Code be fixed?
I have some problems with the terminal of VSCode. When I try to open the terminal it's saying that "The terminal shell path "C:\Program Files\Git\bin\bash.exe" does not exist" (image). How can I fix it, help me please. </p>

答:
If you got "The terminal process failed to launch: Path to shell executable "C:\Program Files\Git\bin\bash.exe" does not exist. VSCODE" in VSCode, it's time to change the settings and change the path of the file where your git is located.

I did encountered the same issue, and when I had VSCode in my old system, it had the old path pre-configured, and if you sign-in to your VSCode in new system, you might want to change your path of the file where the git was initially installed.

To do the changes,

Open VSCode >> Setting ("Ctrl + comma(,)" ). This will open up your settings in VSCode.

Search for terminal.integrated.shell.windows or Got to "Terminal >> Integerated >> Automation profiles >> Windows". If you have Linux/ other operating system you will find the same settings.

Click on "Edit in Settings.json"

Check the image provided below.

VSCode Settings for Windows

Once you opened the "Edit in Settings.json", find the term "terminal.integrated.shell.windows", and change the path of your git location.

This will fix the VSCode issue.

I hope it works for you! Thank you.

Check the image provided below.

terminal.integrated.shell.windows settings


问:
combine two different csv files and make them into one
I want to join csv1 with csv2 to result into final_csv, the schema only has String type columns (file contents are as follows):

```<code>  csv1
  emp_name   designation   salary_col
   smith        manager      40000
   john        analyst       35000
   adam       sr.engineer    50000
   eve           QA          36000
   mills      sr.manager     44000

   csv2
  emp_name   designation   advance_salary_col
   smith        manager      2000
   john        analyst       3030
   adam       sr.engineer    5044
   eve           QA          3600
   mills      sr.manager     4500

 final_csv
  emp_name   designation   salary_col   advance_salary_col
   smith        manager      40000           2000
   john        analyst       35000           3030
   adam       sr.engineer    50000           5044
   eve           QA          36000           3600
   mills      sr.manager     44000           4500
</code>```

I tried using few methods Union, Intersect, UnionByName but am getting null values for all of the columns in scala in my final_df

```<code>    val emp_dataDf1 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("data/emp_data1.csv")

    val emp_dataDf2 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("/data/emp_data2.csv")

    val final_df= emp_dataDf1.union(emp_dataDf2)
</code>```

答:
This is a join. See docs about SQL joins and joins in Spark.</p>
```<code>val final_df = emp_dataDf1.join(emp_dataDf2, Seq("empname", "designation"))
</code>```

Body:
I want to join csv1 with csv2 to result into final_csv, the schema only has String type columns (file contents are as follows):

  csv1
  emp_name   designation   salary_col
   smith        manager      40000
   john        analyst       35000
   adam       sr.engineer    50000
   eve           QA          36000
   mills      sr.manager     44000

   csv2
  emp_name   designation   advance_salary_col
   smith        manager      2000
   john        analyst       3030
   adam       sr.engineer    5044
   eve           QA          3600
   mills      sr.manager     4500

 final_csv
  emp_name   designation   salary_col   advance_salary_col
   smith        manager      40000           2000
   john        analyst       35000           3030
   adam       sr.engineer    50000           5044
   eve           QA          36000           3600
   mills      sr.manager     44000           4500

I tried using few methods Union, Intersect, UnionByName but am getting null values for all of the columns in scala in my final_df

    val emp_dataDf1 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("data/emp_data1.csv")

    val emp_dataDf2 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("/data/emp_data2.csv")

    val final_df= emp_dataDf1.union(emp_dataDf2)

Body:
This is a join. See docs about SQL joins and joins in Spark.

val final_df = emp_dataDf1.join(emp_dataDf2, Seq("empname", "designation"))


问:
How to start a mongodb shell in docker container?
To start the container, I am typing the following command:

```<code>sudo docker run -i -t -p 28000:27017 mongo:latest /usr/bin/mongod --smallfiles
</code>```

But I want to open the shell in this container to type the mongo commands.
What command should I run to do the same?

答:
Extending and updating @vladzam answer and if your container is already running in docker, you can use the exec mongosh command with login and pass options like this:

```<code>docker exec -it database-dev mongosh -u "myLogin" -p "myPass"
</code>```

Body:
To start the container, I am typing the following command:

sudo docker run -i -t -p 28000:27017 mongo:latest /usr/bin/mongod --smallfiles

But I want to open the shell in this container to type the mongo commands.
What command should I run to do the same?

Body:
Extending and updating @vladzam answer and if your container is already running in docker, you can use the exec mongosh command with login and pass options like this:

docker exec -it database-dev mongosh -u "myLogin" -p "myPass"


问:
How to access looped div tag in Typescript file
```<code><div  class="mx-0 p-2 row"  style="box-shadow: 0 -1px 0 0 rgb(0 0 0 / 10%);">
    <div #myDiv (click)="navToOrder(value.agId,value.invoiceId,value.tableNo,value.currStageName)" [style.background-color]="value.currStageColor"

        class="table1 m-3"  *ngFor="let value of dashBoardTableList ;let i=index"
        tooltip={{value.currStageName}} placement="top">
        <span class="homeTopLabel ">{{value.noOfCovers}}</span>
        <span class="leftGlass">
            <i *ngIf="value.currStageName!='Empty'" class="fa fa-glass "></i>
            <i *ngIf="value.currStageName=='Empty'" class=" fa fa-glass fa-flip-vertical"></i>
        </span>
        <span class="fa-stack middlePlate">
            <i class="fa fa-genderless fa-stack-2x" style="font-size:35px;"></i><i class="fa fa-spoon fa-stack-1x"
                style="font-size: 15px;top: 5px;left: -1.5px;"></i>
        </span>
        <span class="rightGlass">
            <i *ngIf="value.currStageName!='Empty'" class="fa fa-glass "></i>
            <i *ngIf="value.currStageName=='Empty'" class=" fa fa-glass fa-flip-vertical"></i>
        </span>

        <span class="homeBlabel">{{value.tableNo}}</span>

    </div>
</div>
</code>```

Here I want to get a specific index of div tag unfortunately Tabindex is not working fine.Is there any other way ?

答:
I've voted for the answer of @Will Alexander, but for code, there are minor issues I'll fix it here.
for the selector name, fix it to be [myStyleDirective] instead of 'myStyleDirective'

And for setStyle method make sure that you are passing the correct parameters, especially for the name of the style and the value for the style

Here is a working example: Stackblitz

Body:
        {{value.noOfCovers}}

        {{value.tableNo}}

Here I want to get a specific index of div tag unfortunately Tabindex is not working fine.Is there any other way ?


问:
How can I create a user input loop for a Guess the Number game between 1-100?
```<code>#Guess the number

from random import *
correct_number = randint(1, 100)
#print(correct_number)

def guess(user_guess):
    while user_input != correct_number:
        if user_guess == correct_number:
            return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
        elif user_guess > correct_number:
            return "Guess a lower number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))
        else:
            return "Guess a higher number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))

"""user_input = ""
while user_input != correct_number:
    user_input = input("Hey user, guess a number between 1 and 100.\n")"""

user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)

value = guess(user_input_guess)
print(value)
</code>```

I have the bulk of the code ready. I just can't nail the user input loop. Each time I guess a number it exits the code.

答:
```<code>from random import randint

correct_number = randint(1, 100)

user_input = ""
while user_input != correct_number:
    user_input = int(input("Hey user, guess a number between 1 and 100.\n"))
</code>```

No need to use functions. You forgot to convert the input to an int in the code inside the comment so that's why it wasn't working

Body:
#Guess the number

from random import *
correct_number = randint(1, 100)
#print(correct_number)

def guess(user_guess):
    while user_input != correct_number:
        if user_guess == correct_number:
            return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
        elif user_guess > correct_number:
            return "Guess a lower number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))
        else:
            return "Guess a higher number\n"
            user_input = int(user_input("Guess a number between 1 and 100.\n"))

"""user_input = ""
while user_input != correct_number:
    user_input = input("Hey user, guess a number between 1 and 100.\n")"""

user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)

value = guess(user_input_guess)
print(value)

I have the bulk of the code ready. I just can't nail the user input loop. Each time I guess a number it exits the code.

Body:
from random import randint

correct_number = randint(1, 100)

user_input = ""
while user_input != correct_number:
    user_input = int(input("Hey user, guess a number between 1 and 100.\n"))

No need to use functions. You forgot to convert the input to an int in the code inside the comment so that's why it wasn't working


问:
enable button after actual input entered
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

```<code> <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#Textfield').keyup(function(){
     var textBox = $('#Textfield').val();
     if((textBox >= 100) || (textBox <= 200) ){
       $('.disabledButton').prop("disabled", false);
     } else {
     $('#error').text('actual amount needed');
        return false;
    }
});
</script>
</code>```

答:
There's a number of reasons your code is not working:

.val() is always text, so you are (would be) comparing "15" with 100 and 200 and it would pass, convert to an integer

you start with the button disabled, then (assuming everything else is working ok) you enable it, but never disable it again if the value changes again

same for the #error text, you don't clear it when the value is valid

The main issue is:

```<code>if((textBox >= 100) || (textBox <= 200) ){
</code>```

if the textbox value is greater than 100 OR it's less than 200, well, all values follow this rule: eg 1 is less than 200, so passes, 3000 is more than 100, so passes.

This should be

```<code>if((textBox >= 100) && (textBox <= 200) ){
</code>```

Giving updated snippet:

$('#Textfield').keyup(function() {
  var textBox = $('#Textfield').val() * 1;
  if ((textBox >= 100) && (textBox <= 200)) {
    $('.disabledButton').prop("disabled", false);
    $('#error').text('ok');
  } else {
    $('.disabledButton').prop("disabled", true);
    $('#error').text('actual amount needed');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<form method="post">
  <input type="text" id="Textfield">
  <button type="submit" class="disabledButton" disabled>Submit</button>
  <p id="error"></p>
</form></code>```

Body:
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

 <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>

</form>

Body:
There's a number of reasons your code is not working:

.val() is always text, so you are (would be) comparing "15" with 100 and 200 and it would pass, convert to an integer

you start with the button disabled, then (assuming everything else is working ok) you enable it, but never disable it again if the value changes again

same for the #error text, you don't clear it when the value is valid

The main issue is:

if((textBox >= 100) || (textBox <= 200) ){

if the textbox value is greater than 100 OR it's less than 200, well, all values follow this rule: eg 1 is less than 200, so passes, 3000 is more than 100, so passes.

This should be

if((textBox >= 100) && (textBox <= 200) ){

Giving updated snippet:

$('#Textfield').keyup(function() {
  var textBox = $('#Textfield').val() * 1;
  if ((textBox >= 100) && (textBox <= 200)) {
    $('.disabledButton').prop("disabled", false);
    $('#error').text('ok');
  } else {
    $('.disabledButton').prop("disabled", true);
    $('#error').text('actual amount needed');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<form method="post">
  <input type="text" id="Textfield">
  <button type="submit" class="disabledButton" disabled>Submit</button>
  <p id="error"></p>
</form>