问:
How to maintain scroll position in a SwiftUI TabView
Using a ScrollView inside a TabView I've noticed that the ScrollView does not maintain it's scroll position when I move back an forth between tabs. How do I change the below example to get the ScrollView to maintain it's scroll position?

```<code>import SwiftUI

struct HomeView: View {
    var body: some View {
        ScrollView {
            VStack {
                Text("Line 1")
                Text("Line 2")
                Text("Line 3")
                Text("Line 4")
                Text("Line 5")
                Text("Line 6")
                Text("Line 7")
                Text("Line 8")
                Text("Line 9")
                Text("Line 10")
            }
        }.font(.system(size: 80, weight: .bold))
    }
}

struct ContentView: View {
    @State private var selection = 0

    var body: some View {
        TabView(selection: $selection) {
            HomeView()
                .tabItem {
                    Image(systemName: "house")
                }.tag(0)

            Text("Out")
                .tabItem {
                    Image(systemName: "cloud")
                }.tag(1)
        }
    }
}
</code>```

答:
This answer is posted as a complement to the solution @oivvio linked in the answer from @arsenius, about how to use a UITabController filled with UIHostingControllers.

The answer in the link has one issue: if the children views have external SwiftUI dependencies, those children will not be updated. This is fine for most cases where children views only have internal states. However, if you are like me, a React developer who enjoys a global Redux system, you will be in trouble.

In order to resolve the issue, the key is to update rootView for each UIHostingController every time when updateUIViewController is called. My code also avoids creating unnecessary UIView or UIViewControllers: they are not that expensive to create if you do not add them to the view hierarchy, but still, the less waste the better.

Warning: the code does not support a dynamic tab view list. To support that correctly, we would like to identify each child tab view and do an array diff to add, order, or remove them correctly. That can be done in principle but goes beyond my need.

We first need a TabItem. It is made this way for the controller to grab all the information, without creating any UITabBarItem:

struct XNTabItem: View {
    let title: String
    let image: UIImage?
    let body: AnyView

    public init<Content: View>(title: String, image: UIImage?, @ViewBuilder content: () -> Content) {
        self.title = title
        self.image = image
        self.body = AnyView(content())
    }
}
```

<p>We then have the controller:</p>

<pre class="lang-swift prettyprint-override"><code>struct XNTabView: UIViewControllerRepresentable {
    let tabItems: [XNTabItem]

    func makeUIViewController(context: UIViewControllerRepresentableContext<XNTabView>) -> UITabBarController {
        let rootController = UITabBarController()
        rootController.viewControllers = tabItems.map {
            let host = UIHostingController(rootView: $0.body)
            host.tabBarItem = UITabBarItem(title: $0.title, image: $0.image, selectedImage: $0.image)
            return host
        }
        return rootController
    }

    func updateUIViewController(_ rootController: UITabBarController, context: UIViewControllerRepresentableContext<XNTabView>) {
        let children = rootController.viewControllers as! [UIHostingController<AnyView>]
        for (newTab, host) in zip(self.tabItems, children) {
            host.rootView = newTab.body
            if host.tabBarItem.title != host.tabBarItem.title {
                host.tabBarItem.title = host.tabBarItem.title
            }
            if host.tabBarItem.image != host.tabBarItem.image {
                host.tabBarItem.image = host.tabBarItem.image
            }
        }
    }
}
</code>```

Children controllers are initialized in makeUIViewController. Whenever updateUIViewController is called, we update each children controller's root view. I did not do a comparison for rootView because I feel the same check would be done at the framework level, according to Apple's description about how views are updated. I might be wrong.

To use it is really simple. The below is partial code I grabbed from a mock project I am currently doing:

class Model: ObservableObject {
    @Published var allHouseInfo = HouseInfo.samples

    public func flipFavorite(for id: Int) {
        if let index = (allHouseInfo.firstIndex { $0.id == id }) {
            allHouseInfo[index].isFavorite.toggle()
        }
    }
}

struct FavoritesView: View {
    let favorites: [HouseInfo]

    var body: some View {
        if favorites.count > 0 {
            return AnyView(ScrollView {
                ForEach(favorites) {
                    CardContent(info: $0)
                }
            })
        } else {
            return AnyView(Text("No Favorites"))
        }
    }
}

struct ContentView: View {
    static let housingTabImage = UIImage(systemName: "house.fill")
    static let favoritesTabImage = UIImage(systemName: "heart.fill")

    @ObservedObject var model = Model()

    var favorites: [HouseInfo] {
        get { model.allHouseInfo.filter { $0.isFavorite } }
    }

    var body: some View {
        XNTabView(tabItems: [
            XNTabItem(title: "Housing", image: Self.housingTabImage) {
                NavigationView {
                    ScrollView {
                        ForEach(model.allHouseInfo) {
                            CardView(info: $0)
                                .padding(.vertical, 8)
                                .padding(.horizontal, 16)
                        }
                    }.navigationBarTitle("Housing")
                }
            },
            XNTabItem(title: "Favorites", image: Self.favoritesTabImage) {
                NavigationView {
                    FavoritesView(favorites: favorites).navigationBarTitle("Favorites")
                }
            }
        ]).environmentObject(model)
    }
}
```

The state is lifted to a root level as Model and it carries mutation helpers. In the CardContent you could access the state and the helpers via an EnvironmentObject. The update would be done in the Model object, propagated to the ContentView, with our XNTabView notified and each of its UIHostController updated.

EDITs:

It turns out that .environmentObject can be put at the top level.

Body:
Using a ScrollView inside a TabView I've noticed that the ScrollView does not maintain it's scroll position when I move back an forth between tabs. How do I change the below example to get the ScrollView to maintain it's scroll position?

import SwiftUI

struct HomeView: View {
    var body: some View {
        ScrollView {
            VStack {
                Text("Line 1")
                Text("Line 2")
                Text("Line 3")
                Text("Line 4")
                Text("Line 5")
                Text("Line 6")
                Text("Line 7")
                Text("Line 8")
                Text("Line 9")
                Text("Line 10")
            }
        }.font(.system(size: 80, weight: .bold))
    }
}

struct ContentView: View {
    @State private var selection = 0

    var body: some View {
        TabView(selection: $selection) {
            HomeView()
                .tabItem {
                    Image(systemName: "house")
                }.tag(0)

            Text("Out")
                .tabItem {
                    Image(systemName: "cloud")
                }.tag(1)
        }
    }
}

Body:
This answer is posted as a complement to the solution @oivvio linked in the answer from @arsenius, about how to use a UITabController filled with UIHostingControllers.

The answer in the link has one issue: if the children views have external SwiftUI dependencies, those children will not be updated. This is fine for most cases where children views only have internal states. However, if you are like me, a React developer who enjoys a global Redux system, you will be in trouble.

In order to resolve the issue, the key is to update rootView for each UIHostingController every time when updateUIViewController is called. My code also avoids creating unnecessary UIView or UIViewControllers: they are not that expensive to create if you do not add them to the view hierarchy, but still, the less waste the better.

Warning: the code does not support a dynamic tab view list. To support that correctly, we would like to identify each child tab view and do an array diff to add, order, or remove them correctly. That can be done in principle but goes beyond my need.

We first need a TabItem. It is made this way for the controller to grab all the information, without creating any UITabBarItem:

struct XNTabItem: View {
    let title: String
    let image: UIImage?
    let body: AnyView

    public init<Content: View>(title: String, image: UIImage?, @ViewBuilder content: () -> Content) {
        self.title = title
        self.image = image
        self.body = AnyView(content())
    }
}

We then have the controller:

struct XNTabView: UIViewControllerRepresentable {
    let tabItems: [XNTabItem]

    func makeUIViewController(context: UIViewControllerRepresentableContext<XNTabView>) -> UITabBarController {
        let rootController = UITabBarController()
        rootController.viewControllers = tabItems.map {
            let host = UIHostingController(rootView: $0.body)
            host.tabBarItem = UITabBarItem(title: $0.title, image: $0.image, selectedImage: $0.image)
            return host
        }
        return rootController
    }

    func updateUIViewController(_ rootController: UITabBarController, context: UIViewControllerRepresentableContext<XNTabView>) {
        let children = rootController.viewControllers as! [UIHostingController<AnyView>]
        for (newTab, host) in zip(self.tabItems, children) {
            host.rootView = newTab.body
            if host.tabBarItem.title != host.tabBarItem.title {
                host.tabBarItem.title = host.tabBarItem.title
            }
            if host.tabBarItem.image != host.tabBarItem.image {
                host.tabBarItem.image = host.tabBarItem.image
            }
        }
    }
}

Children controllers are initialized in makeUIViewController. Whenever updateUIViewController is called, we update each children controller's root view. I did not do a comparison for rootView because I feel the same check would be done at the framework level, according to Apple's description about how views are updated. I might be wrong.

To use it is really simple. The below is partial code I grabbed from a mock project I am currently doing:

class Model: ObservableObject {
    @Published var allHouseInfo = HouseInfo.samples

    public func flipFavorite(for id: Int) {
        if let index = (allHouseInfo.firstIndex { $0.id == id }) {
            allHouseInfo[index].isFavorite.toggle()
        }
    }
}

struct FavoritesView: View {
    let favorites: [HouseInfo]

    var body: some View {
        if favorites.count > 0 {
            return AnyView(ScrollView {
                ForEach(favorites) {
                    CardContent(info: $0)
                }
            })
        } else {
            return AnyView(Text("No Favorites"))
        }
    }
}

struct ContentView: View {
    static let housingTabImage = UIImage(systemName: "house.fill")
    static let favoritesTabImage = UIImage(systemName: "heart.fill")

    @ObservedObject var model = Model()

    var favorites: [HouseInfo] {
        get { model.allHouseInfo.filter { $0.isFavorite } }
    }

    var body: some View {
        XNTabView(tabItems: [
            XNTabItem(title: "Housing", image: Self.housingTabImage) {
                NavigationView {
                    ScrollView {
                        ForEach(model.allHouseInfo) {
                            CardView(info: $0)
                                .padding(.vertical, 8)
                                .padding(.horizontal, 16)
                        }
                    }.navigationBarTitle("Housing")
                }
            },
            XNTabItem(title: "Favorites", image: Self.favoritesTabImage) {
                NavigationView {
                    FavoritesView(favorites: favorites).navigationBarTitle("Favorites")
                }
            }
        ]).environmentObject(model)
    }
}

The state is lifted to a root level as Model and it carries mutation helpers. In the CardContent you could access the state and the helpers via an EnvironmentObject. The update would be done in the Model object, propagated to the ContentView, with our XNTabView notified and each of its UIHostController updated.

EDITs:

It turns out that .environmentObject can be put at the top level.


来源: stackexchange

问:
Linq list of lists to one list
I have a Linq query that updates the first item in each conditioned group like this

```<code>var results = StudentsList.GroupBy(x => x.GroupID)
    .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
    .Select(g =>
            {
                var firstItem = g.First(x => x.University == "OPQ");
                firstItem.IsQualified = true;

                return firstItem;
            }).ToList();
