问:
Android Studio Firebase Database DataSnapshot returning null
TLDR: I have been trying to retrieve user information from the Firebase Realtime Database, but the dataSnapshot within the addChildEventListener or addValueEventListener seems to always return null. I followed the API exactly to no avail. Please send help!!

My Profile Activity:

```<code>import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;

import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends AppCompatActivity {
    private static final String tag = "ProfileActivity";
    private static final int PROFILE_ACTIVITY = 1;

    //firebase elements
    private FirebaseAuth mAuth;
    private FirebaseDatabase mDatabase;
    private DatabaseReference mReference;
    private FirebaseUser currentUser;

    //view elements
    private Button logoutBtn;
    private TextView walletBalance, tasksTaken, tasksPosted, userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        mAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance();
        currentUser = mAuth.getCurrentUser();
        mReference = mDatabase.getReference(mAuth.getUid());
        Query query = mReference;

        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Log.d(tag, dataSnapshot.getValue().toString());
                if(dataSnapshot.getValue() != null)
                {
                    Log.d(tag, "not null");
                    User newUser = dataSnapshot.getValue(User.class);
                    Log.d(tag, newUser.getName());
                    Log.d(tag, Integer.toString(newUser.getWalletBalance()));
                    Log.d(tag, Integer.toString(newUser.getTasksTaken()));
                    Log.d(tag, Integer.toString(newUser.getTasksPosted()));

                    userName.setText(newUser.getName());
                    walletBalance.setText(newUser.getWalletBalance());
                    tasksTaken.setText(newUser.getTasksTaken());
                    tasksPosted.setText(newUser.getTasksPosted());
                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    private void setViewElements() {
        logoutBtn = findViewById(R.id.btn_logout);
        walletBalance = findViewById(R.id.tv_walletBalance);
        tasksTaken = findViewById(R.id.tv_taskSAmount);
        tasksPosted = findViewById(R.id.tv_taskPAmount);
        userName = findViewById(R.id.tv_userName);
    }

    private void goToLoginActivity() {
        startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        finish();
    }

</code>```

My User Object:

```<code>public class User {
    //user information
    String name, email, password;
    int walletBalance, tasksTaken, tasksPosted;

    //constructor
    public User(String name, String email, String password, int walletBalance, int tasksTaken, int tasksPosted) {
        this.name = name;
        this.email = email;
        this.password = password;
        this.walletBalance = walletBalance;
        this.tasksTaken = tasksTaken;
        this.tasksPosted = tasksPosted;
    }

    //empty constructor
    public User() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getWalletBalance() {
        return walletBalance;
    }

    public void setWalletBalance(int walletBalance) {
        this.walletBalance = walletBalance;
    }

    public int getTasksTaken() {
        return tasksTaken;
    }

    public void setTasksTaken(int tasksTaken) {
        this.tasksTaken = tasksTaken;
    }

    public int getTasksPosted() {
        return tasksPosted;
    }

    public void setTasksPosted(int tasksPosted) {
        this.tasksPosted = tasksPosted;
    }
}

</code>```

My Firebase Database:

Any help is very very appreciated!!

答:
When you are using the following reference:

```<code>mReference = mDatabase.getReference(mAuth.getUid());
</code>```

Along with:

```<code>.addChildEventListener(/* ... */)
</code>```

It means that you are trying to read all children that exist within the user object. The direct children of the user object are actually the values as are defined in your User class. If you want to get the details of the logged-in user please use the following lines of code:

```<code>String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        User user = dataSnapshot.getValue(User.class);
        Log.d("TAG", user.getName());
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
    }
};
uidef.addListenerForSingleValueEvent(valueEventListener);
</code>```

The result of the above code will be the name of the logged-in user printed out in the logcat.

Body:
TLDR: I have been trying to retrieve user information from the Firebase Realtime Database, but the dataSnapshot within the addChildEventListener or addValueEventListener seems to always return null. I followed the API exactly to no avail. Please send help!!

My Profile Activity:

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;

import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends AppCompatActivity {
    private static final String tag = "ProfileActivity";
    private static final int PROFILE_ACTIVITY = 1;

    //firebase elements
    private FirebaseAuth mAuth;
    private FirebaseDatabase mDatabase;
    private DatabaseReference mReference;
    private FirebaseUser currentUser;

    //view elements
    private Button logoutBtn;
    private TextView walletBalance, tasksTaken, tasksPosted, userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        mAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance();
        currentUser = mAuth.getCurrentUser();
        mReference = mDatabase.getReference(mAuth.getUid());
        Query query = mReference;

        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Log.d(tag, dataSnapshot.getValue().toString());
                if(dataSnapshot.getValue() != null)
                {
                    Log.d(tag, "not null");
                    User newUser = dataSnapshot.getValue(User.class);
                    Log.d(tag, newUser.getName());
                    Log.d(tag, Integer.toString(newUser.getWalletBalance()));
                    Log.d(tag, Integer.toString(newUser.getTasksTaken()));
                    Log.d(tag, Integer.toString(newUser.getTasksPosted()));

                    userName.setText(newUser.getName());
                    walletBalance.setText(newUser.getWalletBalance());
                    tasksTaken.setText(newUser.getTasksTaken());
                    tasksPosted.setText(newUser.getTasksPosted());
                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    private void setViewElements() {
        logoutBtn = findViewById(R.id.btn_logout);
        walletBalance = findViewById(R.id.tv_walletBalance);
        tasksTaken = findViewById(R.id.tv_taskSAmount);
        tasksPosted = findViewById(R.id.tv_taskPAmount);
        userName = findViewById(R.id.tv_userName);
    }

    private void goToLoginActivity() {
        startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        finish();
    }

My User Object:

public class User {
    //user information
    String name, email, password;
    int walletBalance, tasksTaken, tasksPosted;

    //constructor
    public User(String name, String email, String password, int walletBalance, int tasksTaken, int tasksPosted) {
        this.name = name;
        this.email = email;
        this.password = password;
        this.walletBalance = walletBalance;
        this.tasksTaken = tasksTaken;
        this.tasksPosted = tasksPosted;
    }

    //empty constructor
    public User() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getWalletBalance() {
        return walletBalance;
    }

    public void setWalletBalance(int walletBalance) {
        this.walletBalance = walletBalance;
    }

    public int getTasksTaken() {
        return tasksTaken;
    }

    public void setTasksTaken(int tasksTaken) {
        this.tasksTaken = tasksTaken;
    }

    public int getTasksPosted() {
        return tasksPosted;
    }

    public void setTasksPosted(int tasksPosted) {
        this.tasksPosted = tasksPosted;
    }
}

My Firebase Database:

Any help is very very appreciated!!

Body:
When you are using the following reference:

mReference = mDatabase.getReference(mAuth.getUid());

Along with:

.addChildEventListener(/* ... */)

It means that you are trying to read all children that exist within the user object. The direct children of the user object are actually the values as are defined in your User class. If you want to get the details of the logged-in user please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        User user = dataSnapshot.getValue(User.class);
        Log.d("TAG", user.getName());
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
    }
};
uidef.addListenerForSingleValueEvent(valueEventListener);

The result of the above code will be the name of the logged-in user printed out in the logcat.


来源: stackexchange

问:
From string, extract a word starting with a keyword (SQL or any other methods?)
Let's say I have a string of random characters, and I want to extract only the string that starts after a specific keyword (including the keyword). How could I do so using MySQL or MariaDB? ..............

String example:

axdsSSFddlwie ====> SSFddlwie

aldfklafnlanaSSFiiie ====> SSFiiie

iiiSSFnnnn ====> SSFnnnn

Thanks for the help!

答:
You can use substring_index():

```<code>select concat('SSF', substring_index(col, 'SSF', -1))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use substring_index():

select concat('SSF', substring_index(col, 'SSF', -1))


问:
C# Class reference into another Class but Why?
i am beginner in c# i did't understand why put class reference into another class, here is the code.

```<code>  interface IDB
{
    void AddDoctor(Doctor doc);
    void AddPatient(Patient pat);
    void AddWard(Ward ward);
}

    class DataBaseManager
{
    private IDB db;

    public DataBaseManager(IDB dbase)
    {
        this.db = dbase;
    }

class ComputerOperator
{
    private string name;
    private int age;
    private DataBaseManager dbm;

    public ComputerOperator(string name, int age,SQLDB sqdata)
    {
        this.name = name;
        this.age = age;
        dbm = new DataBaseManager(sqdata);
    }

    class BillingDepartment
    {
    private ComputerOperator operater;