</code>```

While preserving original functionality, I want to additionally-

If exists, update IsQualified= true for ALL students in same group with University!= "OPQ" and Course= "HR" (Group 2). If don't exist, just ignore (Group 5)

Output

Donald, Silver, Emity (all Group 2) and White (Group 5).

What I tried

Just below the "firstItem.IsQualified = true;" line, I added-

```<code>var otherItems=g.Any(x=>x.University != "OPQ" && x.Course =="HR");
otherItems.IsQualified= true;
</code>```

My Code

```<code>    List<StudentInfo> StudentsList = new List<StudentInfo>();

    // Group 1
    StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", Course="GD", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="John", University="abc", Course="ACC", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="Jack", University="def", Course="CS", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Peter", University="abc", Course="GD", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", Course="CS", GroupID = 1, IsQualified=false} );

    // Group 2
    StudentsList.Add( new StudentInfo { Student="Donald", University="def", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", Course="RC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Silver", University="tcs", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Carl", University="yyz", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );

    // Group 3
    StudentsList.Add( new StudentInfo { Student="Adam", University="yub", Course="CS", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", Course="AC",GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", Course="HR", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Saint", University="abc", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", Course="MNGT",  GroupID = 3, IsQualified=false} );

    // Group 4
    StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", Course="GD", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", Course="CS", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", Course="MNGT", GroupID = 4, IsQualified=false} );

    // Group 5
    StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", Course="ACC", GroupID = 5, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="White", University="OPQ", Course="CE", GroupID = 5, IsQualified=false} );

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public string Course { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}
}
</code>```

答:
Demo on dotnet fiddle

Instead of .Select(), You can also use SelectMany to achieve it.

```<code>    var results = StudentsList.GroupBy(x => x.GroupID)
                              .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
                              .SelectMany(g =>
                                    {
                                        var firstItem = g.First(x => x.University == "OPQ");
                                        firstItem.IsQualified = true;

                                        var otherItems = g.Where(x => x.University != "OPQ" && x.Course == "HR")
                                                          .Select(z =>
                                                                  {
                                                                      var item = z;
                                                                      item.IsQualified = true;
                                                                      return item;
                                                                  }).ToList();
                                        otherItems.Add(firstItem);
                                        return otherItems;
                                    }).ToList();
</code>```

Output

```<code>Group:2 Student:Donald IsQualified:True
Group:2 Student:Silver IsQualified:True
Group:2 Student:Emity IsQualified:True
Group:5 Student:White IsQualified:True
</code>```

ContentLicense: CC BY-SA 4.0

Title: Linq list of lists to one list

Body:
I have a Linq query that updates the first item in each conditioned group like this

var results = StudentsList.GroupBy(x => x.GroupID)
    .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
    .Select(g =>
            {
                var firstItem = g.First(x => x.University == "OPQ");
                firstItem.IsQualified = true;

                return firstItem;
            }).ToList();

While preserving original functionality, I want to additionally-

If exists, update IsQualified= true for ALL students in same group with University!= "OPQ" and Course= "HR" (Group 2). If don't exist, just ignore (Group 5)

Output

Donald, Silver, Emity (all Group 2) and White (Group 5).

What I tried

Just below the "firstItem.IsQualified = true;" line, I added-

var otherItems=g.Any(x=>x.University != "OPQ" && x.Course =="HR");
otherItems.IsQualified= true;

My Code

    List<StudentInfo> StudentsList = new List<StudentInfo>();

    // Group 1
    StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", Course="GD", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="John", University="abc", Course="ACC", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="Jack", University="def", Course="CS", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Peter", University="abc", Course="GD", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", Course="CS", GroupID = 1, IsQualified=false} );

    // Group 2
    StudentsList.Add( new StudentInfo { Student="Donald", University="def", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", Course="RC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Silver", University="tcs", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Carl", University="yyz", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );

    // Group 3
    StudentsList.Add( new StudentInfo { Student="Adam", University="yub", Course="CS", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", Course="AC",GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", Course="HR", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Saint", University="abc", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", Course="MNGT",  GroupID = 3, IsQualified=false} );

    // Group 4
    StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", Course="GD", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", Course="CS", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", Course="MNGT", GroupID = 4, IsQualified=false} );

    // Group 5
    StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", Course="ACC", GroupID = 5, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="White", University="OPQ", Course="CE", GroupID = 5, IsQualified=false} );

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public string Course { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}
}

Body:
Demo on dotnet fiddle

Instead of .Select(), You can also use SelectMany to achieve it.

    var results = StudentsList.GroupBy(x => x.GroupID)
                              .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
                              .SelectMany(g =>
                                    {
                                        var firstItem = g.First(x => x.University == "OPQ");
                                        firstItem.IsQualified = true;

                                        var otherItems = g.Where(x => x.University != "OPQ" && x.Course == "HR")
                                                          .Select(z =>
                                                                  {
                                                                      var item = z;
                                                                      item.IsQualified = true;
                                                                      return item;
                                                                  }).ToList();
                                        otherItems.Add(firstItem);
                                        return otherItems;
                                    }).ToList();

Output

Group:2 Student:Donald IsQualified:True
Group:2 Student:Silver IsQualified:True
Group:2 Student:Emity IsQualified:True
Group:5 Student:White IsQualified:True


问:
Ruby on Rails Tutorial chapter 9.3.3
I have tried to do chapter 9.3.3 in Ruby on Rails Tutorial (http://railstutorial.org).

Whenever I run the tests it say something along the lines of:

```<code>Failures:

  1) Users sign in/out success should sign a user in and out
     Failure/Error: user = Factory(:user)
     ActiveRecord::RecordInvalid:
       Validation failed: Email has already been taken
     # ./spec/requests/users_spec.rb:53:in `block (4 levels) in <top (required)>'

Finished in 5.8 seconds
4 examples, 1 failure
</code>```

I've tried various fixes including resetting the database - both using rake db:reset and rake db:populate.

I would appreciate any help.

Thanks in advance.

答: It seems that your test database is not wrapped around a transaction while your tests are running. This is causing you test database to persist between test runs. Use database cleaner to clean up your test database after each spec is run.</p>

ContentLicense: CC BY-SA 3.0

Title: Ruby on Rails Tutorial chapter 9.3.3

Body:
I have tried to do chapter 9.3.3 in Ruby on Rails Tutorial (http://railstutorial.org).

Whenever I run the tests it say something along the lines of:

Failures:

  1) Users sign in/out success should sign a user in and out
     Failure/Error: user = Factory(:user)
     ActiveRecord::RecordInvalid:
       Validation failed: Email has already been taken
     # ./spec/requests/users_spec.rb:53:in `block (4 levels) in <top (required)>'

Finished in 5.8 seconds
4 examples, 1 failure

I've tried various fixes including resetting the database - both using rake db:reset and rake db:populate.

I would appreciate any help.

Thanks in advance.


问:
Add parent array name into JSON as key:value
I have JSON like that:

```<code>{
  "binance_BTCUSDT": [
    {
      "price": "12/02 00:00",
      "time": "10232.79",
      "achg": -0.006151
    },
    {
      "time": "12/02 17:01",
      "price": "10342.92",
      "achg": -0.007977
    },
  ],
  "binance_ZECBNB": [
    {
      "time": "09/02 03:53",
      "price": "3.052",
      "achg": 0.1
    }
  ],
  "binance_ZENBTC": []
}
</code>```

How to add to any leaf key:value with name of parent array and remove such dividing into arrays at all?

I tried use jq with   .[][]|= . + {"pair": path(.) } , but I don't get how to write correctly path().

Expected output

```<code>[
  {
    "pair": "binance_BTCUSDT",
    "price": "12/02 00:00",
    "time": "10232.79",
    "achg": -0.006151
  },
  {
    "pair": "binance_BTCUSDT",
    "time": "12/02 17:01",
    "price": "10342.92",
    "achg": -0.007977
  },
  {
    "pair": "binance_ZECBNB",
    "time": "09/02 03:53",
    "price": "3.052",
    "achg": 0.1
  }
]
</code>```

答:
With your input (after correcting the minor error), the following jq filter produces the output shown below:

```<code>[ to_entries[] | {pair: .key} + .value[] ]
</code>```

Output

```<code>[
  {
    "pair": "binance_BTCUSDT",
    "price": "12/02 00:00",
    "time": "10232.79",
    "achg": -0.006151
  },
  {
    "pair": "binance_BTCUSDT",
    "time": "12/02 17:01",
    "price": "10342.92",
    "achg": -0.007977
  },
  {
    "pair": "binance_ZECBNB",
    "time": "09/02 03:53",
    "price": "3.052",
    "achg": 0.1
  }
]
</code>```

Variation

If you want to retain an entry corresponding to { "binance_ZENBTC": []}, then the following filter would be appropriate:

```<code>[to_entries[] | {pair: .key} + (.value[] // {}) ]
</code>```

Body:
I have JSON like that:

{
  "binance_BTCUSDT": [
    {
      "price": "12/02 00:00",
      "time": "10232.79",
      "achg": -0.006151
    },
    {
      "time": "12/02 17:01",
      "price": "10342.92",
      "achg": -0.007977
    },
  ],
  "binance_ZECBNB": [
    {
      "time": "09/02 03:53",
      "price": "3.052",
      "achg": 0.1
    }
  ],
  "binance_ZENBTC": []
}

How to add to any leaf key:value with name of parent array and remove such dividing into arrays at all?

I tried use jq with   .[][]|= . + {"pair": path(.) } , but I don't get how to write correctly path().

Expected output

[
  {
    "pair": "binance_BTCUSDT",
    "price": "12/02 00:00",
    "time": "10232.79",
    "achg": -0.006151
  },
  {
    "pair": "binance_BTCUSDT",
    "time": "12/02 17:01",
    "price": "10342.92",
    "achg": -0.007977
  },
  {
    "pair": "binance_ZECBNB",
    "time": "09/02 03:53",
    "price": "3.052",
    "achg": 0.1
  }
]

Body:
With your input (after correcting the minor error), the following jq filter produces the output shown below:

[ to_entries[] | {pair: .key} + .value[] ]

Output

[
  {
    "pair": "binance_BTCUSDT",
    "price": "12/02 00:00",
    "time": "10232.79",
    "achg": -0.006151
  },
  {
    "pair": "binance_BTCUSDT",
    "time": "12/02 17:01",
    "price": "10342.92",
    "achg": -0.007977
  },
  {
    "pair": "binance_ZECBNB",
    "time": "09/02 03:53",
    "price": "3.052",
    "achg": 0.1
  }
]

Variation

If you want to retain an entry corresponding to { "binance_ZENBTC": []}, then the following filter would be appropriate:

[to_entries[] | {pair: .key} + (.value[] // {}) ]


问:
Which flow for securing a data-only microservice with Openid
There are three parties in my application:

A web client W (written in Angular)

Microserice A ("my" microservice, developed in C++)

Microservice B (developed by a 3rd party but using SSO, trusted microservice)

General communication between those three: The web client W could be either a frontend UI or a mobile device using just the API as a service without having any sort of frontend. W connects to microservice A to manipulate and consume data from it. Microservice A exchanges data with microservice B and vice versa. W does not need to know about B.

I've settled on an architecture for the web client using Openid Authorization Code Flow with PKCE enabled to get and refresh it's token from Keycloak. I've posted a related question here [1].

Now consider this Web Application W is consuming some data from my microservice A. The JWT token from the web client is sent to the microservice as Bearer Authorization.

So far so good. What kind of flow should I use for the microservice itself, in order to enable the service to fetch and eventually refresh tokens for its own use for verification and user info requests? I've read quite a lot, but at almost every place there is a client at play in the workflow.

Can the PKCE Auth Code flow be used for microservices (e.g. instead of logging in let the server send credentials in exchange for a short-lived token)? Or should the microservice simply fetch tokens via secret in confidential mode?

Since I'm implementing the microservice in C++ it basically means there is a lack of libraries. Thus would be good if you detail the flow, since I have to implement it.

[1] OpenID redirect vs bearer

答:
If I understand correctly there are a couple of auth patterns going on:

Web Application W -> Microservice A    (User Involved)

Microservice A -> Microservice B       (NO User Involved)

(Maybe) Web Application W -> Microservice A -> Microservice B  (User Involved)

Any requests that come from the client (Web Application W) would use the Bearer Authorization which it sounds like you are currently doing.

When doing server to server auth you can setup another client in Keycloak and set the "Access Type" to "Confidential" (like you mentioned) and then Microservice A can get a token and use that to communicate with Microservice B securely.

If Web Application W is involved in a request to Microservice B (via Microservice A) you can just use the same bearer token that was on the header to Microservice A.


问:
Run my JavaScript code on every page on my browser, similar to how a Chrome extension would
I know with Chrome I can use snippets to manually run some JavaScript code on a webpage. But this required manually executing the snippet. Is there a way to have some JavaScript code that my browser (Chrome or Firefox) would load every time I visit a new page?</p>

答:
The Requestly Chrome and Firefox extension can solve your use case. You can use the Insert Script feature to inject any JavaScript code or CSS code before or after page load.

You can either enter a custom URL for the JavaScript file or write the custom JavaScript code in the inbuilt editor. You can also create a JavaScript/CSS file in Requestly library too and use that file.


问:
How should I use the GetDIBits function
```<code>var bitmap win.BITMAP
win.GetObject(win.HGDIOBJ(hBitmap), unsafe.Sizeof(bitmap), unsafe.Pointer(&bitmap))
var bmpInfo win.BITMAPINFO
bmpInfo.BmiHeader.BiSize = uint32(unsafe.Sizeof(Info.BmiHeader))
....................Width = width
....................Height = height
....................Planes = 1
....................BitCount = 24
....................Compression = win.BI_RGB
var hdc win.HDC
hdc = win.GetDC(0)
win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), bitmapInfo, nil, 0)
pBits := make([]byte, imageSize)
win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), bitmapInfo, (*byte)(unsafe.Pointer(&pBits)), 0)
</code>```

use package github.com/lxn/win

First of all, we have done all the work before getting the GetDIBits function.

After that, I finally try to get the image data using the GetDIBits function, but it keeps returning 0.

I changed the data type of pBits to 'unsafe.Pointer' or '* byte' and tried it but it returned nil or 0.

How can I get the image data from the GetDIBits function?

答:
I don't know much about Go language, but when you use GetDIBits, the position of parameters is incorrect.

lpvBits

A pointer to a buffer to receive the bitmap data. If this parameter is
  NULL, the function passes the dimensions and format of the bitmap to
  the BITMAPINFO structure pointed to by the lpbi parameter.

lpbmi

A pointer to a BITMAPINFO structure that specifies the desired format
  for the DIB data.

You can modify it like this:

```<code>win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), nil, bitmapInfo, 0)
pBits := make([]byte, imageSize)

win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), (*byte)(unsafe.Pointer(&pBits)), bitmapInfo, 0)
</code>```

Refer: Using GetDIBits to load a bitmap

Title: How should I use the GetDIBits function

Body:
var bitmap win.BITMAP
win.GetObject(win.HGDIOBJ(hBitmap), unsafe.Sizeof(bitmap), unsafe.Pointer(&bitmap))
var bmpInfo win.BITMAPINFO
bmpInfo.BmiHeader.BiSize = uint32(unsafe.Sizeof(Info.BmiHeader))
....................Width = width
....................Height = height
....................Planes = 1
....................BitCount = 24
....................Compression = win.BI_RGB
var hdc win.HDC
hdc = win.GetDC(0)
win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), bitmapInfo, nil, 0)
pBits := make([]byte, imageSize)
win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), bitmapInfo, (*byte)(unsafe.Pointer(&pBits)), 0)

use package github.com/lxn/win

First of all, we have done all the work before getting the GetDIBits function.

After that, I finally try to get the image data using the GetDIBits function, but it keeps returning 0.

I changed the data type of pBits to 'unsafe.Pointer' or '* byte' and tried it but it returned nil or 0.

How can I get the image data from the GetDIBits function?

Body:
I don't know much about Go language, but when you use GetDIBits, the position of parameters is incorrect.

lpvBits

A pointer to a buffer to receive the bitmap data. If this parameter is
  NULL, the function passes the dimensions and format of the bitmap to
  the BITMAPINFO structure pointed to by the lpbi parameter.

lpbmi

A pointer to a BITMAPINFO structure that specifies the desired format
  for the DIB data.

You can modify it like this:

win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), nil, bitmapInfo, 0)
pBits := make([]byte, imageSize)