    public ComputerOperator Operater
    {
        get { return operater; }
        set { operater = value; }
    }
   }
</code>```

When we put the class into another class is called NESTED CLASSES, then me what is the name of this thing in c# "PUT THE CLASS REFERENCE INTO ANOTHER CLASS."

Edited to add
sir, i am asking about why we need "a class reference into another class", and is that any alternate if we dont put a class reference into another class???
for example,

```<code>      namespace myNameSpace
      {
       public class class1
      {
        //methods
      }

      public class class2
     {
      private class1 myclass1;
       //methods
     }
</code>```

答:
I'm guessing what is meant (because it isn't very clear from the context or your wording) that you have a field containing a reference to another instance of a class. It has a reference to an object whose type is that of the referenced class.

```<code>public class A
{
    public class Nested
    {
    }

    public Nested _nestedFieldRefrence;
    public B _otherClass;
}

public class B
{
}
</code>```

In class A you have
* A nested class called Nested
* A reference to an instance of the nested class called _nestedFieldReference
* A reference to another class called _otherClass

Does that help your understanding?

ContentLicense: CC BY-SA 3.0

Body:
i am beginner in c# i did't understand why put class reference into another class, here is the code.

  interface IDB
{
    void AddDoctor(Doctor doc);
    void AddPatient(Patient pat);
    void AddWard(Ward ward);
}

    class DataBaseManager
{
    private IDB db;

    public DataBaseManager(IDB dbase)
    {
        this.db = dbase;
    }

class ComputerOperator
{
    private string name;
    private int age;
    private DataBaseManager dbm;

    public ComputerOperator(string name, int age,SQLDB sqdata)
    {
        this.name = name;
        this.age = age;
        dbm = new DataBaseManager(sqdata);
    }

    class BillingDepartment
    {
    private ComputerOperator operater;

    public ComputerOperator Operater
    {
        get { return operater; }
        set { operater = value; }
    }
   }

When we put the class into another class is called NESTED CLASSES, then me what is the name of this thing in c# "PUT THE CLASS REFERENCE INTO ANOTHER CLASS."

Edited to add
sir, i am asking about why we need "a class reference into another class", and is that any alternate if we dont put a class reference into another class???
for example,

      namespace myNameSpace
      {
       public class class1
      {
        //methods
      }

      public class class2
     {
      private class1 myclass1;
       //methods
     }

Body:
I'm guessing what is meant (because it isn't very clear from the context or your wording) that you have a field containing a reference to another instance of a class. It has a reference to an object whose type is that of the referenced class.

public class A
{
    public class Nested
    {
    }

    public Nested _nestedFieldRefrence;
    public B _otherClass;
}

public class B
{
}

In class A you have
* A nested class called Nested
* A reference to an instance of the nested class called _nestedFieldReference
* A reference to another class called _otherClass

Does that help your understanding?


问:
How to find the similarity in R?
I have a data set as I've shown below:

It shows which book is sold by which shop.

```<code>df <- tribble(
 ~shop,  ~book_id,
  "A",       1,
  "B",       1,
  "C",       2,
  "D",       3,
  "E",       3,
  "A",       3,
  "B",       4,
  "C",       5,
  "D",       1,
)
</code>```

In the data set,

shop A sells 1, 3

shop B sells 1, 4

shop C sells 2, 5

shop D sells 3, 1

shop E sells only 3

So now, I want to calculate the Jaccard index here. For instance, let's take shop A and shop B. There are three different books that are sold by A and B (book 1, book 3, book 4). However, only one product is sold by both shops (this is product 1). So, the Jaccard index here should be 33.3% (1/3).

Here is the sample of the desired data:

```<code>df <- tribble(
  ~shop_1, ~shop_2, ~similarity,
    "A",    "B",         33.3,
    "B",    "A",         33.33,
    "A",    "C",          0,
    "C",    "A",          0,
    "A",    "D",         100,
    "D",    "A",         100,
    "A",    "E",          50,
    "E",    "A",          50,

)
</code>```

Any comments/assistance really appreciated! Thanks in advance.

答:
I don't know about a package but you can write your own function. I guess by similarity you mean something like this:

```<code>similarity <- function(x, y) {
  k <- length(intersect(x, y))
  n <- length(union(x, y))
  k / n
}
</code>```

Then you can use tidyr::crossing to merge the same data frame with itself

```<code>dfg <- df %>% group_by(shop) %>% summarise(books = list(book_id))
crossing(dfg %>% set_names(paste0, "_A"), dfg %>% set_names(paste0, "_B")) %>%
  filter(shop_A != shop_B) %>%
  mutate(similarity = map2_dbl(books_A, books_B, similarity))
</code>```

Title: How to find the similarity in R?

Body:
I have a data set as I've shown below:

It shows which book is sold by which shop.

df <- tribble(
 ~shop,  ~book_id,
  "A",       1,
  "B",       1,
  "C",       2,
  "D",       3,
  "E",       3,
  "A",       3,
  "B",       4,
  "C",       5,
  "D",       1,
)

In the data set,

shop A sells 1, 3

shop B sells 1, 4

shop C sells 2, 5

shop D sells 3, 1

shop E sells only 3

So now, I want to calculate the Jaccard index here. For instance, let's take shop A and shop B. There are three different books that are sold by A and B (book 1, book 3, book 4). However, only one product is sold by both shops (this is product 1). So, the Jaccard index here should be 33.3% (1/3).

Here is the sample of the desired data:

df <- tribble(
  ~shop_1, ~shop_2, ~similarity,
    "A",    "B",         33.3,
    "B",    "A",         33.33,
    "A",    "C",          0,
    "C",    "A",          0,
    "A",    "D",         100,
    "D",    "A",         100,
    "A",    "E",          50,
    "E",    "A",          50,

)

Any comments/assistance really appreciated! Thanks in advance.

Body:
I don't know about a package but you can write your own function. I guess by similarity you mean something like this:

similarity <- function(x, y) {
  k <- length(intersect(x, y))
  n <- length(union(x, y))
  k / n
}

Then you can use tidyr::crossing to merge the same data frame with itself

dfg <- df %>% group_by(shop) %>% summarise(books = list(book_id))
crossing(dfg %>% set_names(paste0, "_A"), dfg %>% set_names(paste0, "_B")) %>%
  filter(shop_A != shop_B) %>%
  mutate(similarity = map2_dbl(books_A, books_B, similarity))


问:
Vue.js route params data getting lost after the full page reload
I am passing a user id from the router-link using params to display the detail of the user in the profile page and i am getting all the required data and also is displayed correctly but as soon as i reload the page the $route.params.id changes into undefined and the data which were shown are gone to get the data i have to again navigate to the index page and revisit the link.

my index.vue page with the router-link is as follow

```<code><h6 class="author">
    <router-link :to="{name: 'FrontProfile' , params: {
         id: post.user.id }}"
         tag="a" active-class="active">{{post.user.name}}
    </router-link>
</h6>
</code>```

my profile page code is :

```<code>data(){
       return {
               id: this.$route.params.id,
               user: {},
               thoughts: {},
               }
        },
methods:{
         viewProfile() {
            axios.get('user_profile/' + this.id).then((response) => {
                this.user = response.data.user_data;
                this.thoughts = response.data.thoughts;
            }).catch(() => {

            });
        },
 watch:{
        '$route' : 'viewProfile'
    },
created() {
        this.viewProfile();
    }
</code>```

What can I try to resolve this problem?

答: sorry for the trouble mates i fixed the issue by changing some routes configurations. Really thankful for your efforts.There was a collision between my web routes and the vue routes which was solved.</p>

Body:
I am passing a user id from the router-link using params to display the detail of the user in the profile page and i am getting all the required data and also is displayed correctly but as soon as i reload the page the $route.params.id changes into undefined and the data which were shown are gone to get the data i have to again navigate to the index page and revisit the link.

my index.vue page with the router-link is as follow

    <router-link :to="{name: 'FrontProfile' , params: {
         id: post.user.id }}"
         tag="a" active-class="active">{{post.user.name}}
    </router-link>

my profile page code is :

data(){
       return {
               id: this.$route.params.id,
               user: {},
               thoughts: {},
               }
        },
methods:{
         viewProfile() {
            axios.get('user_profile/' + this.id).then((response) => {
                this.user = response.data.user_data;
                this.thoughts = response.data.thoughts;
            }).catch(() => {

            });
        },
 watch:{
        '$route' : 'viewProfile'
    },
created() {
        this.viewProfile();
    }

What can I try to resolve this problem?


问:
"Corda overlapexception in finality flow"
I have been upgrade my cordapps for a new version and after this, i have reached this error: "Multiple attachments define a file at br/com/seven/contracts/cte/cteproc.class., transaction: 2AC7EF8431AAF5C91AD7C6A8E363F862E65AD821E2455164F988C93AB8B04157"]</p>

答:
You will get this error when multiple jars contain that class file. Probably the old attachment with that file is still in Cordapp directory.
Make sure your file is unique across all the installed CorDapps.</p>


问:
What is the version of Akka Streams that Play 2.5 uses?

From version 2.5, Play’s default stream processing library is Akka
  Streams.

I cannot find the official docs anywhere and I'm wondering what exactly is the Akka Stream version that Play 2.5 uses?

答:
Play 2.5.x uses Akka 2.4.20:</p>

```<code>object Dependencies {

  val akkaVersion = "2.4.20"
  ...
  val streamsDependencies = Seq(
    "org.reactivestreams" % "reactive-streams" % "1.0.0",
    "com.typesafe.akka" %% "akka-stream" % akkaVersion,
  ...
}
</code>```

Body:
Play 2.5.x uses Akka 2.4.20:

object Dependencies {

  val akkaVersion = "2.4.20"
  ...
  val streamsDependencies = Seq(
    "org.reactivestreams" % "reactive-streams" % "1.0.0",
    "com.typesafe.akka" %% "akka-stream" % akkaVersion,
  ...
}


问:
Simple databinding IN CODE to a DependencyProperty
My apologies as this is simplistic enough I know the question's been answered but in 30 or so pages, I've yet to find the boiled down problem I'm trying to solve.

I'm not yet well practiced in SL and trying a simple version of attempting to write a TextBox that binds to a property within the screen and updates it when Text is altered and vice versa (property change propagates to the Text).  Due to a few reasons, I need to do this with DependencyProperties and in the codebehind rather than INotifyPropertyChanged and in XAML.

My latest attempts look something like this:

```<code>    public partial class MainPage : UserControl
{
    static MainPage()
    {
        TargetTextProperty = DependencyProperty.Register("TargetText", typeof(string), typeof(MainPage), new PropertyMetadata(new PropertyChangedCallback(TextChanged)));
    }

    public readonly static DependencyProperty TargetTextProperty;

    public string TargetText
    {
        get { return (string)GetValue(TargetTextProperty); }
        set { SetValue(TargetTextProperty, value); }
    }

    public MainPage()
    {
        InitializeComponent();

        TargetText = "testing";
        textBox1.DataContext = TargetText;
        Binding ResetBinding = new Binding("TargetText");
        ResetBinding.Mode = BindingMode.TwoWay;
        ResetBinding.Source = TargetText;

        textBox1.SetBinding(TextBox.TextProperty, ResetBinding);
    }

    private static void TextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MainPage pg = (MainPage)sender;
        pg.textBox1.Text = e.NewValue as string;
    }
}
</code>```

Anyone see what (painfully obvious thing?) I'm missing?

Thanks,

John

答:
The following should be enough to set the binding you want:

```<code>textBox1.SetBinding(TextBox.TextProperty, new Binding() { Path = "TargetText", Source = this });
</code>```

The problem with your code is that you set both Source and binding Path to the TargetText property and as a result you get the framework trying to bind to TargetText.TargetText, which is obviously wrong.

Body:
My apologies as this is simplistic enough I know the question's been answered but in 30 or so pages, I've yet to find the boiled down problem I'm trying to solve.

I'm not yet well practiced in SL and trying a simple version of attempting to write a TextBox that binds to a property within the screen and updates it when Text is altered and vice versa (property change propagates to the Text).  Due to a few reasons, I need to do this with DependencyProperties and in the codebehind rather than INotifyPropertyChanged and in XAML.

My latest attempts look something like this:

    public partial class MainPage : UserControl
{
    static MainPage()
    {
        TargetTextProperty = DependencyProperty.Register("TargetText", typeof(string), typeof(MainPage), new PropertyMetadata(new PropertyChangedCallback(TextChanged)));
    }

    public readonly static DependencyProperty TargetTextProperty;

    public string TargetText
    {
        get { return (string)GetValue(TargetTextProperty); }
        set { SetValue(TargetTextProperty, value); }
    }

    public MainPage()
    {
        InitializeComponent();

        TargetText = "testing";
        textBox1.DataContext = TargetText;
        Binding ResetBinding = new Binding("TargetText");
        ResetBinding.Mode = BindingMode.TwoWay;
        ResetBinding.Source = TargetText;

        textBox1.SetBinding(TextBox.TextProperty, ResetBinding);
    }

    private static void TextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MainPage pg = (MainPage)sender;
        pg.textBox1.Text = e.NewValue as string;
    }
}

Anyone see what (painfully obvious thing?) I'm missing?

Thanks,

John

Body:
The following should be enough to set the binding you want:

textBox1.SetBinding(TextBox.TextProperty, new Binding() { Path = "TargetText", Source = this });

The problem with your code is that you set both Source and binding Path to the TargetText property and as a result you get the framework trying to bind to TargetText.TargetText, which is obviously wrong.


问:
Not creating txt file in c drive by file operations in C language
I am trying to create a simple text file using TurboC++ DOS emulator. But, it's not creating the file. I am referring to an online video where the same file is getting created. What can be the issue?

Below is the code:

```<code>#include<stdio.h>
#include<stdlib.h>

int main()
{
  int num;
  FILE *fptr;

  fptr = fopen("c:\\program.txt","w");

  if(fptr == NULL)
  {
    printf("error");
    exit(1);
  }
  printf("enter num = ");
  scanf("%d", &num);

  fprintf(fptr,"%d",num);
  fclose(fptr);

  return 0;

}
</code>```

答: I switched DOS emulator to code blocks.</p>

Body:
I am trying to create a simple text file using TurboC++ DOS emulator. But, it's not creating the file. I am referring to an online video where the same file is getting created. What can be the issue?

Below is the code:

#include<stdio.h>
#include<stdlib.h>

int main()
{
  int num;
  FILE *fptr;

  fptr = fopen("c:\\program.txt","w");

  if(fptr == NULL)
  {
    printf("error");
    exit(1);
  }
  printf("enter num = ");
  scanf("%d", &num);

  fprintf(fptr,"%d",num);
  fclose(fptr);

  return 0;

}

Body: I switched DOS emulator to code blocks.


问:
Combining data from one column into one with multiplication

I am trying to find a way to add up amount with the same ID and different units but also perform multiplication or division on them before adding them together.
The column time describes the amount of time spent doing a certain task.
There are four different values the time column can have which are:
- Uur (which stands for Hours)
- Minuut (which stands for Minutes)
- Etmaal (which stands for 24 hours)
- Dagdeel (which stands for 4 hours)

What I'd like is to transform them all into hours which should eventually return the row:

```<code>ID | Amount  | Time |
---------------------
82 | 1690634 | Uur  |
</code>```

So only one unit remains.

This means rows that contain minuut will have their amount divided by 60
Rows that contain etmaal will have their amount multiplied by 24
and rows that contain dagdeel will have their amount multiplied by 4

答:
Please use below query,</p>

```<code>select id,
case when time = 'minuut' then amount/60
     when time = 'etmaal' then amount*24
     when time = 'dagdeel' then amount*4 end as amount,
time
from table;
</code>```

Body:
I am trying to find a way to add up amount with the same ID and different units but also perform multiplication or division on them before adding them together.
The column time describes the amount of time spent doing a certain task.
There are four different values the time column can have which are:
- Uur (which stands for Hours)
- Minuut (which stands for Minutes)
- Etmaal (which stands for 24 hours)
- Dagdeel (which stands for 4 hours)

What I'd like is to transform them all into hours which should eventually return the row:

ID | Amount  | Time |
---------------------
82 | 1690634 | Uur  |

So only one unit remains.

This means rows that contain minuut will have their amount divided by 60
Rows that contain etmaal will have their amount multiplied by 24
and rows that contain dagdeel will have their amount multiplied by 4

Body:
Please use below query,

select id,
case when time = 'minuut' then amount/60
     when time = 'etmaal' then amount*24
     when time = 'dagdeel' then amount*4 end as amount,
time
from table;


问:
Taking details from a map and saving it into another?
I have a map like this

```<code>map<string, pair< pair<int, int>, string> >
</code>```

what is the easiest way to get only the two strings and save into another map like this

```<code>map<string, string>
</code>```

?
I mean is there another way other than something like this??

```<code>    map<string, pair< pair<int, int>, string> >  info;
    map<string, pair< pair<int, int>, string> >::iterator i;
    map<string, string> something;

    for(i=info.begin(); i!=info.end(); ++i)
        something[*i).first] = ((*i).second).second;
</code>```

答:
First, I'd define a proper type:

```<code>struct Mapped
{
    int someSignificantName;
    int anotherName;
    std::string yetAnother;
};
</code>```

There are almost no cases where std::pair is an acceptable solution
(except for quick hacks and tests).  Given that, you define a mapping
functional object:

```<code>struct Remap
    : std::unary_operator<std::pair<std::string, Mapped>,
                          std::pair<std::string, std::string> >
{
    std::pair<std::string, std::string> operator()(
            std::pair<std::string, Mapped> const& in ) const
    {
        return std::make_pair( in.first, in.second.yetAnother );
    }
};
</code>```

, then use std::transform:

```<code>std::transform( in.begin(), in.end(),
                std::inserter( out, out.end() ),
                Remap() );
</code>```

Body:
I have a map like this

map<string, pair< pair<int, int>, string> >

what is the easiest way to get only the two strings and save into another map like this

map<string, string>

?
I mean is there another way other than something like this??

    map<string, pair< pair<int, int>, string> >  info;
    map<string, pair< pair<int, int>, string> >::iterator i;
    map<string, string> something;

    for(i=info.begin(); i!=info.end(); ++i)
        something[*i).first] = ((*i).second).second;

Body:
First, I'd define a proper type:

struct Mapped
{
    int someSignificantName;
    int anotherName;
    std::string yetAnother;
};

There are almost no cases where std::pair is an acceptable solution
(except for quick hacks and tests).  Given that, you define a mapping
functional object:

struct Remap
    : std::unary_operator<std::pair<std::string, Mapped>,
                          std::pair<std::string, std::string> >
{
    std::pair<std::string, std::string> operator()(
            std::pair<std::string, Mapped> const& in ) const
    {
        return std::make_pair( in.first, in.second.yetAnother );
    }
};

, then use std::transform:

std::transform( in.begin(), in.end(),
                std::inserter( out, out.end() ),
                Remap() );


问:
Advanced Rails Active Record Query
Calling Active Record query experts! I'm having problem debugging an N+1 query. Here's a summary of my models and the page that's causing the issue. I'd love to find a good way to create a query for this page, and figure out the best way to cache this page. Any help is much appreciated!!

```<code>class Brief < ApplicationRecord