win.GetDIBits(hdc, bitmap, 0, uint32(bitmap.BmHeight), (*byte)(unsafe.Pointer(&pBits)), bitmapInfo, 0)

Refer: Using GetDIBits to load a bitmap


问:
SQL populating added field rows with default value =0
I have table with three fields:

```<code>ID|DESCRIPTION |PRICE
01|Item 1      |2.95
02|Item 2      |5.95
</code>```

Now, more fields can be added to the end as supplier selling price.
What's the SQL query to default every existing item's selling price to 0 for this newly added field?

List item

答:
For sql Server:

```<code>ALTER TABLE YOURTBL
        ADD sellingprice numeric(20,4) NULL
        DEFAULT (0)
</code>```

My SQL

```<code>ALTER TABLE YOURTBL ADD COLUMN sellingprice decimal(20,4) NULL DEFAULT 0;
</code>```

Oracle

```<code>ALTER TABLE YOURTBL
ADD sellingprice  NUMBER(20,4) DEFAULT 0 NULL
</code>```

MSAccess

```<code>ALTER TABLE YOURTBL ADD COLUMN sellingprice NUMBER DEFAULT 0
</code>```

Body:
I have table with three fields:

ID|DESCRIPTION |PRICE
01|Item 1      |2.95
02|Item 2      |5.95

Now, more fields can be added to the end as supplier selling price.
What's the SQL query to default every existing item's selling price to 0 for this newly added field?

List item

Body:
For sql Server:

ALTER TABLE YOURTBL
        ADD sellingprice numeric(20,4) NULL
        DEFAULT (0)

My SQL

ALTER TABLE YOURTBL ADD COLUMN sellingprice decimal(20,4) NULL DEFAULT 0;

Oracle

ALTER TABLE YOURTBL
ADD sellingprice  NUMBER(20,4) DEFAULT 0 NULL

MSAccess

ALTER TABLE YOURTBL ADD COLUMN sellingprice NUMBER DEFAULT 0


问:
Asp.net MVC Core giving null checkbox data instead of all selected checkboxes on HTTPPost
I am trying to bind list of checkboxes.On Post Model showng the value of Job_Type as 0  .It should return all selected checkboxes.Which in my case not doing so .After hours of searching I havn't found any solution.

This is the relevent part of code in my view

```<code> <div class="form-group">
                    @foreach (var item in Model.Job_Type)
                    {
                        <input name="Job_Type" value="@item.valID" type="checkbox" checked="@item.IsChecked"/>
                        @item.text <br/>
                    }

                </div>
</code>```

My Controller:

```<code>  // GET: Jobs/Create
        public IActionResult Create()
        {
            NewJob newJob = new NewJob();
            List<CheckBoxModel> chkVisatype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1, text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
                new CheckBoxModel {valID=1,text="dd",IsChecked=true },
            };
            List<CheckBoxModel> chkJobtype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1,text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="tt",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
            };
            newJob.Job_Type = chkJobtype;
            newJob.Visa_Type = chkVisatype;
            return View(newJob);
        }

        // POST: Jobs/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("JobID,Job_Title,AddedDate,Primary_Technology,MPTJob_Length,MPTJobLengthSelection,SPTJob_Length,SPTJobLengthSelection,Job_Length,JobLengthSelection,Secondary_Technology,Description,PossibiltyForExtenshion,Email,CC_Email,URL,City,State,Country,ZipCode,Employment_Type,Job_Type,Compensation,JobExperienceLevel,Visa_Type")] NewJob newJob)
        {
            if (ModelState.IsValid)
            {
                newJob.AddedDate = DateTime.Now;
                _context.Add(newJob);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(newJob);
        }
</code>```

My Model:

```<code>
 public class CheckBoxModel
    {
        [Key]
        public int valID { get; set; }
        public string text { get; set; }
        public bool IsChecked { get; set; }
    }
 public class NewJob
    {

public List<CheckBoxModel> Job_Type { get; set; }
 }
</code>```

答:
If you check the request in browser Network tab, you would find only valID of checked options are sent via form data, like below. So Job_Type property is not successfully bound, which cause the issue.

If possible, you can dynamically generate expected data based on checked options, and then submit the data using jQuery AJAX etc.

In View page

```<code>@foreach (var item in Model.Job_Type)
{
    <input name="Job_Type" value="@item.valID" type="checkbox" checked="@item.IsChecked" />
    <span>@item.text</span>
    <br />
}
</code>```

Make ajax request

```<code>function myCreateFunc() {

    var job_title = $('input[name="Job_Title"]').val();

    var job_type = [];

    $('input[name="Job_Type"]:checked').each(function (i,el) {

        job_type.push({ "valID": $(el).val(), "text": $(el).next("span").text(), "IsChecked": true });
    });

    var job_data = { "Job_Title": job_title, "Job_Type": job_type };

    $.ajax({
            url: "/Home/Create",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(job_data),
            success: function (response) {
                //code logic here
            }
        });
}
</code>```

In controller action (with [FromBody] attribute)

```<code>[HttpPost]
public IActionResult Create([FromBody][Bind("JobID, Job_Title, Job_Type")]NewJob newJob) //in my testing sample, only define JobID, Job_Title, Job_Type properties
</code>```

Test Result

Body:
I am trying to bind list of checkboxes.On Post Model showng the value of Job_Type as 0  .It should return all selected checkboxes.Which in my case not doing so .After hours of searching I havn't found any solution.

This is the relevent part of code in my view

                    @foreach (var item in Model.Job_Type)
                    {
                        <input name="Job_Type" value="@item.valID" type="checkbox" checked="@item.IsChecked"/>
                        @item.text

                    }

My Controller:

  // GET: Jobs/Create
        public IActionResult Create()
        {
            NewJob newJob = new NewJob();
            List<CheckBoxModel> chkVisatype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1, text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
                new CheckBoxModel {valID=1,text="dd",IsChecked=true },
            };
            List<CheckBoxModel> chkJobtype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1,text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="tt",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
            };
            newJob.Job_Type = chkJobtype;
            newJob.Visa_Type = chkVisatype;
            return View(newJob);
        }

        // POST: Jobs/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("JobID,Job_Title,AddedDate,Primary_Technology,MPTJob_Length,MPTJobLengthSelection,SPTJob_Length,SPTJobLengthSelection,Job_Length,JobLengthSelection,Secondary_Technology,Description,PossibiltyForExtenshion,Email,CC_Email,URL,City,State,Country,ZipCode,Employment_Type,Job_Type,Compensation,JobExperienceLevel,Visa_Type")] NewJob newJob)
        {
            if (ModelState.IsValid)
            {
                newJob.AddedDate = DateTime.Now;
                _context.Add(newJob);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(newJob);
        }

My Model:

 public class CheckBoxModel
    {
        [Key]
        public int valID { get; set; }
        public string text { get; set; }
        public bool IsChecked { get; set; }
    }
 public class NewJob
    {

public List<CheckBoxModel> Job_Type { get; set; }
 }

Body:
If you check the request in browser Network tab, you would find only valID of checked options are sent via form data, like below. So Job_Type property is not successfully bound, which cause the issue.

If possible, you can dynamically generate expected data based on checked options, and then submit the data using jQuery AJAX etc.

In View page

@foreach (var item in Model.Job_Type)
{
    <input name="Job_Type" value="@item.valID" type="checkbox" checked="@item.IsChecked" />
    <span>@item.text</span>
    <br />
}

Make ajax request

function myCreateFunc() {

    var job_title = $('input[name="Job_Title"]').val();

    var job_type = [];

    $('input[name="Job_Type"]:checked').each(function (i,el) {

        job_type.push({ "valID": $(el).val(), "text": $(el).next("span").text(), "IsChecked": true });
    });

    var job_data = { "Job_Title": job_title, "Job_Type": job_type };

    $.ajax({
            url: "/Home/Create",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(job_data),
            success: function (response) {
                //code logic here
            }
        });
}

In controller action (with [FromBody] attribute)

[HttpPost]
public IActionResult Create([FromBody][Bind("JobID, Job_Title, Job_Type")]NewJob newJob) //in my testing sample, only define JobID, Job_Title, Job_Type properties

Test Result


问:
jsGrid: How to pass additional variables from javascript to php using ajax
I'm using jsGrid for my project. View here for original source code

I want to pass an additional variable call $user_session to use for mysql select query in fetch.php but failed. Below is what i have been trying.

```<code><script>

var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

//......

 controller: {
  loadData: function(){
   return $.ajax({
    type: "GET",
    url: "fetch_data.php",
    data: {user_session:user_session} //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   });
  },

 //......
</code>```

Here's the fetch.php file

```<code><?php

if($method == 'GET')
{
 $user_session = $_GET['user_session']; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $connect->prepare($query);
 $statement->execute($user_session); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
//......
?>
</code>```

What is the proper way to do this?

答:
Finally, i found a better way.

I can directly call $user_session inside fetch.php.

```<code><?php
require('user_session.php'); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
require('includes/db.php');

$method = $_SERVER['REQUEST_METHOD'];

if($method == 'GET')
{
 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $conn->prepare($query);
 $statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'ChildID'    => $row['ChildID'],
   'Name'  => $row['Name'],
   'BirthDate'   => $row['BirthDate'],
   'Gender'   => $row['Gender'],
   'StudyorWorking'   => $row['StudyorWorking'],
   'CourseorOccupation'   => $row['CourseorOccupation'],
   'Married'   => $row['Married']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
?>
</code>```

Body:
Finally, i found a better way.

I can directly call $user_session inside fetch.php.

<?php
require('user_session.php'); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
require('includes/db.php');

$method = $_SERVER['REQUEST_METHOD'];

if($method == 'GET')
{
 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $conn->prepare($query);
 $statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'ChildID'    => $row['ChildID'],
   'Name'  => $row['Name'],
   'BirthDate'   => $row['BirthDate'],
   'Gender'   => $row['Gender'],
   'StudyorWorking'   => $row['StudyorWorking'],
   'CourseorOccupation'   => $row['CourseorOccupation'],
   'Married'   => $row['Married']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
?>


答:
is the current field Price the one you want to default to 0 for each new record? is so, then run this

```<code>ALTER TABLE t1 ADD CONSTRAINT df_Name DEFAULT 0 FOR Price
</code>```

For a new field, this will create the field, and add 0 as the default

```<code>ALTER TABLE TableName ADD NewFieldName DECIMAL(10,4) DEFAULT(0)
</code>```

Title: SQL populating added field rows with default value =0

Body:
is the current field Price the one you want to default to 0 for each new record? is so, then run this

ALTER TABLE t1 ADD CONSTRAINT df_Name DEFAULT 0 FOR Price

For a new field, this will create the field, and add 0 as the default

ALTER TABLE TableName ADD NewFieldName DECIMAL(10,4) DEFAULT(0)


问:
How to add an additional endpoint to the AWS Amplify Express Server?
I've generated an REST express server with Amplify.

I tried adding to more endpoints to it:

```<code>// using serverless express
app.post('/myendpoint', function(req, res) {
  console.log('body: ', req.body)
  res.json(req.body)
});

// using serverless express
app.get('/myendpoint', function(req, res) {
  res.json({success: 'get call to my endpoint succeed!', url: req.url});
});

</code>```

After running amplify push I don't see these endpoints in the console, and I can't make requests to them via amplify.

The endpoints that were generated as part of the initial configuration work.

What is the correct way to add more REST endpoints?  I have a feeling that I'm missing some additional configuration step.

答: After deploy the API and function, to add additional path you should use "amplify update api"</p>

Body:
I've generated an REST express server with Amplify.

I tried adding to more endpoints to it:

// using serverless express
app.post('/myendpoint', function(req, res) {
  console.log('body: ', req.body)
  res.json(req.body)
});

// using serverless express
app.get('/myendpoint', function(req, res) {
  res.json({success: 'get call to my endpoint succeed!', url: req.url});
});

After running amplify push I don't see these endpoints in the console, and I can't make requests to them via amplify.

The endpoints that were generated as part of the initial configuration work.

What is the correct way to add more REST endpoints?  I have a feeling that I'm missing some additional configuration step.


问:
How to find dead code in a large react project?
In order to refactor a client-side project, i'm looking for a safe way to find (and delete) unused code.

What tools do you use to find unused/dead code in large react projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible.

Suggestions for general strategies/techniques (other than specific tools) are also appreciated.

Thank you

答:
Solution for Webpack: UnusedWebpackPlugin

I work on a big front-end React project (1100+ js files) and stumbled upon the same problem: how to find out which files are unused anymore?

I've tested the next tools so far:

findead

deadfile

unrequired

None of them really worked. One of the reason is that we use "not standard" imports. In additional to the regular relative paths in our imports we also use paths resolved by the webpack resolve feature which basically allows us to use neat import 'pages/something' rather than cumbersome import '../../../pages/something'.

UnusedWebpackPlugin

So here is the solution I've finally come across thanks to Liam O'Boyle (elyobo) @GitHub:
https://github.com/MatthieuLemoine/unused-webpack-plugin

It's a webpack plugin so it's gonna work only if your bundler is webpack.

I personaly find it good that you don't need to run it separately but instead it's built into your building process throwing warnings when something is not ok.

Our research topic: https://github.com/spencermountain/unrequired/issues/6


问:
BeautifulSoup error while accesing a td inside a tr
this is the HTML that I'm trying to access, But am unable to access the 2nd td inside the tr.

Below is the HTML source code:

  22184
  Abercrombie, Dave J.
  Feb 14, 2020
  F0517CC - Fld 05 West Section C

  14075
  Abeyta, Patricia F.
  Feb 28, 2018
  F1228 - JMC Packing House Plantation Management

  43296
  Acevedo, Patricia W.
  Jun 23, 2017
  F0517CC - Fld 05 West Section C

  45023
  Ackerman, Brittany B.
  Nov 7, 2017
  DL-50 - DL-50

  11032
  Acosta, Ronald G.
  Jan 16, 1992
  DL-42 - DL-42

  72974
  Acton, Leslie F.
  Sep 1, 2011
  F0518CB - Fld 5 East Sec B

  71894
  Adams, Frances G.
  Apr 2, 2018
  F1007 - Spray Department

  32997
  Adams, Susan M.
  Aug 31, 2018
  F1062 - Corp S16 Planation Management Hourlies

  10990
  Adams, Michael B.
  Aug 30, 2018
  DL-04 - DL-04

  79358
  Adams, Lisa B.
  Apr 30, 2019
  C1155 - C1155

```
</div>
</div>
</p>

<p>And here's my code:</p>

<pre class="lang-py prettyprint-override"><code>steven=soup.find("table",{"class":"table sticky-table-header table-hover ng-isolate-scope resize"})
        for row in steven.tbody.find_all('tr'):
            print(row.td.text)
</code>```

答:
The issue that you are searching with the wrong attributes which is actually not within the source code at all.

Below you can achieve your goal:

soup = BeautifulSoup(html, 'html.parser')

count = 0
for item in soup.findAll("tr", {"class": "hand_cursor ng-scope"}):
    for td in item.findAll("td")[1]:
        count += 1
        print(td)
print(f"Count is: {count}")
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>Abercrombie, Dave J.
Abeyta, Patricia F.
Acevedo, Patricia W.
Ackerman, Brittany B.
Acosta, Ronald G.
Acton, Leslie F.
Adams, Frances G.
Adams, Susan M.
Adams, Michael B.
Adams, Lisa B.
Count is: 10
</code>```

Body:
this is the HTML that I'm trying to access, But am unable to access the 2nd td inside the tr.

Below is the HTML source code:

  22184
  Abercrombie, Dave J.
  Feb 14, 2020
  F0517CC - Fld 05 West Section C

  14075
  Abeyta, Patricia F.
  Feb 28, 2018
  F1228 - JMC Packing House Plantation Management

  43296
  Acevedo, Patricia W.
  Jun 23, 2017
  F0517CC - Fld 05 West Section C

  45023
  Ackerman, Brittany B.
  Nov 7, 2017
  DL-50 - DL-50

  11032
  Acosta, Ronald G.
  Jan 16, 1992
  DL-42 - DL-42

  72974
  Acton, Leslie F.
  Sep 1, 2011
  F0518CB - Fld 5 East Sec B

  71894
  Adams, Frances G.
  Apr 2, 2018
  F1007 - Spray Department

  32997
  Adams, Susan M.
  Aug 31, 2018
  F1062 - Corp S16 Planation Management Hourlies

  10990
  Adams, Michael B.
  Aug 30, 2018
  DL-04 - DL-04

  79358
  Adams, Lisa B.
  Apr 30, 2019
  C1155 - C1155

And here's my code:

steven=soup.find("table",{"class":"table sticky-table-header table-hover ng-isolate-scope resize"})
        for row in steven.tbody.find_all('tr'):
            print(row.td.text)

Body:
The issue that you are searching with the wrong attributes which is actually not within the source code at all.

Below you can achieve your goal:

soup = BeautifulSoup(html, 'html.parser')

count = 0
for item in soup.findAll("tr", {"class": "hand_cursor ng-scope"}):
    for td in item.findAll("td")[1]:
        count += 1
        print(td)
print(f"Count is: {count}")

Output:

Abercrombie, Dave J.
Abeyta, Patricia F.
Acevedo, Patricia W.
Ackerman, Brittany B.
Acosta, Ronald G.
Acton, Leslie F.
Adams, Frances G.
Adams, Susan M.
Adams, Michael B.
Adams, Lisa B.
Count is: 10


问:
WinForms multi-threaded databinding scenario, best practice?
I'm currently designing/reworking the databinding part of an application that makes heavy use of winforms databinding and updates coming from a background thread (once a second on > 100 records).

Let's assume the application is a stock trading application, where a background thread monitors for data changes and putting them onto the data objects. These objects are stored in a BindingList<> and implement INotifyPropertyChanged to propagate the changes via databinding to the winforms controls.
Additionally the data objects are currently marshalling the changes via WinformsSynchronizationContext.Send to the UI thread.
The user is able to enter some of the values in the UI, which means that some values can be changed from both sides. And the user values shouldn't be overritten by updates.

So there are several question coming to my mind:

Is there a general design-guildline how to do that (background updates in databinding)?

When and how to marshal on the UI thread?

What is the best way of the background thread to interact with
binding/data objects?

Which classes/Interfaces should be used? (BindingSource, ...)

...

The UI doesn't really know that there is a background thread, that updates the control, and as of my understanding in databinding scenarios the UI shouldn't know where the data is coming from... You can think of the background thread as something that pushes data to the UI, so I'm not sure if the backgroundworker is the option I'm searching for.

Sometimes you want to get some UI response during an operation in the data-/business object (e.g. setting the background during recalculations). Raising a propertychanged on a status property which is bound to the background isn't enough, as the control get's repainted after the calculation has finished? My idea would be to hook on the propertychanged event and call .update() on the control...
Any other ideas about that?

答:
This is a problem that I solved in Update Controls. I bring this up not to suggest you rewrite your code, but to give you some source to look at for ideas.

The technique that I used in WPF was to use Dispatcher.BeginInvoke to notify the foreground thread of a change. You can do the same thing in Winforms with Control.BeginInvoke. Unfortunately, you have to pass a reference to a Form object into your data object.

Once you do, you can pass an Action into BeginInvoke that fires PropertyChanged. For example:

```<code>_form.BeginInvoke(new Action(() => NotifyPropertyChanged(propertyName))) );
</code>```

You will need to lock the properties in your data object to make them thread-safe.

OwnerDisplayName: Martin Moser

LastEditorDisplayName: Martin Moser

Body:
This is a problem that I solved in Update Controls. I bring this up not to suggest you rewrite your code, but to give you some source to look at for ideas.

The technique that I used in WPF was to use Dispatcher.BeginInvoke to notify the foreground thread of a change. You can do the same thing in Winforms with Control.BeginInvoke. Unfortunately, you have to pass a reference to a Form object into your data object.

Once you do, you can pass an Action into BeginInvoke that fires PropertyChanged. For example:

_form.BeginInvoke(new Action(() => NotifyPropertyChanged(propertyName))) );

You will need to lock the properties in your data object to make them thread-safe.

OwnerDisplayName: Michael L Perry

ContentLicense: CC BY-SA 2.5


问:
Custom psobject truncating the results that are added using add-member
I have two clusters, cluster1 with 5 nodes and cluster2 with 4 nodes. With below script the cluster1 output is getting truncated. How to address this problem?

```<code>PS C:\WINDOWS\system32> $temp = @()
PS C:\WINDOWS\system32> foreach($i in @('cluster1','cluster2')){
>> $pso = New-Object -TypeName psobject
>> $cluster = Get-Cluster $i | select name
>> $cluster_nodes = Get-ClusterNode -Cluster $cluster.Name | select name
>> $pso | Add-Member -MemberType NoteProperty -Name 'Cluster' -Value $cluster.Name
>> $pso | Add-Member -MemberType NoteProperty -Name 'Cluster_nodes' -Value $cluster_nodes.name
>> $temp += $pso
>> }
</code>```

Output:

```<code>PS C:\WINDOWS\system32> $temp

Cluster         Cluster_nodes
-------         -------------
cluster1        {node1, node2, node3, node4...}
cluster2        {node1, node2, node3, node4}
</code>```

答:
AdminOfThings provided the crucial pointer in a comment on the question:

Preference variable $FormatEnumerationLimit controls how many elements of a collection-valued property to display in formatted output.

E.g, $FormatEnumerationLimit = 2; [pscustomobject] @{ prop = 1, 2, 3 } prints (at most) 2 elements from .prop's value and hints at the existence of more with ...; e.g., {1, 2...}).

The default value is 4, but you can set it to an arbitrary positive value.

-1 places no limit on how many values are displayed, but note that with tabular output (implicit or explicit Format-Table) the column width may still truncate the value list.

Pipe to Format-List to ensure that all values are shown.

Caveat: Due to a bug as of PowerShell [Core] 7.0, setting $FormatEnumerationLimit is only effective in the global scope - see this GitHub issue.

As a workaround in scripts, modify the global copy, $global:FormatEnumerationLimit, temporarily (restore it to the original value before exiting the script).

Body:
I have two clusters, cluster1 with 5 nodes and cluster2 with 4 nodes. With below script the cluster1 output is getting truncated. How to address this problem?

PS C:\WINDOWS\system32> $temp = @()
PS C:\WINDOWS\system32> foreach($i in @('cluster1','cluster2')){
>> $pso = New-Object -TypeName psobject
>> $cluster = Get-Cluster $i | select name
>> $cluster_nodes = Get-ClusterNode -Cluster $cluster.Name | select name
>> $pso | Add-Member -MemberType NoteProperty -Name 'Cluster' -Value $cluster.Name
>> $pso | Add-Member -MemberType NoteProperty -Name 'Cluster_nodes' -Value $cluster_nodes.name
>> $temp += $pso
>> }

Output:

PS C:\WINDOWS\system32> $temp

Cluster         Cluster_nodes
-------         -------------
cluster1        {node1, node2, node3, node4...}
cluster2        {node1, node2, node3, node4}


问:
JavaScript firing too many events?
The handle mousemove events are amongst 3
s which are nested inside each other. Can't seem to find the issue which is causing too many events to get fired.

(function() {
  var boxes = [
    document.getElementById("box1"),
    document.getElementById("box2"),
    document.getElementById("box3"),
  ];

  boxes[0].addEventListener(
    "mousemove", function(event) { console.log("Box 1"); }
  );
  boxes[1].addEventListener(
    "mousemove", function(event) { console.log("Box 2"); }
  );
  boxes[2].addEventListener(
    "mousemove", function(event) { console.log("Box 3"); }
  );
})();

```

答:
If you just want the events to fire when you hover then that event is called 'mouseover'

boxes[0].addEventListener("mouseover", function(event) {
  console.log("Box 1");
});```

Title: JavaScript firing too many events?


问:
ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored
I am using ubuntu 12.04. Every time I start my bash terminal and every time when I finish typing a command(and press enter) , I get this message:

ERROR: ld.so: object '/usr/lib/liblunar-calendar-preload.so' from
  LD_PRELOAD cannot be preloaded: ignored.

It is weird.
So what is the environment variable LD_PRELOAD used for? And what is the going on behind the scene?

Thanks.

答:
You can check /etc/ld.so.preload file content

I fix it by:

echo "" > /etc/ld.so.preload


问:
How do you map routes according to the following schema?
How do you map this url

/Topic/topicName/action?topicId=someInt

Where Topic is the controller name (this is const - it always reads "Topic"),

topicName is being ignored

action is action name,

and someInt is the topicId argument for "action".

Here are couple of examples:

/Topic/c-sharp/AddQuestion?topicId=1

To invoke:

Controller: Topic

Action: AddQuestion

topicId =1

Where this is the action's singnature in TopicConroller

```<code>public ActionResult AddQuestion(int topicId)
</code>```

Another example:

/Topic/MySql-queries/AddSubTopic?topicId=1

To invoke:

Controller: Topic

Action: AddSubTopic

topicId =1

Where this is the action's singnature in TopicConroller

```<code>public ActionResult AddSubTopic(int topicId)
</code>```

etc. (all actions in Topic controller receive only one argument - that is the topic's id).

答:
I found this tool route debuger very useful to test my way around to the perfect route

http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

it has also a nuget package now.
Might help for further scenarios, too...

Body:
How do you map this url

/Topic/topicName/action?topicId=someInt

Where Topic is the controller name (this is const - it always reads "Topic"),

topicName is being ignored

action is action name,

and someInt is the topicId argument for "action".

Here are couple of examples:

/Topic/c-sharp/AddQuestion?topicId=1

To invoke:

Controller: Topic

Action: AddQuestion

topicId =1

Where this is the action's singnature in TopicConroller

public ActionResult AddQuestion(int topicId)

Another example:

/Topic/MySql-queries/AddSubTopic?topicId=1

To invoke:

Controller: Topic

Action: AddSubTopic

topicId =1

Where this is the action's singnature in TopicConroller

public ActionResult AddSubTopic(int topicId)

etc. (all actions in Topic controller receive only one argument - that is the topic's id).


问:
Error check user input with integers in C
I am trying to take RGB codes entered by a user in the format #1, #2, #3. I error check the input to make sure it matches the ', ' format and can extract the numbers from the string. However, I am having trouble checking if the input is a number after that.

Ex: If the user enters: 255, 0, 0f the program still runs.

Any help would be appreciated!

```<code>char input[100];
printf("Enter RGB code \n");
scanf(" %[^\n]s", input);

//function to error check ', ' format

int c1,c2,c3;
//formats the input into three ints.
sscanf(input, "%d, %d, %d\n", &c1,&c2,&c3);
</code>```

I just need to check if these are in fact integers

答:
If you want to do any serious format checking, I'd suggest you incorporate PCRE into your code. Then you can simply get a line (more robustly than you currently do (scanf is can be unreliable), such as the one from this answer), then use a regex like:

```<code>^\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*$
</code>```

to both check and extract the fields you desire, with each field being one to three (inclusive) digits.

You'll probably then want to check that the extracted fields are less than 256 but that should be relatively easy. Or, if you want all that done by the regex itself, you can replace each occurrence of (\d{1,3}) in the regex above, with:

```<code>(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])
</code>```

This guarantees a 0..255 number in the field rather than an arbitrary one-to-three digit number, using the following possibilities:

```<code>0          : 0
[1-9]\d?   : 1-99
1\d\d      : 100-199
2[0-4]\d   : 200-249
25[0-5]    : 250-255
</code>```

Body:
I am trying to take RGB codes entered by a user in the format #1, #2, #3. I error check the input to make sure it matches the ', ' format and can extract the numbers from the string. However, I am having trouble checking if the input is a number after that.

Ex: If the user enters: 255, 0, 0f the program still runs.

Any help would be appreciated!

char input[100];
printf("Enter RGB code \n");
scanf(" %[^\n]s", input);

//function to error check ', ' format

int c1,c2,c3;
//formats the input into three ints.
sscanf(input, "%d, %d, %d\n", &c1,&c2,&c3);

I just need to check if these are in fact integers

Body:
If you want to do any serious format checking, I'd suggest you incorporate PCRE into your code. Then you can simply get a line (more robustly than you currently do (scanf is can be unreliable), such as the one from this answer), then use a regex like:

^\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*$

to both check and extract the fields you desire, with each field being one to three (inclusive) digits.

You'll probably then want to check that the extracted fields are less than 256 but that should be relatively easy. Or, if you want all that done by the regex itself, you can replace each occurrence of (\d{1,3}) in the regex above, with:

(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])

This guarantees a 0..255 number in the field rather than an arbitrary one-to-three digit number, using the following possibilities:

0          : 0
[1-9]\d?   : 1-99
1\d\d      : 100-199
2[0-4]\d   : 200-249
25[0-5]    : 250-255


问:
AWS Windows EC2 Instance is not connecting to internet
I am having a EC2 Windows instance in my AWS account. I have used 2019 base to create my machine, I am able to connect to my machine and I do not have internet connectivity in the instance. I am new to AWS, kindly provide your inputs to resolve the issue.</p>

答:
As you said you able to connect to your instance that means your instance have public IP.
I think your instance able to connect internet.
I guess you are facing issue when using IE browser? That why you think your instance not able to connect internet. Is that correct? </p>


问:
Views are not reflecting any changes whatsoever, when done programmatically
```
The basic view hierarchy is this:
secondActivity
    linearLayout(LinearLayout)
        constLayout(ConstraintLayout)
            textbox(TextView)
            image(ImageView)
            image2
            image3
            ...