  belongs_to :account
  has_one :user, through: :account
  has_many :submissions

class Account < ApplicationRecord

  belongs_to :user, touch: true
  has_many :briefs
end

class Submission < ApplicationRecord

  belongs_to :brief, touch: true
  belongs_to :user
</code>```

I have a page of @briefs where I'm looking to display for each brief:

Brief account name -> brief.account.name

Brief's submission status for the current_user -> brief.submissions.where(user: current_user).status ** Note this could return nil if a User has not created a Submission for a Brief

```<code>
class BriefsController < BaseController
  def index
    @briefs = Brief.includes([:account, :submissions]).order(expiration_date: :desc).live
  end

class Brief < ApplicationRecord
 ### CLASS METHODS
 def self.live
    Brief.all.select { |brief| brief.active? == true }
  end

</code>```

Currently this is how I'm caching the page:

live_briefs.html.erb

```<code><% cache @briefs, expires_in: 1.hour do %>
  <% @briefs.each do |brief| %>
    <% cache brief do %>
      <%= render 'live_briefs/components/brief', brief: brief %>
    <% end %>
  <% end %>
<% end %>
</code>```

_.brief.html.erb

```<code><%= brief.account.name %>
<%= live_brief_submission_status(brief, current_user) %>
</code>```

brief_helper.rb (this is what's causing the added queries)

```<code>def live_brief_submission_status(brief, user)
    submission = brief.submissions.where(user: user).first
    if submission.present?
      case submission.status
      when "approved"
        tag.div "Approved", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-indigo-100 text-indigo-800"
      when "invited"
        tag.div "Invited", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-green-400 text-white"
      when "pending"
        tag.div "Pending", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-gray-100 text-gray-800"
      when "declined"
        tag.div "Declined", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-red-100 text-red-800"
      else
      end
    else
      tag.div "Apply Now!", class: "inline-flex items-center pl-3 py-0.5 rounded-full text-sm font-medium leading-5 text-gray-800"
    end
  end
</code>```

And this is the output when I load the page:

```<code>Started GET "/briefs/live" for ::1 at 2020-06-01 15:34:11 -0700
Processing by LiveBriefsController#index as HTML
  User Load (5.9ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Brief Load (10.8ms)  SELECT "briefs".* FROM "briefs" ORDER BY "briefs"."expiration_date" DESC
  ↳ app/models/brief.rb:32:in `live'
  Account Load (7.5ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" IN ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)  [["id", 10], ["id", 4], ["id", 9], ["id", 3], ["id", 6], ["id", 5], ["id", 7], ["id", 2], ["id", 1], ["id", 8]]
  ↳ app/models/brief.rb:32:in `live'
  Submission Load (46.7ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" IN ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30)  [["brief_id", 27], ["brief_id", 9], ["brief_id", 21], ["brief_id", 22], ["brief_id", 10], ["brief_id", 29], ["brief_id", 24], ["brief_id", 3], ["brief_id", 1], ["brief_id", 6], ["brief_id", 25], ["brief_id", 7], ["brief_id", 2], ["brief_id", 23], ["brief_id", 5], ["brief_id", 28], ["brief_id", 26], ["brief_id", 30], ["brief_id", 8], ["brief_id", 4], ["brief_id", 14], ["brief_id", 17], ["brief_id", 16], ["brief_id", 11], ["brief_id", 13], ["brief_id", 20], ["brief_id", 12], ["brief_id", 15], ["brief_id", 19], ["brief_id", 18]]
  ↳ app/models/brief.rb:32:in `live'
  Rendering layouts/application.html.erb
  Rendering live_briefs/index.html.erb within layouts/application
  Rendered live_briefs/components/_title.html.erb (Duration: 0.1ms | Allocations: 55)
  Submission Load (1.2ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 9], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 32.0ms | Allocations: 3088)
  Submission Load (3.8ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 10], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 11.7ms | Allocations: 2119)
  Submission Load (27.0ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 3], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 49.2ms | Allocations: 2028)
  Submission Load (26.0ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 1], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 34.2ms | Allocations: 2034)
  Submission Load (0.7ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 6], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 8.2ms | Allocations: 2028)
  Submission Load (0.9ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 7], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 12.0ms | Allocations: 2028)
  Submission Load (12.5ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 2], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 18.2ms | Allocations: 2027)
  Submission Load (136.9ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 5], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 157.4ms | Allocations: 2405)
  Submission Load (168.4ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 8], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 177.6ms | Allocations: 2035)
  Submission Load (31.7ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 4], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 39.5ms | Allocations: 2029)
  Rendered live_briefs/index.html.erb within layouts/application (Duration: 581.8ms | Allocations: 23083)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layouts/_sidebar.html.erb (Duration: 9.3ms | Allocations: 1433)
  Rendered layouts/_notifications.html.erb (Duration: 1.8ms | Allocations: 86)
  Rendered application/_css_overrides.html.erb (Duration: 0.2ms | Allocations: 56)
  Rendered layouts/application.html.erb (Duration: 631.4ms | Allocations: 28281)
Completed 200 OK in 994ms (Views: 227.1ms | ActiveRecord: 484.8ms | Allocations: 93326)
</code>```

答:
First make sure the method is chainable by calling it on self so that you can add it to an existing relation:

```<code>class Brief < ApplicationRecord
  def self.live
   where(active: true)
  end
end
</code>```

Then make sure you eager load the needed data in the controller:

```<code>@briefs = Brief.live
               .eager_load(submissions: :user)
               .order(expiration_date: :desc)
</code>```

Instead of using .where which will always create a query use the methods from enumerable to traverse the association which is loaded in memory:

```<code>def live_brief_submission_status(brief, user)
  submission = brief.submissions.detect {|s| s.user = user }
  if submission.present?
    case submission.status
    when "approved"
      tag.div "Approved", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-indigo-100 text-indigo-800"
    when "invited"
      tag.div "Invited", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-green-400 text-white"
    when "pending"
      tag.div "Pending", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-gray-100 text-gray-800"
    when "declined"
      tag.div "Declined", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-red-100 text-red-800"
    end
  else
    tag.div "Apply Now!", class: "inline-flex items-center pl-3 py-0.5 rounded-full text-sm font-medium leading-5 text-gray-800"
  end
end
</code>```

But that query should really be refactored out of the helper method to reduce its cyclic complexity and redestribute the responsibilites.

Title: Advanced Rails Active Record Query

Body:
Calling Active Record query experts! I'm having problem debugging an N+1 query. Here's a summary of my models and the page that's causing the issue. I'd love to find a good way to create a query for this page, and figure out the best way to cache this page. Any help is much appreciated!!

class Brief < ApplicationRecord

  belongs_to :account
  has_one :user, through: :account
  has_many :submissions

class Account < ApplicationRecord

  belongs_to :user, touch: true
  has_many :briefs
end

class Submission < ApplicationRecord

  belongs_to :brief, touch: true
  belongs_to :user

I have a page of @briefs where I'm looking to display for each brief:

Brief account name -> brief.account.name

Brief's submission status for the current_user -> brief.submissions.where(user: current_user).status ** Note this could return nil if a User has not created a Submission for a Brief

class BriefsController < BaseController
  def index
    @briefs = Brief.includes([:account, :submissions]).order(expiration_date: :desc).live
  end

class Brief < ApplicationRecord
 ### CLASS METHODS
 def self.live
    Brief.all.select { |brief| brief.active? == true }
  end

Currently this is how I'm caching the page:

live_briefs.html.erb

<% cache @briefs, expires_in: 1.hour do %>
  <% @briefs.each do |brief| %>
    <% cache brief do %>
      <%= render 'live_briefs/components/brief', brief: brief %>
    <% end %>
  <% end %>
<% end %>

_.brief.html.erb

<%= brief.account.name %>
<%= live_brief_submission_status(brief, current_user) %>

brief_helper.rb (this is what's causing the added queries)

def live_brief_submission_status(brief, user)
    submission = brief.submissions.where(user: user).first
    if submission.present?
      case submission.status
      when "approved"
        tag.div "Approved", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-indigo-100 text-indigo-800"
      when "invited"
        tag.div "Invited", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-green-400 text-white"
      when "pending"
        tag.div "Pending", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-gray-100 text-gray-800"
      when "declined"
        tag.div "Declined", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-red-100 text-red-800"
      else
      end
    else
      tag.div "Apply Now!", class: "inline-flex items-center pl-3 py-0.5 rounded-full text-sm font-medium leading-5 text-gray-800"
    end
  end

And this is the output when I load the page:

Started GET "/briefs/live" for ::1 at 2020-06-01 15:34:11 -0700
Processing by LiveBriefsController#index as HTML
  User Load (5.9ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Brief Load (10.8ms)  SELECT "briefs".* FROM "briefs" ORDER BY "briefs"."expiration_date" DESC
  ↳ app/models/brief.rb:32:in `live'
  Account Load (7.5ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" IN ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)  [["id", 10], ["id", 4], ["id", 9], ["id", 3], ["id", 6], ["id", 5], ["id", 7], ["id", 2], ["id", 1], ["id", 8]]
  ↳ app/models/brief.rb:32:in `live'
  Submission Load (46.7ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" IN ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30)  [["brief_id", 27], ["brief_id", 9], ["brief_id", 21], ["brief_id", 22], ["brief_id", 10], ["brief_id", 29], ["brief_id", 24], ["brief_id", 3], ["brief_id", 1], ["brief_id", 6], ["brief_id", 25], ["brief_id", 7], ["brief_id", 2], ["brief_id", 23], ["brief_id", 5], ["brief_id", 28], ["brief_id", 26], ["brief_id", 30], ["brief_id", 8], ["brief_id", 4], ["brief_id", 14], ["brief_id", 17], ["brief_id", 16], ["brief_id", 11], ["brief_id", 13], ["brief_id", 20], ["brief_id", 12], ["brief_id", 15], ["brief_id", 19], ["brief_id", 18]]
  ↳ app/models/brief.rb:32:in `live'
  Rendering layouts/application.html.erb
  Rendering live_briefs/index.html.erb within layouts/application
  Rendered live_briefs/components/_title.html.erb (Duration: 0.1ms | Allocations: 55)
  Submission Load (1.2ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 9], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 32.0ms | Allocations: 3088)
  Submission Load (3.8ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 10], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 11.7ms | Allocations: 2119)
  Submission Load (27.0ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 3], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 49.2ms | Allocations: 2028)
  Submission Load (26.0ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 1], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 34.2ms | Allocations: 2034)
  Submission Load (0.7ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 6], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 8.2ms | Allocations: 2028)
  Submission Load (0.9ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 7], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 12.0ms | Allocations: 2028)
  Submission Load (12.5ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 2], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 18.2ms | Allocations: 2027)
  Submission Load (136.9ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 5], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 157.4ms | Allocations: 2405)
  Submission Load (168.4ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 8], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 177.6ms | Allocations: 2035)
  Submission Load (31.7ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."brief_id" = $1 AND "submissions"."user_id" = $2 ORDER BY "submissions"."id" ASC LIMIT $3  [["brief_id", 4], ["user_id", 1], ["LIMIT", 1]]
  ↳ app/helpers/brief_helper.rb:20:in `live_brief_submission_status'
  Rendered live_briefs/components/_brief.html.erb (Duration: 39.5ms | Allocations: 2029)
  Rendered live_briefs/index.html.erb within layouts/application (Duration: 581.8ms | Allocations: 23083)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layouts/_sidebar.html.erb (Duration: 9.3ms | Allocations: 1433)
  Rendered layouts/_notifications.html.erb (Duration: 1.8ms | Allocations: 86)
  Rendered application/_css_overrides.html.erb (Duration: 0.2ms | Allocations: 56)
  Rendered layouts/application.html.erb (Duration: 631.4ms | Allocations: 28281)
Completed 200 OK in 994ms (Views: 227.1ms | ActiveRecord: 484.8ms | Allocations: 93326)

Body:
First make sure the method is chainable by calling it on self so that you can add it to an existing relation:

class Brief < ApplicationRecord
  def self.live
   where(active: true)
  end
end

Then make sure you eager load the needed data in the controller:

@briefs = Brief.live
               .eager_load(submissions: :user)
               .order(expiration_date: :desc)

Instead of using .where which will always create a query use the methods from enumerable to traverse the association which is loaded in memory:

def live_brief_submission_status(brief, user)
  submission = brief.submissions.detect {|s| s.user = user }
  if submission.present?
    case submission.status
    when "approved"
      tag.div "Approved", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-indigo-100 text-indigo-800"
    when "invited"
      tag.div "Invited", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-green-400 text-white"
    when "pending"
      tag.div "Pending", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-gray-100 text-gray-800"
    when "declined"
      tag.div "Declined", class: "inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium leading-5 bg-red-100 text-red-800"
    end
  else
    tag.div "Apply Now!", class: "inline-flex items-center pl-3 py-0.5 rounded-full text-sm font-medium leading-5 text-gray-800"
  end
end

But that query should really be refactored out of the helper method to reduce its cyclic complexity and redestribute the responsibilites.


问:
Local storage stores string once and will not change
I have this function where it shows the search listing in a card (recent searches). When I search something, it stores successfully in local storage but when I search another item the listing (recent search) doesn't update. Even after page refresh, the same first search stays in the card and won't update at all. Can anyone see whats happening and how to fix this? Thanks in advance!

Javascript:

```<code>function customDeal1() {

  var recentSearch = document.querySelector('#search').value;
  var HighScore = localStorage.getItem('highScore');

var matchArray = findDeals(HighScore, name).slice(0,1);
  const html = matchArray.map(place => {
    const regex = new RegExp(HighScore);
    const nameName = place.name.replace(regex, `<span class="hl">${HighScore}</span>`);
         var shop = place.url.replace(/(centra)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop1 = place.url.replace(/(tesco)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop2 = place.url.replace(/(aldi)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop3 = place.url.replace(/(lidl)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop4 = place.url.replace(/(supervalu)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
    return `

            <img src="${place.imgurl}" alt="Drink Image">
            <h5>${nameName}</h5>
            <p>${(place.price)} ${shop} ${shop1} ${shop2} ${shop3} ${shop4}</p>

    `;
  }).join('') || '<li> No Searches Found </li>';
  deal2.innerHTML = html;

if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}

};
const deal2 = document.querySelector('.deal1');
setInterval(customDeal1,5000);
</code>```

答:
how about this:</p>

```<code>        function customDeal1() {

        var recentSearch = document.querySelector('#search').value;
        var HighScore = localStorage.getItem('highScore');
        deal2.innerHTML = recentSearch;

        // delete the conditions : if(!localStorage.getItem('highScore') ...
        localStorage.setItem('highScore', recentSearch);

    };
    const deal2 = document.querySelector('.deal1');
    setInterval(customDeal1, 5000);
</code>```

Body:
I have this function where it shows the search listing in a card (recent searches). When I search something, it stores successfully in local storage but when I search another item the listing (recent search) doesn't update. Even after page refresh, the same first search stays in the card and won't update at all. Can anyone see whats happening and how to fix this? Thanks in advance!

Javascript:

function customDeal1() {

  var recentSearch = document.querySelector('#search').value;
  var HighScore = localStorage.getItem('highScore');

var matchArray = findDeals(HighScore, name).slice(0,1);
  const html = matchArray.map(place => {
    const regex = new RegExp(HighScore);
    const nameName = place.name.replace(regex, `<span class="hl">${HighScore}</span>`);
         var shop = place.url.replace(/(centra)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop1 = place.url.replace(/(tesco)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop2 = place.url.replace(/(aldi)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop3 = place.url.replace(/(lidl)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop4 = place.url.replace(/(supervalu)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
    return `

${nameName}

${(place.price)} ${shop} ${shop1} ${shop2} ${shop3} ${shop4}

    `;
  }).join('') || '
 No Searches Found
';
  deal2.innerHTML = html;

if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}

};
const deal2 = document.querySelector('.deal1');
setInterval(customDeal1,5000);

Body:
how about this:

        function customDeal1() {

        var recentSearch = document.querySelector('#search').value;
        var HighScore = localStorage.getItem('highScore');
        deal2.innerHTML = recentSearch;

        // delete the conditions : if(!localStorage.getItem('highScore') ...
        localStorage.setItem('highScore', recentSearch);

    };
    const deal2 = document.querySelector('.deal1');
    setInterval(customDeal1, 5000);


问:
Flutter: How to Retrieve field within documents below
I want to retrieve the hasVoted field within all these documents shown in the image attached (i have that hasVoted field within all the documents created). Below is my code but it does not seem to be working. What am i doing wrong and what is the proper way of retrieving those fields?

```<code>_checkUserVotes(context, data) async {

bool hasVoted = false;
final record = Record.fromSnapshot(data);

getData() async {

return await Firestore.instance.collection("finance").getDocuments();

}

getData().then((val){

if(hasVoted == true){

  return Text("Sorry you have voted already");
}

else if(hasVoted != true){

 return GestureDetector(

    onTap: () => record.reference.updateData({'votes': record.votes + 1}),

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

this is the Backened

答:
Assuming that your collection is called finance you need to access the Map field that is inside each document.

```<code>QuerySnapshot snapshot = await Firestore.instance.collection("finance").getDocuments();

snapshot.documents.forEach((document){
      if(document.data != null && document.data['hasVoted']['yourId']){
        print('Has voted');
      }
    });
</code>```

Now the thing is, I don't know where do you get that yourID property from, but you should now.

If you want to iterate from them all, just use the value(s) directly from that map.

```<code>snapshot.documents.forEach((document){
      if(document.data['hasVoted'] is Map && (document.data['hasVoted'] as Map).values.first){
        print('Has voted');
      }
    });
</code>```

But I really recommend you to parse that data into a model (eg. MyModel.fromData(document)) that way you really increase the readability of your code.

Body:
I want to retrieve the hasVoted field within all these documents shown in the image attached (i have that hasVoted field within all the documents created). Below is my code but it does not seem to be working. What am i doing wrong and what is the proper way of retrieving those fields?

_checkUserVotes(context, data) async {

bool hasVoted = false;
final record = Record.fromSnapshot(data);

getData() async {

return await Firestore.instance.collection("finance").getDocuments();

}

getData().then((val){

if(hasVoted == true){

  return Text("Sorry you have voted already");
}

else if(hasVoted != true){

 return GestureDetector(

    onTap: () => record.reference.updateData({'votes': record.votes + 1}),

  );
}
});
}

this is the Backened

Body:
Assuming that your collection is called finance you need to access the Map field that is inside each document.

QuerySnapshot snapshot = await Firestore.instance.collection("finance").getDocuments();

snapshot.documents.forEach((document){
      if(document.data != null && document.data['hasVoted']['yourId']){
        print('Has voted');
      }
    });

Now the thing is, I don't know where do you get that yourID property from, but you should now.

If you want to iterate from them all, just use the value(s) directly from that map.

snapshot.documents.forEach((document){
      if(document.data['hasVoted'] is Map && (document.data['hasVoted'] as Map).values.first){
        print('Has voted');
      }
    });

But I really recommend you to parse that data into a model (eg. MyModel.fromData(document)) that way you really increase the readability of your code.


问:
Jenkins CI/CD runs a script after doing git pull on server
I want to create a CI/CD pipeline using Jenkins where whenever someone commits on master branch, two things happen on a specific "server" (EC2).

First, git pull to sync with latest change

Run a specific shell script present on server

Can you kindly point me in the right direction? I understand that git sync can be done with Jenkins plugin for git, but how can I run the second script "Using Jenkins flow"?

答:
One way to do it is to add the EC2 machine where you are running the script via SSH. To this install the SSH Plugin

Then follow the steps as given here

After this you can execute the scripts by creating a new pipeline. Either a free style or multibranch pipeline. Refer the article here


问:
iframe not support by any browser
I am getting this error in my console tab

Load denied by X-Frame-Options: “DENY” from
  “http://localhost:8000/media/song/bensound-betterdays.mp3”, site does
  not permit any framing. Attempted to load into
  “http://localhost:3000/home”.

I also followed this link to solve this problem, but it didn't help.

api-data:

```<code>[
    {
        "id": 1,
        "song": "http://localhost:8000/media/song/bensound-betterdays.mp3",

    },
]

</code>```

settings.py

```<code>CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

</code>```

./src/Home.js

```<code>import React, {Component} from "react";

class App extends Component{

    constructor(props) {
    super(props);

    this.state = {
      response: "",
    };

  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData = async () => {

    try {
      const response = await fetch(
        `http://localhost:8000/api/music`
      );
      const JsonResponse = await response.json();
      this.setState({ response: JsonResponse });
    }
    catch (error) {
      console.log(error);
    }
  };

    render(){

        const { response } = this.state;

         if (!response) {
          return "Loading...";
        }

        return(

                     <div class="home">

                         {response.map((response) =>(

                            <div class="home_content">
                                <div class="track track_home">
                                    <iframe width="100%" height="166" src={response.song}></iframe>
                                </div>
                            </div>

                            ))}

                        </div>

            )
    }
}

export default App;

</code>```

答:
Change settings.py as:

```<code>X_FRAME_OPTIONS = 'http://localhost:8000'
</code>```

Title: iframe not support by any browser

Body:
I am getting this error in my console tab

Load denied by X-Frame-Options: “DENY” from
  “http://localhost:8000/media/song/bensound-betterdays.mp3”, site does
  not permit any framing. Attempted to load into
  “http://localhost:3000/home”.

I also followed this link to solve this problem, but it didn't help.

api-data:

[
    {
        "id": 1,
        "song": "http://localhost:8000/media/song/bensound-betterdays.mp3",

    },
]

settings.py

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

./src/Home.js

import React, {Component} from "react";

class App extends Component{

    constructor(props) {
    super(props);

    this.state = {
      response: "",
    };

  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData = async () => {

    try {
      const response = await fetch(
        `http://localhost:8000/api/music`
      );
      const JsonResponse = await response.json();
      this.setState({ response: JsonResponse });
    }
    catch (error) {
      console.log(error);
    }
  };

    render(){

        const { response } = this.state;

         if (!response) {
          return "Loading...";
        }

        return(

                         {response.map((response) =>(

                            ))}

            )
    }
}

export default App;

Body:
Change settings.py as:

X_FRAME_OPTIONS = 'http://localhost:8000'


问:
Cannot Understand The Exception
This is the code :

```<code>import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}
</code>```

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.

答:
This works fine :
Since you are using graphics in swing, this will help.

```<code>import java.awt.*;
import javax.swing.*;

class tester_1 extends JPanel{
JFrame fr;
JPanel p;

tester_1() {
 buildGUI();
}

public void buildGUI() {
fr=new JFrame();
p=new JPanel();
p.setBackground(Color.red);
}

 @Override
protected void paintComponent(Graphics g) {
 super.paintComponent(g);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
}
}

class tester {
 tester() {
  JFrame frm=new JFrame();
  tester_1 t=new tester_1();
  frm.add(t);
  frm.setVisible(true);
  frm.setSize(500,500);
 }

  public static void main(String args[]) {
     new tester();
   }
  }
</code>```

The exception that you have been getting is because you didn't initialize the variable g.

Title: Cannot Understand The Exception

Body:
This is the code :

import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.

Body:
This works fine :
Since you are using graphics in swing, this will help.

import java.awt.*;
import javax.swing.*;

class tester_1 extends JPanel{
JFrame fr;
JPanel p;

tester_1() {
 buildGUI();
}

public void buildGUI() {
fr=new JFrame();
p=new JPanel();
p.setBackground(Color.red);
}

 @Override
protected void paintComponent(Graphics g) {
 super.paintComponent(g);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
}
}

class tester {
 tester() {
  JFrame frm=new JFrame();
  tester_1 t=new tester_1();
  frm.add(t);
  frm.setVisible(true);
  frm.setSize(500,500);
 }

  public static void main(String args[]) {
     new tester();
   }
  }

The exception that you have been getting is because you didn't initialize the variable g.


问:
Web scraping in Python - extract a value from website
I'm trying to extract two values from this website:

bizportal.co.il

One value is the dollar rate from the right, and from the left the drop/rise in percentage.

The problem is that, after I'm getting the dollar rate value, the number is rounded from some reason. (You can see in the terminal). I want to get the exactly number as shown in the website.

Is there some friendly documentation for web scraping in Python?

P.S: how can I get rid of the pop up Python terminal window when running a code in VS ? I just want the output will be in VS - in the interactive window.

```<code>my_url = "https://www.bizportal.co.il/forex/quote/generalview/22212222"

uClient = urlopen(my_url)

page_html = uClient.read()

uClient.close()

page_soup = BeautifulSoup(page_html, "html.parser")

div_class = page_soup.findAll("div",{"class":"data-row"})

print (div_class)
#print(div_class[0].text)
#print(div_class[1].text)
</code>```

答:
The data is loaded dynamically via Ajax, but you can simulate this request with requests module:

```<code>import json
import requests

url = 'https://www.bizportal.co.il/forex/quote/generalview/22212222'
ajax_url = "https://www.bizportal.co.il/forex/quote/AjaxRequests/DailyDeals_Ajax?paperId={paperId}&take=20&skip=0&page=1&pageSize=20"
paper_id = url.rsplit('/')[-1]
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

data = requests.get(ajax_url.format(paperId=paper_id), headers=headers).json()

# uncomment this to print all data:
#print(json.dumps(data, indent=4))

# print first one
print(data['Data'][0]['rate'], data['Data'][0]['PrecentageRateChange'])
</code>```

Prints:

```<code>3.4823 -0.76%
</code>```

Body:
I'm trying to extract two values from this website:

bizportal.co.il

One value is the dollar rate from the right, and from the left the drop/rise in percentage.

The problem is that, after I'm getting the dollar rate value, the number is rounded from some reason. (You can see in the terminal). I want to get the exactly number as shown in the website.

Is there some friendly documentation for web scraping in Python?

P.S: how can I get rid of the pop up Python terminal window when running a code in VS ? I just want the output will be in VS - in the interactive window.

my_url = "https://www.bizportal.co.il/forex/quote/generalview/22212222"

uClient = urlopen(my_url)

page_html = uClient.read()

uClient.close()

page_soup = BeautifulSoup(page_html, "html.parser")

div_class = page_soup.findAll("div",{"class":"data-row"})

print (div_class)
#print(div_class[0].text)
#print(div_class[1].text)

Body:
The data is loaded dynamically via Ajax, but you can simulate this request with requests module:

import json
import requests

url = 'https://www.bizportal.co.il/forex/quote/generalview/22212222'
ajax_url = "https://www.bizportal.co.il/forex/quote/AjaxRequests/DailyDeals_Ajax?paperId={paperId}&take=20&skip=0&page=1&pageSize=20"
paper_id = url.rsplit('/')[-1]
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

data = requests.get(ajax_url.format(paperId=paper_id), headers=headers).json()

# uncomment this to print all data:
#print(json.dumps(data, indent=4))

# print first one
print(data['Data'][0]['rate'], data['Data'][0]['PrecentageRateChange'])

Prints:

3.4823 -0.76%


问:
How to prevent spring batch to start new instance of job?
Idea is not to start job if already same job is running.

JobExplorer is simple injected in class where is scheduled method for running

```<code>public class JobClass {

    private final Job job;
    private final JobExplorer jobExplorer;
    private final JobLauncher jobLauncher;

    public JobMain(Job job,
                   JobLauncher jobLauncher,
                   JobExplorer jobExplorer) {
        this.job = job;
        this.jobLauncher = jobLauncher;
        this.jobExplorer = jobExplorer;
    }
</code>```

and then it is executed

```<code>    @Scheduled("0 */5 * ? * *")
    public void startJob() {
        JobParameters jobParameters = new JobParametersBuilder()
                    .addString("jobName", String.valueOf(instant.toEpochMilli()))
                    .toJobParameters();
        jobLauncher.run(job, jobParameters);
    }
</code>```

This is not solution because if JVM stopped while job is running this will be same as current job running:

```<code>jobExplorer.findRunningJobExecutions("jobName")
</code>```

It will find all jobs with exitCode ExitStatus.UNKNOWN.

There is 3 solutions as I see it:

Solution 1:

stop previous running not finished jobs and run new job
PROS: everything is clean, just one property

CONT: loosing current execution of current job

```<code>@Scheduled("0 */5 * ? * *")
public void startJob() {
    (JobExecution jobExecution: jobExplorer.findRunningJobExecutions("jobName")) jobExecution.stop();
    ...
}
</code>```

Solution 2

Calculate time between latest running job like it is here described and if it is any do not start new job:
https://stackoverflow.com/a/23218986/1182625

PROS: everything is clean

CONT: have to have doubled property (5 *60*1000 and "0 */5 * ? * *")

```<code>Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("jobName");
        if(jobExecutions.size()>1){
            Long currentTime = (new Date()).getTime();
            for(JobExecution execution : jobExecutions) {
                if((currentTime - execution.getStartTime().getTime()) < 5*60*1000) {
                    return;
                } else {
                    execution.stop();
                }
            }

        }
</code>```

Solution 3

Idea is simple to add static (to share between instances of class) volatile (to share between threads) flag which will indicate is any job currently running
PROS: just one property

CONT: needs 2 listeners, and volatile static variable which i don't know how reacted in multi-nodes environment

```<code>    private static volatile boolean FINISHED = true;
</code>```

and then simple add listener and FINISHED modify method:

```<code>// reset FINISHED after job is done
     @AfterJob
     public void afterJob() {
         FINISHED = true;
     }

    public void setFinished() {
        this.FINISHED = true;
    }
</code>```

And simple add:

```<code>    @Scheduled("0 */5 * ? * *")
    public void startJob() {
    if(!FINISHED) return;
    FINISHED = false;
    ...
    }
</code>```

And finally add StepListener

```<code>public MyStepListener() {
...
    @AfterStep
    public ExitStatus afterStep(StepExecution stepExecution) {
    if(stepExecution.getExitStatus().getExitCode().equalsIgnoreCase(ExitStatus.FAILED.getExitCode()))  (new JobMain()).setFinished();
    return null;
    }
</code>```

答:
Ok, I think I go to far with something could be KISS.

Keep It Simple & Stupid.

So, to achieve this is simple to put fixedDelay or fixedStringDelay in @Scheduled annotation if you want to use value from properties file.

```<code>@Scheduled(initialDelay = 3*60*1000, fixedDelayString ="${job.fixed_delay}")
</code>```

With this I achieve that I don't have more than 1 instance of same job at same time.
I only lose that job start at exactly time (like ad midnight or...)

Body:
Idea is not to start job if already same job is running.

JobExplorer is simple injected in class where is scheduled method for running

public class JobClass {

    private final Job job;
    private final JobExplorer jobExplorer;
    private final JobLauncher jobLauncher;

    public JobMain(Job job,
                   JobLauncher jobLauncher,
                   JobExplorer jobExplorer) {
        this.job = job;
        this.jobLauncher = jobLauncher;
        this.jobExplorer = jobExplorer;
    }

and then it is executed

    @Scheduled("0 */5 * ? * *")
    public void startJob() {
        JobParameters jobParameters = new JobParametersBuilder()
                    .addString("jobName", String.valueOf(instant.toEpochMilli()))
                    .toJobParameters();
        jobLauncher.run(job, jobParameters);
    }

This is not solution because if JVM stopped while job is running this will be same as current job running:

jobExplorer.findRunningJobExecutions("jobName")

It will find all jobs with exitCode ExitStatus.UNKNOWN.

There is 3 solutions as I see it:

Solution 1:

stop previous running not finished jobs and run new job
PROS: everything is clean, just one property

CONT: loosing current execution of current job

@Scheduled("0 */5 * ? * *")
public void startJob() {
    (JobExecution jobExecution: jobExplorer.findRunningJobExecutions("jobName")) jobExecution.stop();
    ...
}

Solution 2

Calculate time between latest running job like it is here described and if it is any do not start new job:
https://stackoverflow.com/a/23218986/1182625

PROS: everything is clean

CONT: have to have doubled property (5 *60*1000 and "0 */5 * ? * *")

Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("jobName");
        if(jobExecutions.size()>1){
            Long currentTime = (new Date()).getTime();
            for(JobExecution execution : jobExecutions) {
                if((currentTime - execution.getStartTime().getTime()) < 5*60*1000) {
                    return;
                } else {
                    execution.stop();
                }
            }

        }

Solution 3

Idea is simple to add static (to share between instances of class) volatile (to share between threads) flag which will indicate is any job currently running
PROS: just one property

CONT: needs 2 listeners, and volatile static variable which i don't know how reacted in multi-nodes environment

    private static volatile boolean FINISHED = true;

and then simple add listener and FINISHED modify method:

// reset FINISHED after job is done
     @AfterJob
     public void afterJob() {
         FINISHED = true;
     }

    public void setFinished() {
        this.FINISHED = true;
    }

And simple add:

    @Scheduled("0 */5 * ? * *")
    public void startJob() {
    if(!FINISHED) return;
    FINISHED = false;
    ...
    }

And finally add StepListener

public MyStepListener() {
...
    @AfterStep
    public ExitStatus afterStep(StepExecution stepExecution) {
    if(stepExecution.getExitStatus().getExitCode().equalsIgnoreCase(ExitStatus.FAILED.getExitCode()))  (new JobMain()).setFinished();
    return null;
    }

Body:
Ok, I think I go to far with something could be KISS.

Keep It Simple & Stupid.

So, to achieve this is simple to put fixedDelay or fixedStringDelay in @Scheduled annotation if you want to use value from properties file.

@Scheduled(initialDelay = 3*60*1000, fixedDelayString ="${job.fixed_delay}")

With this I achieve that I don't have more than 1 instance of same job at same time.
I only lose that job start at exactly time (like ad midnight or...)


问:
Why interface type doesn't provide an "IsNil" method?
First let's consider the following:

```<code>func process(body io.Reader) {
    fmt.Printf("body == nil ? %+v\n", body == nil)
}

func main() {
    var body *bytes.Buffer
    fmt.Printf("body == nil ? %+v\n", body == nil)
    process(body)
    process(nil)
}
</code>```

And here's the output:

```<code>body == nil ? true
body == nil ? false  // Did you get this right?
body == nil ? true
</code>```

Another example:

```<code>type Container struct {
    Reader io.Reader
}

func processContainer(container Container) {
    fmt.Printf("container.Reader == nil ? %+v\n", container.Reader == nil)
}

func main() {
    var body *bytes.Buffer
    processContainer(Container{Reader: body})
    processContainer(Container{Reader: nil})
}
</code>```

Output:

```<code>container.Reader == nil ? false // Did you get this right?
container.Reader == nil ? true
</code>```

The explanation for this is at https://golang.org/doc/faq#nil_error.

A naive solution is to make the == nil test just return true if the interface object contains nil value.  But this would violate transitivity of ==, as it would assert two objects with nil value but different interface types true under ==.

However, I wonder if there should be an IsNil() method on all interface types, which would solve this issue?

Another example, this line from Go http client, can catch you unexpectedly:

https://github.com/golang/go/blob/master/src/net/http/client.go#L545

So if you call it like this

```<code>var body *bytes.Buffer
http.NewRequest(method, path, body)
</code>```

You'll get a nil pointer exception, even though, by the look of the source code, this shouldn't happen.

Edit

Sorry I referenced the wrong line of the Go http source, now corrected.
But the example still holds.

Edit 2

I've highlighted my question to make it clear what I'm asking.

答:
Here's a function that reports if an interface contains any nil. Note that reflect.Value.IsNil() panics if the type doesn't have a nil value, so some checking on the kind must be done before calling it.

```<code>func isNil(x interface{}) bool {
    v := reflect.ValueOf(x)
    switch v.Kind() {
    case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Slice:
        return v.IsNil()
    default:
        return false
    }
}
</code>```

Here's a working example in the playground: https://play.golang.org/p/RHzu3VVj4Zd

Body:
First let's consider the following:

func process(body io.Reader) {
    fmt.Printf("body == nil ? %+v\n", body == nil)
}

func main() {
    var body *bytes.Buffer
    fmt.Printf("body == nil ? %+v\n", body == nil)
    process(body)
    process(nil)
}

And here's the output:

body == nil ? true
body == nil ? false  // Did you get this right?
body == nil ? true

Another example:

type Container struct {
    Reader io.Reader
}

func processContainer(container Container) {
    fmt.Printf("container.Reader == nil ? %+v\n", container.Reader == nil)
}

func main() {
    var body *bytes.Buffer
    processContainer(Container{Reader: body})
    processContainer(Container{Reader: nil})
}

Output:

container.Reader == nil ? false // Did you get this right?
container.Reader == nil ? true

The explanation for this is at https://golang.org/doc/faq#nil_error.

A naive solution is to make the == nil test just return true if the interface object contains nil value.  But this would violate transitivity of ==, as it would assert two objects with nil value but different interface types true under ==.

However, I wonder if there should be an IsNil() method on all interface types, which would solve this issue?

Another example, this line from Go http client, can catch you unexpectedly:

https://github.com/golang/go/blob/master/src/net/http/client.go#L545

So if you call it like this

var body *bytes.Buffer
http.NewRequest(method, path, body)

You'll get a nil pointer exception, even though, by the look of the source code, this shouldn't happen.

Edit

Sorry I referenced the wrong line of the Go http source, now corrected.
But the example still holds.

Edit 2

I've highlighted my question to make it clear what I'm asking.

Body:
Here's a function that reports if an interface contains any nil. Note that reflect.Value.IsNil() panics if the type doesn't have a nil value, so some checking on the kind must be done before calling it.

func isNil(x interface{}) bool {
    v := reflect.ValueOf(x)
    switch v.Kind() {
    case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Slice:
        return v.IsNil()
    default:
        return false
    }
}

Here's a working example in the playground: https://play.golang.org/p/RHzu3VVj4Zd


问:
robust continuous TCP connection (python socket)
My goal is to establish a continuous and robust TCP connection between one server and exactly one client. If one side fails, the other one should wait until it recovers.

I wrote the following code based on this question (that only asks for continuous, but not robust TCP connections and does not handle keepalive issues), this post and my own experience.

I have two questions:

How can I make the keepalive work? If the server dies, the client only recognizes it after trying to send() - which worked also without the KEEPALIVE option as this results in a connection reset. Is there some way that the socket sends an interrupt for a connection that is dead or some keepalive function that I can check on a regular basis?

Is this a robust way of handling a continous TCP connection? Having a stable, continous TCP connection seems to be a standard problem, however, I couldn't find tutorials covering this in detail. There must be some best-practice.

Note, I could handle keep alive messages on my own at the application level. However, as TCP already implements this at transport level, it is better to rely on this service provided by the lower level.

The server:

```<code>from socket import *
serverPort = 12000

while True:
    # 1. Configure server socket
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serverSocket.bind(('127.0.0.1', serverPort))
    serverSocket.listen(1)
    print("waiting for client connecting...")
    connectionSocket, addr = serverSocket.accept()
    connectionSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
    print(connectionSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    print("...connected.")
    serverSocket.close() # Destroy the server socket; we don't need it anymore since we are not accepting any connections beyond this point.

    # 2. communication routine
    while True:
        try:
            sentence = connectionSocket.recv(512).decode()
        except ConnectionResetError as e:
            print("Client connection closed")
            break
        if(len(sentence)==0): # close if client closed connection
            break
        else:
            print("recv: "+str(sentence))

    # 3. proper closure
    connectionSocket.shutdown(SHUT_RDWR)
    connectionSocket.close()
    print("connection closed.")
</code>```

The client:

```<code>from socket import *
import time

while True:
    # 1. configure socket dest.
    serverName = '127.0.0.1'
    serverPort = 12000
    clientSocket = socket(AF_INET, SOCK_STREAM)
    try:
        clientSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
        clientSocket.connect((serverName, serverPort))
        print(clientSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    except ConnectionRefusedError as e:
        print("Server refused connection. retrying")
        time.sleep(1)
        continue

    # 2. communication routine
    while(1):
        sentence = input('input sentence: ')
        if(sentence == "close"):
            break
        try:
            clientSocket.send(sentence.encode())
        except ConnectionResetError as e:
            print("Server connection closed")
            break

    # 3. proper closure
    clientSocket.shutdown(SHUT_RDWR)
    clientSocket.close()
</code>```

I tried to hold this example as minimal as possible. But given the requirement of robustness, it is relativley long.

I also tried some socket options as TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT.

Thank you!

答:
I will try to answer both questions.

... Is there some way that the socket sends an interrupt for a connection that is dead ...

I know none. TCP_KEEPALIVE only tries to maintain the connection. It is very useful if any equipment on the network flow has a timeout, because it prevents the timeout to abort the connection. But if the connection drops because because of any other reason (that timeout) TCP_KEEPALIVE cannot do anything. The rationale is that there is no need to restore a dropped inactive connection before something has to be exchanged.

Is this a robust way of handling a continous TCP connection?

Not really.

The robust way is to be prepared that the connection fails for any reason at any moment. So you should be prepared to face an error when sending a message (your code is) and if that happens try to re-open the connection and send the message again (your current code does not). Something like:

```<code>def connect(...):
    # establish and return a connection
    ...
    return clientSocket

clientSocket = connect(...)
while True:
    ...
    while True:
        try:
            clientSocket.send(message)
            break
        except OSError:
            clientSocket = connect()
    ...
</code>```

Unrelated: your graceful shutdown is incorrect. The initiator (the part using shutdown) should not immediately close the socket, but start a read loop and only close when everything has be received and processed.

Body:
My goal is to establish a continuous and robust TCP connection between one server and exactly one client. If one side fails, the other one should wait until it recovers.

I wrote the following code based on this question (that only asks for continuous, but not robust TCP connections and does not handle keepalive issues), this post and my own experience.

I have two questions:

How can I make the keepalive work? If the server dies, the client only recognizes it after trying to send() - which worked also without the KEEPALIVE option as this results in a connection reset. Is there some way that the socket sends an interrupt for a connection that is dead or some keepalive function that I can check on a regular basis?

Is this a robust way of handling a continous TCP connection? Having a stable, continous TCP connection seems to be a standard problem, however, I couldn't find tutorials covering this in detail. There must be some best-practice.

Note, I could handle keep alive messages on my own at the application level. However, as TCP already implements this at transport level, it is better to rely on this service provided by the lower level.

The server:

from socket import *
serverPort = 12000

while True:
    # 1. Configure server socket
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serverSocket.bind(('127.0.0.1', serverPort))
    serverSocket.listen(1)
    print("waiting for client connecting...")
    connectionSocket, addr = serverSocket.accept()
    connectionSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
    print(connectionSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    print("...connected.")
    serverSocket.close() # Destroy the server socket; we don't need it anymore since we are not accepting any connections beyond this point.

    # 2. communication routine
    while True:
        try:
            sentence = connectionSocket.recv(512).decode()
        except ConnectionResetError as e:
            print("Client connection closed")
            break
        if(len(sentence)==0): # close if client closed connection
            break
        else:
            print("recv: "+str(sentence))

    # 3. proper closure
    connectionSocket.shutdown(SHUT_RDWR)
    connectionSocket.close()
    print("connection closed.")

The client:

from socket import *
import time

while True:
    # 1. configure socket dest.
    serverName = '127.0.0.1'
    serverPort = 12000
    clientSocket = socket(AF_INET, SOCK_STREAM)
    try:
        clientSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
        clientSocket.connect((serverName, serverPort))
        print(clientSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    except ConnectionRefusedError as e:
        print("Server refused connection. retrying")
        time.sleep(1)
        continue

    # 2. communication routine
    while(1):
        sentence = input('input sentence: ')
        if(sentence == "close"):
            break
        try:
            clientSocket.send(sentence.encode())
        except ConnectionResetError as e:
            print("Server connection closed")
            break

    # 3. proper closure
    clientSocket.shutdown(SHUT_RDWR)
    clientSocket.close()

I tried to hold this example as minimal as possible. But given the requirement of robustness, it is relativley long.

I also tried some socket options as TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT.

Thank you!

Body:
I will try to answer both questions.

... Is there some way that the socket sends an interrupt for a connection that is dead ...

I know none. TCP_KEEPALIVE only tries to maintain the connection. It is very useful if any equipment on the network flow has a timeout, because it prevents the timeout to abort the connection. But if the connection drops because because of any other reason (that timeout) TCP_KEEPALIVE cannot do anything. The rationale is that there is no need to restore a dropped inactive connection before something has to be exchanged.

Is this a robust way of handling a continous TCP connection?

Not really.

The robust way is to be prepared that the connection fails for any reason at any moment. So you should be prepared to face an error when sending a message (your code is) and if that happens try to re-open the connection and send the message again (your current code does not). Something like:

def connect(...):
    # establish and return a connection
    ...
    return clientSocket

clientSocket = connect(...)
while True:
    ...
    while True:
        try:
            clientSocket.send(message)
            break
        except OSError:
            clientSocket = connect()
    ...

Unrelated: your graceful shutdown is incorrect. The initiator (the part using shutdown) should not immediately close the socket, but start a read loop and only close when everything has be received and processed.