```

The textbox TextView has visibility GONE, and goal is to make it VISIBLE on clicking other visible siblings, change some colors and text, and when clicked again it must be invisible again and reverse all changes.
Cant understand whatever it is that am missing. I have checked many older projects in which I did the same thing and cant find any visible differences as to why this code is not working now.

secondActivity.java

```<code>public class secondActivity extends Activity {

    public boolean isTextBoxHidden;
    public ConstraintLayout constLayout;
    public TextView textbox;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        constLayout = findViewById(R.id.constLayout);
        textbox = findViewById(R.id.textbox);
        isTextBoxHidden = false;

        // SETTING UP LISTENER
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isTextBoxHidden) {
                    constLayout.setBackgroundColor(Color.BLACK);  //setting color on previously
                    v.setBackgroundColor(Color.BLACK);            //setting color on visible view

                    textbox.setText("whatever");
                    textbox.setVisibility(View.VISIBLE);  //was gone
                    isTextBoxHidden = true;
                }
                else {
                    textbox.setVisibility(View.GONE);     //hide again
                    constLayout.setBackgroundColor(Color.WHITE);
                    v.setBackgroundColor(Color.WHITE);
                    isTextBoxHidden = false;
                }
            }
        };

        // INSERTING LISTENERS into all children
        for(int i=0; i<constLayout.getChildCount(); i++) {
                constLayout.getChildAt(i).setOnClickListener(clickListener);
        }
    }
}
</code>```

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".secondActivity">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/constLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">

        <TextView
            android:id="@+id/textbox"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="example"

            android:visibility="gone"

            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <ImageButton
            android:id="@+id/image"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:src="@drawable/example"

            android:clickable="true"

            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"/>

    </android.support.constraint.ConstraintLayout>
</LinearLayout>
```

答:
I can't see where you're setting textbox reference, so maybe that's a clue.

Edit:
Did compiled that example you have provided and everything works correctly, but i assume that [...] gone again for good meant you probably want this to be one shot  action so instead of boolean just use Boolean and compare it to null.

Edit:
On the second thought you can just remove isTextBoxHidden = false; in else branch

Body:
The basic view hierarchy is this:
secondActivity
    linearLayout(LinearLayout)
        constLayout(ConstraintLayout)
            textbox(TextView)
            image(ImageView)
            image2
            image3
            ...

The textbox TextView has visibility GONE, and goal is to make it VISIBLE on clicking other visible siblings, change some colors and text, and when clicked again it must be invisible again and reverse all changes.
Cant understand whatever it is that am missing. I have checked many older projects in which I did the same thing and cant find any visible differences as to why this code is not working now.

secondActivity.java

public class secondActivity extends Activity {

    public boolean isTextBoxHidden;
    public ConstraintLayout constLayout;
    public TextView textbox;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        constLayout = findViewById(R.id.constLayout);
        textbox = findViewById(R.id.textbox);
        isTextBoxHidden = false;

        // SETTING UP LISTENER
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isTextBoxHidden) {
                    constLayout.setBackgroundColor(Color.BLACK);  //setting color on previously
                    v.setBackgroundColor(Color.BLACK);            //setting color on visible view

                    textbox.setText("whatever");
                    textbox.setVisibility(View.VISIBLE);  //was gone
                    isTextBoxHidden = true;
                }
                else {
                    textbox.setVisibility(View.GONE);     //hide again
                    constLayout.setBackgroundColor(Color.WHITE);
                    v.setBackgroundColor(Color.WHITE);
                    isTextBoxHidden = false;
                }
            }
        };

        // INSERTING LISTENERS into all children
        for(int i=0; i<constLayout.getChildCount(); i++) {
                constLayout.getChildAt(i).setOnClickListener(clickListener);
        }
    }
}

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".secondActivity">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/constLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">

        <TextView
            android:id="@+id/textbox"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="example"

            android:visibility="gone"

            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <ImageButton
            android:id="@+id/image"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:src="@drawable/example"

            android:clickable="true"

            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"/>

    </android.support.constraint.ConstraintLayout>
</LinearLayout>


问:
Command output to console & grep to assert success status
I am running a python script which creates google cloud dataflow job. The command looks like this

```<code>python -m runpipline <command_options ...>
</code>```

The output of this command gives if the job was created successfully or not. In case of successful creation, the command ends like this

```<code>INFO:apache_beam.runners.dataflow.internal.apiclient:Create job: <Job
 createTime: '2020-02-18T20:39:44.885028Z'
 currentStateTime: '1970-01-01T00:00:00Z'
 id: '2020-02-18_12_39_43-1111111111111111111'
 location: 'us-central1'
 name: '<name_of_the_job>'
 projectId: '<project_name>'
 stageStates: []
 startTime: '2020-02-18T20:39:44.885028Z'
 steps: []
 tempFiles: []
 type: TypeValueValuesEnum(JOB_TYPE_STREAMING, 2)>
INFO:apache_beam.runners.dataflow.internal.apiclient:Created job with id: [2020-02-18_12_39_43-1111111111111111111]
INFO:apache_beam.runners.dataflow.internal.apiclient:To access the Dataflow monitoring console, please navigate to https://console.cloud.google.com/dataflow/jobsDetail/locations/us-central1/jobs/2020-02-18_12_39_43-1111111111111111111?project_name%
</code>```

This script is being run by github action and is using ubunt-latest image. What I want to do is

The output of the command should be print to console AND I should be able to extract the job_id from the command

If I am able to extract job id, i should be able to do next X command.

If job_id doesn't exist then I should fail the script.

I used grep to do this python -m runpipline <command_options ...> | grep -E "\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2}-\d{19}\]" but this would stop me from outputing to console. Also, It just gives me the line which matches this criteria. not the job id. So not sure what to do

答:
Would you please try the following:

```<code>id=$(python -m runpipline <command_options ...> | tee /dev/tty | grep -Po "id:\s*\[\K\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2}-\d{19}(?=])")

if [[ -n $id ]]; then
    : # do your command here
else
    echo "grep failed"
fi
</code>```

It searches the python output for the id preceded by a string id: [ and followed by ].

Thanks to the lookaround assertion, only the id portion is assigned to the variable id.

You can continue your task by using the result.

[EDIT]

If your grep does not support the -P option, please try the following instead:

```<code>id=$(python -m runpipline <command_options ...> | tee /dev/tty | grep -Eo "id:[[:blank:]]*\[[[:digit:]]{4}(-[[:digit:]]{2}){2}(_[[:digit:]]{2}){3}-[[:digit:]]{19}]")

if [[ -n $id ]]; then
    id=$(sed 's/^id:[[:blank:]]*\[\(.\+\)]/\1/' <<< "$id")      # remove leading and trailing extra substrings
    echo "grep passed. Id=$id"
else
    echo "grep failed"
fi
</code>```

Body:
I am running a python script which creates google cloud dataflow job. The command looks like this

python -m runpipline <command_options ...>

The output of this command gives if the job was created successfully or not. In case of successful creation, the command ends like this

INFO:apache_beam.runners.dataflow.internal.apiclient:Create job: <Job
 createTime: '2020-02-18T20:39:44.885028Z'
 currentStateTime: '1970-01-01T00:00:00Z'
 id: '2020-02-18_12_39_43-1111111111111111111'
 location: 'us-central1'
 name: '<name_of_the_job>'
 projectId: '<project_name>'
 stageStates: []
 startTime: '2020-02-18T20:39:44.885028Z'
 steps: []
 tempFiles: []
 type: TypeValueValuesEnum(JOB_TYPE_STREAMING, 2)>
INFO:apache_beam.runners.dataflow.internal.apiclient:Created job with id: [2020-02-18_12_39_43-1111111111111111111]
INFO:apache_beam.runners.dataflow.internal.apiclient:To access the Dataflow monitoring console, please navigate to https://console.cloud.google.com/dataflow/jobsDetail/locations/us-central1/jobs/2020-02-18_12_39_43-1111111111111111111?project_name%

This script is being run by github action and is using ubunt-latest image. What I want to do is

The output of the command should be print to console AND I should be able to extract the job_id from the command

If I am able to extract job id, i should be able to do next X command.

If job_id doesn't exist then I should fail the script.

I used grep to do this python -m runpipline <command_options ...> | grep -E "\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2}-\d{19}\]" but this would stop me from outputing to console. Also, It just gives me the line which matches this criteria. not the job id. So not sure what to do

Body:
Would you please try the following:

id=$(python -m runpipline <command_options ...> | tee /dev/tty | grep -Po "id:\s*\[\K\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2}-\d{19}(?=])")

if [[ -n $id ]]; then
    : # do your command here
else
    echo "grep failed"
fi

It searches the python output for the id preceded by a string id: [ and followed by ].

Thanks to the lookaround assertion, only the id portion is assigned to the variable id.

You can continue your task by using the result.

[EDIT]

If your grep does not support the -P option, please try the following instead:

id=$(python -m runpipline <command_options ...> | tee /dev/tty | grep -Eo "id:[[:blank:]]*\[[[:digit:]]{4}(-[[:digit:]]{2}){2}(_[[:digit:]]{2}){3}-[[:digit:]]{19}]")

if [[ -n $id ]]; then
    id=$(sed 's/^id:[[:blank:]]*\[\(.\+\)]/\1/' <<< "$id")      # remove leading and trailing extra substrings
    echo "grep passed. Id=$id"
else
    echo "grep failed"
fi


答:
```<code>ALTER TABLE Table_Name
ADD supplier_selling_price INT NULL DEFAULT (0)
</code>```

From DEFAULT Key word you can assign a default value to existing lines of newly added column. Please change the data type as per your need. (int, numeric, decimal)

Body:
I have table with three fields:

ID|DESCRIPTION |PRICE
01|Item 1      |2.95
02|Item 2      |5.95

Now, more fields can be added to the end as supplier selling price.
What's the SQL query to default every existing item's selling price to 0 for this newly added field?

List item

Body:
ALTER TABLE Table_Name
ADD supplier_selling_price INT NULL DEFAULT (0)

From DEFAULT Key word you can assign a default value to existing lines of newly added column. Please change the data type as per your need. (int, numeric, decimal)


问:
Hide/Show components in react native
I'm really new to React Native and I'm wondering how can I hide/show a component.

Here's my test case:

```<code><TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>
</code>```

I have a TextInput component, what I want is to show the TouchableHighlight when the input gets the focus, then hide the TouchableHighlight when the user press the cancel button.

I don´t know how to "access" the TouchableHighlight component in order to hide/show it inside of my functions showCancel/hideCancel.

Also, how can I hide the button from the very beginning?

答:
The following example is coding in typescript with Hooks.</p>

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

........

const App = () => {

   const [showScrollView, setShowScrollView] = useState(false);

   ......

   const onPress = () => {
    // toggle true or false
    setShowScrollView(!showScrollView);
  }

  ......

      </MapboxGL.ShapeSource>
        <View>{showScrollView ? (<DetailsScrollView />) : null}</View>
      </MapboxGL.MapView>
  ......

}
</code>```

Title: Hide/Show components in react native

Body:
I'm really new to React Native and I'm wondering how can I hide/show a component.

Here's my test case:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>

I have a TextInput component, what I want is to show the TouchableHighlight when the input gets the focus, then hide the TouchableHighlight when the user press the cancel button.

I don´t know how to "access" the TouchableHighlight component in order to hide/show it inside of my functions showCancel/hideCancel.

Also, how can I hide the button from the very beginning?

Body:
The following example is coding in typescript with Hooks.

import React, { useState, useEffect } from "react";

........

const App = () => {

   const [showScrollView, setShowScrollView] = useState(false);

   ......

   const onPress = () => {
    // toggle true or false
    setShowScrollView(!showScrollView);
  }

  ......

      </MapboxGL.ShapeSource>
        <View>{showScrollView ? (<DetailsScrollView />) : null}</View>
      </MapboxGL.MapView>
  ......

}


问:
How to select and change value of table cell with jQuery?
How do I change the content of the cell containing the 'c' letter in the HTML sample using jQuery?

```<code><table id="table_header">
<tr>
   <td>a</td>
   <td>b</td>
   <td>c</td>
</tr>
</table>
</code>```

Thanks.

答:
I wanted to change the column value in a specific row. Thanks to above answers
and after some searching able to come up with below,</p>
```<code>var dataTable = $("#yourtableid");
var rowNumber = 0;
var columnNumber= 2;
dataTable[0].rows[rowNumber].cells[columnNumber].innerHTML = 'New Content';
</code>```

Body:
How do I change the content of the cell containing the 'c' letter in the HTML sample using jQuery?

   a
   b
   c

Thanks.

Body:
I wanted to change the column value in a specific row. Thanks to above answers
and after some searching able to come up with below,

var dataTable = $("#yourtableid");
var rowNumber = 0;
var columnNumber= 2;
dataTable[0].rows[rowNumber].cells[columnNumber].innerHTML = 'New Content';


问:
Unused arguments of sarima()
When I am trying to run

```<code>sarima(log(AirPassengers),0,1,1,0,1,1,12)
</code>```

It returns

Error in sarima(log(AirPassengers), 0, 1, 1, 0, 1, 1, 12) :
    unused arguments (1, 1, 12)

The dataset is under the package of astsa package. The data type is ts type.

```<code>class(AirPassengers)
[1] "ts"
</code>```

I don't know the reason of this error. I ran the same code in DataCamp, it works.

答:
A few general comments:

You can fit SARIMA models with base R's arima function; there is really no need to load an additional package for fitting basic SARIMA models.

The AirPassengers dataset is part of base R, not part of astsa.

In arima, you specify the non-seasonal and seasonal parameters through function arguments order and seasonal, respectively. You can find detailed information what arguments the function takes if you type ?arima into an R terminal.

For example, to specify a SARIMA(0,1,1)(0,1,1)12 model you do

arima(log(AirPassengers), order = c(0,1,1), seasonal = list(order = c(0,1,1), period = 12))
```

<p>Note that the <code>seasonal</code> argument is a <code>list</code> with the two elements <code>order</code> (denoting the order of seasonal AR terms, order of seasonal differencing, and order of seasonal MA terms) and <code>period</code>.</p>

<hr>

<p>The error you're seeing with <code>astsa::sarima</code> seems to stem from too many arguments; check that you really have 3 non-seasonal arguments, 3 (optional) seasonal arguments, and one (optional) period.</p>

<p>Above model would be</p>

<pre class="lang-r prettyprint-override"><code>sarima(log(AirPassengers), 0, 1, 1, 0, 1, 1, 12)
</code>```

which produces the same fit results as arima (in fact sarima just calls arima "under the hood").

Title: Unused arguments of sarima()

Body:
When I am trying to run

sarima(log(AirPassengers),0,1,1,0,1,1,12)

It returns

Error in sarima(log(AirPassengers), 0, 1, 1, 0, 1, 1, 12) :
    unused arguments (1, 1, 12)

The dataset is under the package of astsa package. The data type is ts type.

class(AirPassengers)
[1] "ts"

I don't know the reason of this error. I ran the same code in DataCamp, it works.

Body:
A few general comments:

You can fit SARIMA models with base R's arima function; there is really no need to load an additional package for fitting basic SARIMA models.

The AirPassengers dataset is part of base R, not part of astsa.

In arima, you specify the non-seasonal and seasonal parameters through function arguments order and seasonal, respectively. You can find detailed information what arguments the function takes if you type ?arima into an R terminal.

For example, to specify a SARIMA(0,1,1)(0,1,1)12 model you do

arima(log(AirPassengers), order = c(0,1,1), seasonal = list(order = c(0,1,1), period = 12))

Note that the seasonal argument is a list with the two elements order (denoting the order of seasonal AR terms, order of seasonal differencing, and order of seasonal MA terms) and period.

The error you're seeing with astsa::sarima seems to stem from too many arguments; check that you really have 3 non-seasonal arguments, 3 (optional) seasonal arguments, and one (optional) period.

Above model would be

sarima(log(AirPassengers), 0, 1, 1, 0, 1, 1, 12)

which produces the same fit results as arima (in fact sarima just calls arima "under the hood").